Modular code is a programming method that breaks down programs into independent modules, each handling a unique task.
By doing so, code is more reusable, better organized, and easier to maintain.
Let’s examine the basic traits and advantages of modular code.
Characteristics of Modular Code
- Separation of Concerns: Every module focuses on a single function or problem, making management of the code easier.
- Encapsulation: Modules expose only required interfaces while hiding internal implementation details.
- Reusability: Modules are reusable in different parts of a program, or even in other projects.
- Testability: Debugging and validation are easier because isolated modules allow independent testing.
- Collaboration: Developers can work on different code sections concurrently without conflict.
Example of Modular code
Below is a vary basic example of how to refactor a piece of code adhering to the modular code principles.

We are refactoring the code above as follows.

We see that the refactored code, in second example, is more modular and maintainable.
It adheres to DRY (Don’t Repeat Yourself) principles.
It’s cleaner and more extensible for future use cases (like message types, translations, HTML formatting, etc.).
Let’s dig in a little more.
Reusability: initFlashArray() encapsulates initialization logic. This makes the addMessage() cleaner and makes initFlashArray() reusable in other methods (e.g., getMessages(), clear(), etc.).
Collaboration and Testability: By extracting the logic, our intent is clear and better supports unit testing.
Separation of Concerns: Breaking the function in two modules makes it easier to maintain as functionality grows. We may later want to customize addMessage (e.g., support for message types like success/error).
