Domanda

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?

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top