1

I have two classes: Student and User. The User class extends Student, and both of them implement a common interface, which defines a checkSelf() method. This method checks if the state of the object is valid and is called before performing updates or insertions in the database.

I insert both students and users in the database, which makes it necessary for this method to be callable from outside the class in both cases. This is why the solution found in this post doesn't seem applicable to my problem. Maybe I missed something though.

Basically, the way things are now, both checkSelf() methods are public and the one in the User class calls the one from its parent (Student) before doing its own checks.

How could I go about solving this so I have clean code?

Community
  • 1
  • 1
PLPeeters
  • 1,009
  • 12
  • 26

1 Answers1

4

I don't personally agree with this rule (IMHO more headache than use), but the answer in the question you mentioned gives a fairly good indication of what you can do.

  • Make the checkSelf() method final
  • Create an empty protected checkSelfEx() method in Student that is called as the last step of checkSelf()
  • Implement checkSelfEx() in User making it final.

This guarantees that the checks performed in checkSelf() are ALWAYS going to be performed when the method is called (hence no break of contract by subclasses is possible). The problem of course arises in naming, as if you want some more logic in a subclass of User, you would need checkSelfExEx(). If all those checks can be grouped with a better name it is at least OK to read, but exposing a lot of final methods to subclasses is not a great thing.

Ordous
  • 3,844
  • 15
  • 25
  • What shall I do if I want to make inheritance deeper? For example `class A {}`, `class B extends A`, `class C extends B` and so on? – RoninDev May 06 '16 at 07:09
  • 1
    @RoninDev This rule is supposed to be used with shallow class hierarchies. Checkstyle themselves say "Nothing wrong could be with founded classes this Check make sence only for library project, not application projects". As such, it's really only applicable to classes you make publicly available in your API, and those are unlikely to have deep hierarchies (we don't count private classes they may subclass from, only other public ones). IMHO, since you control the build, it may be better to just make a custom annotation and build check to make sure the super implementation is called. – Ordous May 06 '16 at 11:27