I wanted to have a behaviour similar to ActiveRecord's one:
- You create a class, representing a database row, extending a base class
- The new class inherits from the superclass all its database mapping business logic
- The new class now has some instance methods to work with the row it represents (save, delete...) and some static methods to retrieve objects reading the DB table (find, create...)
Come Java, and its implementation of inheritance. In Java static methods are not inherited. A derived class can use its superclass static methods, but these methods still reside in the superclass. The problem with this approach is that if you try to get the name of the current class or one of its fields, via reflection, inside a static method, you will always get the name or the field of the class which defined the static method and not the name of one of its derived class that is using said method.
This leads to an important decision about how to implement the Active Record pattern. Basically I had two possibilities:
- Break the design pattern and any basic logic behind a class, having only instance methods
- Use static methods, passing them a parameter to be able to identify the actual class we are using.
On the other hand, the second approach keeps the Class logic intact, but needs an extra parameter, containing the actual class informations, for every static method inside the base class.
Instead of choosing one approach instead of the other, I decided to keep them both, and provide two superclasses from which to inherit: one providing static methods and one providing instance methods. If and when one approach becomes better than the other, I will ditch the inferior one.