Monday, July 27, 2009

One minor annoyance is when things are declared public when they should have been declared private. It makes maintaining code more difficult, because changing public signatures means having to find out where they are used. If there are public signatures that are used externally, then changing them even more difficult and might not even be worth it. Private signatures, on the other hand, have limited scope, making them much easier to change. Dealing with public signatures that should have been private means having to look and see that they aren't being used, shouldn't be used, and won't be used outside the class, before changing them (and making them private).

Using the Spring Framework usually means making a bunch of public setter methods. Another option would be to have them all as constructor arguments, which more error-prone, since constructor arguments aren't by name, and can't be defaulted. The public setter methods aren't visible in practice, though, since the rest of the code sees the object through an interface that does not include the setters.

However, since having things set in the constructor better guarantees that the object is properly initialized when it is instantiates than having setter methods, I'm considering something like making an auxiliary parameter class for a constructor argument, and using public setters in parameter class. Something like

public class Bean {
public Bean(Parameters parameters) {
...
}

public static class Parameters {
private Object parameter;
...

public void setParameter(Object parameter) {
this.parameter = parameter;
}

...
}
}

and the configuration would be

<bean class="Bean">
<constructor-arg>
<bean class="Bean$Parameter">
<property name="parameter">...</property>
...
<bean>
</constructor-arg>
</bean>

which has the advantage of named properties with default values without adding public setter methods to the main object.

No comments:

Post a Comment