Skip to content

Single Responsibility Principle

Last updated on March 16, 2023

Single Responsibility Principle

Each class should have only one responsibility

By looking at the line of codes, we could probably somehow measure how many responsibilities actually lie in the class. With that, I am taking different examples from different sources to better help us measure how many lines of codes should we have.

  • According to Code Complete, a study from 1996 found that classes with more routines had more defects.
  • According to Ben Nadel’s (Object Calistenics), classes over 50 lines usually do more than one thing, which makes them harder to understand and harder to reuse. 50-line classes have the added benefit of being visible on one screen without scrolling, which makes them easier to grasp quickly.
  • According to one of the discussion on (StackExchange), 200 lines is a good guideline.
  • SwiftLint, a tool that help enforce Swift style using the default configuration believe a class should have less than 500 lines of code. (I am aware that you may alter the configuration of such settings)

As for how many lines of code you should have in your project, I’ll leave it to your own jurisdiction as I believe we know best our own project and I trust we should know how long our line of codes can be but I definitely like the idea of keeping it less than 200.

Judging on the line of codes that we have, we could basically measure how many responsibilities we have in our class and could probably break them into different classes.

Code Example:

Let’s look at a bad way of doing it and then see what we could do better.

// You have two responsiblities in this class
struct Person {
    let name: String
    let age: Int

    func checkAge() -> String {
        if age < 8 {
            return "Underage"
        } else {
            return "Qualified"
        }
    }
}

let person = Person(name: "Kelvin", age: 27)
person.checkAge()

I hope you see the point here by separating the responsibilities. Yes, it may be true that we will have a lot of files if we intend to go that route, but let’s think of how organized your code will be and easy to maintain in the longer run.

// One responsibility in one class
struct Person {
    let name: String
    let age: Int
}

// another responsibility in another class
struct AgeVerifier {
    func checkAge(age: Int) -> String {
        if age < 8 {
            return "Underage"
        } else {
            return "Qualified"
        }
    }
}

let person = Person(name: "Lexton", age: 1)
let verifyAge = AgeVerifier()
verifyAge.checkAge(age: person.age)

A little image I hope you will remember each time you are tempted to put more than one responsibility for a class.

Image Credit: Exception Not Found
Published inDesign Principle

Comments are closed.