Lazy Initialization
Context
A general design rule for Java, related to the
toString
method that is implemented on
Object
.
Description
Non-abstract classes should not inherit the
toString()
implementation from
Object
.
Rationale
Implementing a toString method that provides a convenient representation of an object for display purposes makes it more easy to see and interpret the contents of variables in the Java debugger.
This is not a do or die type of rule but merely encourages developers to develop a nice toString method for all their classes by ensuring they do not use the fairly useless implementation that is provided by the Object class.
The rule does not apply to abstract classes because they do not have instances.
Example
None given.
Definition
Query that finds violations:
class(?Violation),NOT(modifier(?Violation,abstract)),
package(?Violation,?Pack),re_name(?Pack,/^tyRuBa/),
name(?Object,Object),class(?Object),
method(?Object,?toString),name(?toString,toString),
inheritedMethod(?Violation,?toString,?Object)
forall class( !abtract tyRuBa..* )
NOT( inherits( String Object.toString() ) )
Ruminations
This is a generic rule which is generally a good principle for all Java programs. However, since it is not a "do or die" rule, users may still which to restrict the scope of the rule: what part of their code do they really want this rule to be enforced it.
This raises the issue if we need some mechanism to allow users to reuse generic rules but tailor them to their own need, for example as is the case here by restricting the scope of the rule.