Thursday, May 26, 2011

Dynamic Behavior Addition

Suppose you are building a system that sorts a set of numbers. User has option to choose various algorithms. You allow 3rd party sorting algorithms to be added to system on the fly without needing application restart. All this facilities using a UI. Is it possible to do it? What would be the best way to do it?

My Answer (I have not tried it, but believe it should work.)
1. Create an interface SortAlgorithm containing sort (List) method.
2. Publish its source and .class file.
3. Design a table SortAlgorithms with two columns algo_name and class_name.
4. Provide a UI for 3rd party vendors to upload their concrete implementation for SortAlgorithm.
5. Put the .class file of 4 in class-path and create an entry in the table.
6. Your UI would start listing the new algorithm picked up from the same table.
7. If user chooses new algorithm, load its corresponding class with its name in that table.
8. Your code was always using SortAlgorithm interface so it never needed changes.

Does this approach makes sense to add new behaviors in the system?

3 comments:

  1. How will you load the class runtime? entry of all sort classes is in classpath, it means all classes are available, how and where do you make a choice in your code.

    Also how do you make sure that the concrete implementation submitted by user compiles well, dont you think you have to compile complete application to verify compatibility of the user submitted class with your application. What happens If I submit a mischevious code, DOES this use case takes care of all this?

    ReplyDelete
  2. I intended byte-code for the class would be uploaded. When user uploads the compiled file, he also specifies the name of the class. When the class file is copied in class-path, we would be able to load it using the class-name available in table and java API class.forName().
    But, yes it does not take into account malicious code-execution.

    ReplyDelete
  3. also, will a class file compiled in say java6 be compatible with jvm version 5?

    ReplyDelete