Saturday, March 26, 2011

Law of Demeter (LoD)

As a programmer, you want to create software that are loosely coupled. A common rule called Law of Demeter (LoD) can be used in object-oriented software to reduce coupling.

The rule is formulated as: Only talk to your friends. A friend is defined as a variable a piece of code directly knows, ie. an attribute, a local variable or a method parameter.

Now, let's examine the following code:

public void do(ExampleClass c) {
String s = "Hello";

c.getSomething().passString(s);
}

In this example, the code is coupled to three classes: ExampleClass, String, and an unknown class returned by the getSomething() method. Only the first two classes are considered friends.

The code is calling (talking to) methods of two objects: the ExampleClass object and the unknown object.

According to the LoD rule, we don't want to talk to classes that are not our friends. This unknown object is not a friend of us, so we'd rather not call its methods.

We can improve the code using the Law of Demeter like this:

public void do(ExampleClass c) {
String s = "Hello";

c.passStringToSomething(s);
}

A new method is created in ExampleClass in order to take over the responsibility for passing a String to the unknown object. The improved example is coupled to two classes now.

Saturday, March 19, 2011

JAR-files and Property-files in an EAR-file

If you get a ClassNotFoundException when deploying an EAR-file, chances are that shared library/utility JAR-files like hibernate3.jar or log4j.jar are not included in the EAR-file.

Place the missing files directly in APP-INF/lib of the EAR-file. Property-files must be placed in APP-INF/classes. This ensures both types of files are visible after deployment.

More on this subject can be found here.

Sunday, March 13, 2011

Thread scoped JAX-WS webservices

Like Servlets, the container uses one instance of a web service class to handle incoming web service requests, which is the default behavior. Ofcourse, you can make the web service thread-safe by adding the synchronized method to the exposed methods like the following code:

@WebService
public class ExampleWS {
public synchronized void doSomething() {
;
}

public synchronized void doSomethingElse() {
;
}
}

By doing this, you eliminate the possibility of parallel or concurrent handling of incoming requests. In order to support concurrent processing, you can mark the web service class as thread scoped by using the @ThreadScope annotation.

import org.jvnet.jax_ws_commons.thread_scope.ThreadScope;

@WebService
@ThreadScope
public class ExampleWS {
public synchronized void doSomething() {
;
}

public synchronized void doSomethingElse() {
;
}
}

The added annotation will force the container to create a new instance of the web service class for every thread (ie. every request). Instances will not be shared by threads.