- Learning Functional Programming in Go
- Lex Sheehan
- 322字
- 2021-07-02 23:13:48
This OOP method stinks
This is what a method contract looks like in the OOP world:
![](https://epubservercos.yuewen.com/6176FA/19470400908922906/epubprivate/OEBPS/Images/Chapter_112.jpg?sign=1739353388-adtXohS6UxzLSJO71jkbzjJ47CGsfCR1-0-9961b4d968563c39ac1e820cb2cbd357)
Our method m is passed an a, does some processing and returns b. An exception can occur, which may or may not be caught and handled and errors can be returned. Additionally, in order for the method to properly satisfy its contract, it's up to us to read the documentation (which of course will always be completely accurate and up-to-date.... not!) in hopes that we cover all the preconditions, invariant, and postconditions.
An invariant is something that must be always be true for the life of the method. For example, if our class has a duration member variable, that value must always be a positive float. Another example could be that our internal latitude and longitude values must always be in the northern hemisphere. We could go so far as to write invariance validator private methods to ensure our invariant are in compliance with their range of acceptable values.
A precondition is something that must be true at the time our method is called. For example, before we execute our consummateMarriage method we should ensure that our chosen wouldBeSpouse is not already married to another; Otherwise, we'd likely be in violation of our state's anti-polygamy laws. We would likely do our checking by executing another verifyPersonIsSingle method.
Let's not forget the postconditions. An example might be: After executing our consummateMarriage method we should ensure that the person with whom we consummate is actually the same person on our marriage certificate. Marrying the wrong person could cause all sorts of problems.
The last issue to deal with is side effects. A side effect is what happens when our method changes something other than the b (or the error) that it outputs. For example, if our postcondition check caused a credit card charge from a private investigation firm, that charge would be a side effect.