DEV Community

amu
amu

Posted on

Associated Class Members Introduce "Dimensions" to Classes

Usually, in the more useful object oriented tips the focus is more on improving the inheritance relations. Which is wonderful; it is nice to not see long inheritance chains. Even better, it is nice to see composition more than inheritance.

But there is another kind of chain that is caused just by using an object within the class regardless of composition and inheritance.

If a class uses another object in any form of association-esk relation, it introduces new "dimensions" for it. You could say in a very simple sense, dimension is observed through the number of dots you enter when accessing a method within the class: this.object_a.object_b.object_c.hello().
You want the number of dots to be "enough" so that the class is properly "populated" and/or "bloated."

Too large of a dot count might be the sign of a class doing something that is too low-level given its abstraction layer.

Consider a very dimensional class on one side of the spectrum, with the other side being a flat class. The flattest class contains only "plain old data" types. This means there might be custom objects within our class, but they don't have functionality; they're merely a collection of data and perform primitive operations on them.

It is useful to take a second to reconsider whether a new dimension would be helpful before starting the implementation. It greatly contributes to reducing overengineering. The principle/idea is to usually prefer being more flat unless it is obvious that introducing dimension helps more. E.g. when a collection of members and methods are gravitating towards a certain behavior that can become a class on its own.

Using this policy, the dimensions are grown out of necessity, not out of our imagination of arbitrary necessities when they don't exist.

Overengineering is born because the abstractions are larger than the requirements of the current code. Moreover, in an overengineered code, you have to fit the feature into the structure. But when the class is flatter, more free-form, you can just add a piece of code and then carve out abstractions based on that, if needed.

This stands in any granularity level:

  • Variable: Does this value really need to be saved in a variable and occupy memory?
  • Method: Do these few lines of code really need to be a method?
  • Class: Does this collection of variables and methods really need to be a class on its own? Or is it okay enough to be in the class that they are currently residing in?

Having more dimension increases complexity. This statement is against the traditional "clean code" that generally encourages more classes and methods. Complexity isn't a "bad" thing. Complexity is a property that naturally exists, like the BMI level of human body. We just need to make sure it has a "reasonable" amount.

Top comments (0)