Developing for re-usability
14 May 2005Lately we’ve been re-using a few legacy components in other applications and its forced me to think a little bit about developing for re-usability.
Here are a few off the cuff thoughts on re-usable component development
1) Adequately comment all public/protected (and ideally private) methods.
– By adequate I mean full javadoc including expected parameter value ranges, is null?, etc. If a method throws an exception (checked or unchecked), includ
e that in the documentation.
– If appropriate, consider external non-code documentation for the component.
2) Provide controlled accessors to variables instead of direct access.
– Avoid allowing people to do componentInstance.variable = null. It’s just good coding habits.
3) A failure in the component should not bring down the calling application.
– No one would actually consider doing this right? but a System.exit() inside a method is just plain terrible and unacceptable.
– Exception conditions should be handled appropriate and resources/connections closed.
4) Adequate (but not excessive) logging
– Make proper use of the different logging levels.
– Don’t hardcode log4j usage and create an unwanted dependency in calling applications.
– Don’t log stack traces and then proceed to re-throw the exception: ie)
catch (IOException e)
{
// this logger is worthless and may cause unnecessary console prints
// in the calling application.
logger.error(“Error accessing file: ” + file, e);
throw new CustomException(“Error accessing file: ” + file, e);
}
5) Unit-test
– A unit-test should help self-document and code review the component. The unit test should cover all boundary conditions on variables and alert the devel
oper if they missed something.
– A unit-test will act as a form of documentation showing expected uses and results.
– A test will serve as a foundation point that other developers can build upon as they integrate. There’s nothing worse than wanting to use a component bu
t not being sure if it actually works correctly and having to test it yourself.
6) Interface development (updated)
– Start with the development/specification of an interface between your code and the outside world.
– When it comes time to implement your component, program to the interface.
– Avoid directly calling/loading of implementing classes, consider the use of Factories or alternatively DI frameworks like Spring.
I’ve got to run now so that’s all for now.