When we talk about OOP and classes to most fresh developers the first thing that comes to mind is a dog. This is because years of training has tought us that a class is a representation of an object, an object with behavior and state. Such as a dog, a dog that barks.
You maybe thinking that this kind of zoological analogies for engineering principles is too simplistic, and you would be right!
While classes in programming can be used to model real life objects this is not what they we’re designed for, in fact this use happens only in fringe cases!
So then what are classes to be used for?
To find the answer to that we must dig way down to The heart of software engineering.
Did you guess it? Yes classes we’re built with the explicit mission to manage complexity!. Incredible isn’t it? Maybe not so much, lets look at some ways in which classes are used in practise.
As good engineers we know that our code is likely to change especially for tricky areas. In such cases it makes sense to write a class that exposes an interface that is much easier to understand in context and forget about the details pertaining to implementation.
Examples of details to hide include:
- Complex algorithms
- Database access routines
- Business logic
For especially complex routines, it makes sense to break them apart into simpler routines and then package all of them into the same class. That way it’s easier to understand each of the individual components of the algorithm in isolation.
Global data is evil! While most languages have made advances in preventing use of it, for obdurate developers there is always a way. For this cases, classes can provide a way to package all data needed globally into a single class and then use an existing pattern, say Singleton to access it.
NB: Singleton is considered by some to be an anti-pattern. Hector Matos gives a more extensive treatment on the subject here http://krakendev.io/blog/antipatterns-singletons
Packaging relating functionality
Most languages provide a standard package for mathematical and statistical functions. You may however have certain special needs for your own software in which case you can package the functions in one class.
Some examples would include:
- Rate calculations
- Financial functions
- Engineering functions
Classes are especially suited for control of knowledge in your application. Building a class to say control access to outside services or provide meta data greatly simplifies design.
You may want to build a class that say:
- Validates information
- Controls external devices
In the above mentioned cases, thinking of classes in the primitive real world object sense is not only useless it can actually be harmful.
How do you use comments in your own design? Tell us in the comment section below.