5 Rules to follow in order to write better code.

Sometime back, our team had a project that no one wanted to work on. The main concern was the cascade effect that was expected from the project. It was so unpredictable and had huge "utils" classes. This has been known to scare most developers as it is believed that the functionality of such a code base is humongous.

The classes under "utils" were also huge. Below are 5 rules to follow to write better code.

  • Group related Logic.

Methods that operate on the same data should be within the same class. Group data and behavior.

  • Practice Single Responsibility.

Every class should have only one reason to change. This means that a class should only have one job or responsibility. If you find a class doing too much then it should be broken down into more focused classes.

  • Encapsulation through Composition.

Prefer composition over inheritance where practical. Use Objects to represent behaviors or states you can compose into your classes rather than extending them through inheritance.

  • Validate Input at public interfaces.

When the methods need to accept input from other parts of the code, trusting that the input will always be correct is wrong. The input should be validated to ensure that it meets the method's requirements.

  • Cut mutable State.

Reduce the number of changeable states in the class. The more variables that can change, the harder it will be to track their interactions and maintain the system. Where possible, make the class instances immutable.

  • Not using encapsulation leads to harder-to-maintain Systems.

Below is an Image illustrating some aspects of how to write better code.

Image

That is all for today.

Thank you and see you in the next one.

Credits to @RaulJuncoV on X(Formerly Twitter).