Post

Open-Closed Principle (OCP) for REST APIs

Open-Closed Principle (OCP) for REST APIs

What is the Open-Closed Principle?

The Open-Closed Principle (OCP) is one of the five SOLID principles. It states that “software entities (classes, modules, functions, etc.) should be open for extension but closed for modification.” In essence, this means that you should be able to add new functionality to a system without changing existing, tested code.

Real-World Encounter

We had to implement an interactive map which shows the number signups in an area. The frontend in this project was a separate system built with plain HTML and JavaScript ¯\_(ツ)_/¯. For the backend we needed an endpoint that serves a JSON with the area and the number of signups from this area.

Pretty easy… I created this Rails controller:

1
2
3
4
5
map = User.group(:area).count.map do |area_name, count|
  data = { area_name => count }
end

render json: map

So the generated JSON looked like this:

1
[{"South Area": 3}]

The Problem

What happens if I want to add other properties to the area in the future (area code, average salary, etc.)? Well, I can’t… Unless I change how the response is structured and thus breaking everything down the line.

The {"South Area": 3} format looked fine for the initial case, but it’s too rigid. We need to think about the future and structure our code so it’s easy to extend and maintain.

The Solution

After a quick modification this is how the new JSON looks like:

1
2
3
4
{
  "area_name": "South Area",
  "signups": 3,
}

This way after one year we can add other fields without breaking the existing code.

1
2
3
4
5
6
{
  "area_name": "South Area",
  "signups": 3,
  "area_code": 1000,
  "avg_salary": 2300,
}

Conclusion

A very simple fix, but you just need to know the theory.

This post is licensed under CC BY-NC 4.0 by the author.