In Java, one almost certainly will see the following statement, when using a larger API:
“When overriding this method, a call to super must be the first (the last) statement of the overriding method”
One will see this quite likely when using frameworks where the overridden method will do some initialization of any kind. Obviously, violating the contract can have severe consequences. There is, however, a quite simple pattern to enforce this. I always wondered that one does not see it more often in books about patterns, as it is very simple, and, by means of object orientation, very straightforward. First, assume an API class:
This pattern can be seen quite often in complex frameworks. A better alternative is:
Since Base.initialize() is final, it cannot be overridden. Instead any subclasser is enforced to use Base.doInitialization() which is called at a well defined point. Furthermore (if that is needed in the concrete case) there is no possibility to hamper with Foo.
I used this pattern when I wrote a specialized TestCase for JUnit tests for UI tests. There had specific actions for tearDown() to be done (like closing erronously opened modal dialogs). Therefore I overrode tearDown() marking it final and introduced a second method for client specific tearDown actions.