Tuesday, May 19, 2009

Static Methods versus Object Instantiation

One of the arguments I have been having in my team lately is whether our models should be a set of static methods or an object that is instantiated with public methods. My background is such that I tend to lean towards object instantiation in 95% of the objects I develop. In addition, many of the objects with all static methods are simply a method for namespacing global functions. Using objects this way is 100% against my understanding of object oriented development.

Wikipedia (Objects) definitionIn computer science, an object commonly means a data structure consisting of data fields and procedures (methods) that can manipulate those fields.

Therefore a class of methods that behaves like a toolbox is simply not object oriented development. With that said, I read a good article yesterday while searching for more information about the two sides of the arguments that basically stated that unless the object has a persistent state beyond a single method invocation it might be worthwhile to consider making it public static. Reading this simply, if the object has no properties then it is a candidate to be a set of static methods.

In regards to Models, the problem I have with this is that I strongly believe that the database adapter should be decoupled from the Model itself. If all methods of a Model are static then this means the database adapter would be a required parameter for each method. This added complexity is unnecessary. In my opinion the database adapter should be a required parameter for instantiating a Model. After all, a Model is designed to interact with a data store so providing the adapter to do so makes a lot of sense. This decouples it and reduces the complexity in the parameters for each method the model implements.

This is synonymous of my approach to development in general in that I prefer to divide responsibilities into smaller, simpler methods. This facilitates easier and more complete unit testing in that smaller, simpler methods do not have many paths to traverse therefore testing every path is clear and straightforward. In addition, this approach reduces complexity of the code which is a common practice for improving flexibility and maintainability of code. If a method is not complex it is easier to understand what it is accomplishing as well as to refactor or add functionality.

This discussion has made me rethink other objects of our stack though. I realize that I have under utilized classes that have static methods. I still do not agree that methods should be simply made static and put in a class together if they do not actually represent an object. But I do see greater utility in static methods in general and will implement them more frequently.