SOLID - What It Means For Your Code 14 January, 2014

The SOLID acronym is fairly well known, but the phrase it represents seems to be the only well known part of it. It's a set of letters representing techniques for creating maintainable code. What I've done here is give a brief explanation of each solid principle, followed by a short explanation of how you can apply that principle to your code.

Single Responsibility Principle - Each object should have one responsibility, the granularity of which depends on future changes. Develop with the current feature set in mind and using small objects. The first time that code changes, you'll have a better idea about what the single responsibility should be.

Open/Closed Principle - The goal is to keep the number of code changes low. Requirements will change, but the less code you change, the easier regression testing will be. If a code change requires enough testing that it bothers you, you probably need to adapt the code to be more open for extension and closed for modification. You probably can't always follow this principle, but you can segregate the "open for modification" part while trying to keep it small.

Liskov Substitution Principle - Subclasses and superclasses should be able to run interchangeably without breaking the system. Precondition and postcondition consistency across these objects is a key to avoiding bugs in substitutable types.

Interface-Segregation Principle - Code shouldn't depend on something it doesn't use. If you find you are changing or implementing unused methods, break up whatever you are inheriting or abstracting from.

Dependency Inversion Principle - When you depend on an abstract class, a change in one class has a lower chance of forcing a change in dependent class. You don't need to create an abstraction for every kind of object up front because most abstractions never get a second implementation. Often it is better to wait until the need for a second implementation arises, and then create an abstraction.

No comments:

Post a Comment