WRITELOOP

NOTES ON CODE COHESION/COUPLING

Some notes on code cohesion and coupling to write better code

2022 August 29
  • Weak cohesion: function that does a lot of things

  • Strong cohesion: function that has a single clear responsability

  • Coupling: how dependant 2 or more sections of code are on each other. You must have the least coupling possible.

  • A function that depends on a property of an object and receives the full object is also coupling! Solution: pass only the data the function needs or move its’ code into the object’s class.

  • Some coupling will always exists

  • How to detect high coupling: when you change the implementation of a function/method, you have to change it and any other code that uses it - that violates the principle that the code that uses it must not know the implementation details and rely on them.

  • How to begin refactoring high-coupled code: start creating classes with type hints to iterate and think on the data model (even if your app/script does NOT deal with databases). E.g.:

class VehicleInfo:
    brand: str
    price: int
    electric: bool

class Vehicle:
    id: str
    licence_plate: str
    info: VehicleInfo

Later on, you can start adding methods to those classes as your code evolves. E.g., a “register” method on the “Vehicle” class above.

NOTE: The original content(s) that inspired this one can be found at:
https://youtu.be/eiDyK_ofPPM
All copyright and intellectual property of each one belongs to its' original author.