Graduate Program KB

Chapter 10 - Classes

  • Classes should be small

  • Single Responsibility Principle (SRP)

    • Class or module should have one and only one reason to change
    • SRP is often overlooked as developers often focus on if code works and not if it is clean code
  • Classes and Functions must have High Cohesion

    • Cohesion: A measure of how many methods an instance variable is read into
    • Cohesion relates to how well the elements of a module belong together
  • Maintaining Cohesion results in many small classes

    • Breaking down process
      • We start with a very large method that we want to break down into smaller method
      • As we split the large method into smaller methods we create more instance variables
      • Even though we have broken our method into smaller methods, as we have many instance variables our class cohesion is very low
      • This results in creating smaller classes from our one large class with the appropriate methods in each class
      • High cohesion has finally been achieved
  • Conclusion - Reducing the Risk of Change

    • Whenever we modify a class we introduce a risk of breaking another part of that class
    • Clean code means having small classes, small functions and high cohesion
    • It is very hard to break code of small classes or fuctions as there not as many factors to worry about when changing code.