Friday, April 20, 2007

Simple little things in programming - Part 1

No I am not a guru and have no jurisdiction to teach good programming skills and patterns. But its a good practice to keep the code clean and provide room for scalability. I have seen failed but very well written codes as well as very successful but piece of $%!^. Don't use badly written code as a tool for the job security. I think I should start some simple little things in Java programming which is not too much to do but adds to the quality. This sequence is in no effort to discuss complex pattern, or may be later. Your comments are most welcome.

# Use of Reflection to eliminate if-then-else:
==============================================
If-then-else is one of the very basic and one of the most powerful syntax provided by the programming languages. Its also a source of unmanageable, lengthy and cumbersome codes. Most of the patterns defined in GoF and beyond try to address the If-Then-Else world. Java Reflection on the other hand is one of the building blocks of most of the patterns. It provides a very strong set of APIs which can make your code very scalable and easy to maintain. Lets take an example:


# Sample(1):
ReturnType rT = null;
if (condition1) {
rT = callMethod1 (param1, param2);
} else if (condition2) {
rT = callMethod2 (param1, param3);
} else {
rT = callMethod3 (param3);
}


The callMethodX () takes different set of parameters but either returns the same Object or something which can be made more generic. In most cases, the params are owned by the same class. Even though these params have different scopes but together they form one logical set. The problem with the above code is it is not scalable. The invoker has a strong dependency on these call methods. New call methods can be added but they can not be used unless the section of invoker is updated. Lets take another sample:


# Sample(2):
import java.lang.reflect.Method;

public class ClassName {
..
public ReturnType invoker (param1, param2, param3) { // -- scope can change
Object [] inputs = {param1, param2, param3};
Class [] params = new Class [3];
parmas [0] = String.class;
params [1] = Boolean.class;
params [2] = String.class;
ClassName theClass = new ClassName ();
Class thisClass = theClass.getClass ();
// -- put some standardization to the namings
// -- derive the "call" + methodName from the condition.
Method method = thisClass.getMethod ("call" + methodName, params);
ReturnType rT = (ReturnType) method.invoke (theClass, inputs);

return rT;
}


The Sample(2) disconnects the need for the invoker () method to know anything about whats its invoking. Clean yeah? So the code has become a little rich by a simple standard driven method nomenclature. A full blown command pattern will take it to the new heights. Will talk about it later.

No comments: