Friday, June 08, 2007

Style, taste, sensibilities in coding

Chris Aston has an eminently sensible post on programming in the small (not his words[*]), Coding Against the Grain, on some coding style and taste points that have been part of my habits nearly as long as I have programmed.

He emphasizes balance and clarity and cautions against turning objects into stand-ins for global variables: the function is given its due.

To elaborate on his points, I often treat objects as small bundles of encapsulated state with public methods that tie private fields to private functions. A simple example illustrates:

class UsefulExample {
    private int count;

    public String repeatMessage(String message) {
        return repeatMessage(message, count);

    static String repeatMessage(String message,
            int count) {
        StringBuilder builder = new StringBuilder(message);

        for (int i = 1; i < count; ++i)
            builder.append(' ').append(message);

        return builder.toString();

This example is not very interseting, but it makes it easy to list benefits:

  • Testing the functions independent of the encapsulated state is easy.
  • Changing the algorithm of functions does not affect public methods.
  • If the functions are common across classes, refactoring them out to a common utility class is simple.
  • Design changes in the encapsulated state do not impact functions.

In effect, the I have decoupled encapsulated state within the object from implementation algorithms within the functions, and use public methods to connect them together.

This is carrying a common design pattern from "programming in the large" into "programming in the small", with the same advantages. The decoupling of state from algorithm is an old idea [PDF].

More on programming in the small

Ivan Moore has a delightful series of posts on Programming in the Small well worth reading.

Post a Comment