Posted 3 months, 3 weeks ago | Originally written on 28 Sep 2020
Object oriented software design is praised for the fact that it provides an easy mental handle by which a developer may reason about a software entity. However, the bit that is often ignored is the fact that the easy mental handle requires work in order to be teased out. I have seen many budding software developers turn to object orientation only to write functional code around objects, which undermines the whole idea. Clearly the problem has little to do with object orientation as a feature of the language; rather, the main problem lies with learning design using object orientation. This is why I've titled this article 'the dark side': more light needs to be shed on object orientation so that neophytes to the technique will start off knowing that there is more to object orientation than syntax.
Like most useful techniques worth learning, applying object orientation can only be learned from someone who knows how to apply it effectively so as to elicit the benefits mentioned above. Once properly applied, object orientation does confer the above benefits.
Some tips to making the most of object orientation
- Only introduce classes during refactoring and never during the hack stage of development. This way you can automatically reveal the core classes which will typically represent repetitive items.
- Define your class names using nouns. Being objects classes should represent things that encapsulate all we need to know about an entity.
- Define your methods using verbs. Verbs refer to action and methods do things.
- The most useful classes live in the top layer. Define at most seven top level classes that live at the top-most layer that do all the work. Any more than seven and you'll spend your life constantly referring to the code or documentation.
- Internal layers expose single classes. Take advantage of the encapsulation property of objects to abstract away internal functionality. For example, you might define an internal class that handles connections that is never explicitly defined by users of the top-level classes.
- Play through the software's pipeline from beginning to the end to reveal classes based on the major items that are involved in realising the output. For example, in Django the main classes involved are Request and Response objects signifying the bare minimum needed to work. These classes capture the stateless nature of HTML: an agent submits a request and receives a response. The set of classes that handle everything after the request and before the response is generated (in the middle) are Middleware classes.