Part 1: The Code

It is amazing how much time is spent in management meetings talking about how to improve delivery speed and reduce costs. It sometimes seems that agile software development is seen as a silver-bullet that can fix all the ingrained problems an organisation has.

The strangest thing sometimes is how little energy is spent talking about improving the codebase itself.

Regardless of which software development life cycle process is being used, ultimately it is the code that must be transformed from its current state to a new state to support the goals of the organisation or users.

Part 1 of this book is focussed on the code itself, and how a codebase can be kept more pliable and easier to change.

The SOLID Principles of OO Design

THIS IS A SAMPLE PART OF THE SOLID CHAPTER

The SOLID acronym represents some important principles of object-oriented programming and design.

It stands for:

  • S - Single Responsibility Principle
  • O - Open Closed Principle
  • L - Liskov Substitution Principle
  • I - Interface Segregation Principle
  • D - Dependency Inversion Principle

This chapter examines each of these principles in term and relates them back to how they help to keep software soft.

The Single Responsibility Principle (SRP)

Any given class should do one well-defined thing, and only that one well-defined thing.

To put in another way, if a class has more than one responsibility, it will have to change whenever any one of it’s responsibilities change. If there’s more than one reason to change a class, its likely that the Single Responsibility Principle has been violated.

As an example, consider an OrderManager class that is responsible for: calculating the total order amount, debiting a credit card, and updating the order status in the database. Clearly this is a violation of SRP. Instead, a cleaner implementation could be to split out each responsibility into three separate classes: OrderTotalsCalculator, CreditCardCharger, and OrderRepository. Now each class only needs to change if it’s responsibility changes.

Why SRP?

SRP is important to keeping software soft because:

  • A class that conforms to SRP only needs to be changed when the thing it’s responsible for changes
  • Each class now has fewer lines of more highly-related code, so it should be easier for a developer to understand in its entirety
  • More individual source code files (e.g. one for each responsible class) should result in fewer merge conflicts
  • Testability is likely to be better and the related test code more highly focussed and cohesive

Without SRP there is greater fear (and potentially higher regression test costs) when changing any given part of the system.

Customer: “We want to change the way order totals are calculated.” Development Team: “No problem, give us the new business rules, we’ll write some tests then go and change the OrderCalculator, we don’t have to worry about breaking the database because that’s in a separate place”.