Extremely Serious

Month: February 2020

Cyclomatic Complexity

Cyclomatic complexity is the count of linearly independent paths in a program's source code. With the help of control flow graph, we can use the following formula to calculate this:

CC = E - N + 2P

Variable Description
E The number of edges in the control flow graph.
N The number of nodes in the control flow graph.
P The number of connected components. This has a value of 1 if you are computing at the method (i.e. function or subroutine) level.

Related
Control Flow Graph

Reasons to Favor Composition Over Inheritance

Composition

Using some functionalities of a class but doesn't inherit (i.e. is-a relationship) it, is known as composition (i.e. has-a relationship).

Reasons to Favor Composition Over Inheritance

  • Composition offers a better testability. Imagine a class composed of another class or interface. You can easily create a mock of the composed class for the sake of testing.
  • Composition is more flexible than inheritance. It is easier to change the implemention of the composed class with better and improved version. Just create a new independent implementation (e.g. annonymously) of the composed class and change it at runtime.
  • Both composition and inheritace supports code reuse. However, inheritance breaks encapsulation. Example, if a subclass is depending on its super class behavior for its operation, it becomes fragile. Try to imagine that you change the implementation on the super class. Did you consider the effect of the change on the subclasses that overrides it but partially depends on it. In composition there's no dependencies like this. Thus, you have more robust code.