Sobes.tech
Junior

What does the letter 'O' mean in the SOLID pattern?

sobes.tech AI

Answer from AI

'O' stands for the Open/Closed Principle.

Modules (classes, functions, etc.) should be open for extension but closed for modification. This means that new functionality can be added without changing existing code.

Example of violating the principle:

// Package shape
type Shape interface {
	Type() string
}

type Rectangle struct{}

func (r Rectangle) Type() string {
	return "rectangle"
}

type Circle struct{}

func (c Circle) Type() string {
	return "circle"
}

// Package calculator
type AreaCalculator struct{}

func (ac AreaCalculator) CalculateArea(shapes []Shape) float64 {
	totalArea := 0.0
	for _, shape := range shapes {
		switch shape.Type() { // Need to modify this code when adding a new shape
		case "rectangle":
			// Logic for calculating rectangle area
		case "circle":
			// Logic for calculating circle area
		}
	}
	return totalArea
}

When adding a new shape (e.g., Triangle), the CalculateArea function in AreaCalculator needs to be modified to handle the new type.

Example of adhering to the principle:

// Package shape
type Shape interface {
	Area() float64 // Add the Area() method to the interface
}

type Rectangle struct {
	Width, Height float64
}

func (r Rectangle) Area() float64 {
	return r.Width * r.Height // Area calculation logic encapsulated within the struct
}

type Circle struct {
	Radius float64
}

func (c Circle) Area() float64 {
	return 3.14 * c.Radius * c.Radius // Area calculation logic encapsulated within the struct
}

// Package calculator
type AreaCalculator struct{}

func (ac AreaCalculator) CalculateArea(shapes []Shape) float64 {
	totalArea := 0.0
	for _, shape := range shapes {
		totalArea += shape.Area() // Use polymorphism, without knowing the specific shape type
	}
	return totalArea
}

In this example, adding a new shape that implements the Shape interface with the Area() method does not require changes to the AreaCalculator code. AreaCalculator is open for extension (adding new Shape types) but closed for modification (no code changes needed when adding new types).

This is achieved through polymorphism and encapsulation of the area calculation logic within each shape type. The principle promotes creating more flexible, maintainable, and extendable code.