Clean Code – Classes

coryWelcome to Part 6 of this review of the Pluralsight course Clean Code: Writing Code for Humans by Cory House.

Cory is a Microsoft MVP in C#, founder of OutlierDeveloper.com, avid tech reader, and speaker. He believes in clean code, pragmatic development, and responsive native UIs.

Here are the links to each part in this series:

Part 1 – Writing Code For Humans

Part 2 – Clean Code Principles

Part 3 – Clean Code Naming

Part 4 – Clean Code Conditionals

Part 5 – Clean Code Functions

Part 6 – Clean Code Classes

Part 7 – Clean Code Comments

Part 8 – Clean Code Summary

In this episode we learn more about the role of classes, what makes a good class, and when to create them.

Classes

When to Create

Cory discusses many situations where it is appropriate to create a new class:

  • New concept
  • Low cohesion
  • Promote reuse
  • Reduce complexity
  • Clarify parameters

He explains the benefits of creating a new class in each of these situations

Cohesion

This clip explains the concept of high cohesion, which was first introduced by Tom De Marco in 1979.

Cory contrasts this with some of the magnet classes that were discussed in the Naming module.

As an example we see that a magnet Vehicle class is much better split out into three classes:

  • Vehicle
  • VehicleMaintenance
  • VehicleFinance

Cory stresses that you should start with a good, specific class name, and that usually leads to higher cohesion.

When is a Class too Small?

Signs that a class is too small are:

  1. Inappropriate intimacy
  2. Feature Envy
  3. Too many pieces

Steve Smith’s Refactoring Fundamentals course goes into a lot more detail in these areas.

Cory adds that it is very rare for classes to be too small, so be more concerned about classes that are too big.

Primitive Obsession

Primitive obsession is using primitive types such as strings and integers instead of encapsulating model classes.

Cory explains 4 advantages of creating a new class here.

Also see Mark Seemann’s From Primitive Obsession to Domain Modelling

Principle of Proximity

This is all about making code easy to read from the top of the file downwards, and Cory discusses keeping related actions together.

Outline Rule

Collapsed code should read like an outline. This is a tricky concept to grasp initially, so there is a demonstration later in this course.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s