Skip to content

clean code checklist

corebonts edited this page Nov 17, 2020 · 5 revisions
  • Code is clean if it can be understood easily by everyone on the team. With Understandability comes readability, changeability, extensibility and maintainability. All the things needed to keep a project going over a long time without accumulating up a large amount of technical debt.

  • Writing clean code from the start in a project is an investment in keeping the Cost of Change (CoC) as constant as possible throughout the lifecycle of a software product. Building the house analogy applies here. If you spend little more initially during the foundation, your maintenance cost will be less compare to house that were built quick and dirty.

  • In Clean Code, Bugs Cannot Hide
    Most software defects are introduced when changing existing code. The reason behind this is that the developer changing the code cannot fully grasp the effects of the changes made. Clean code minimizes the risk of introducing defects by making the code as easy to understand as possible.

Principles

  • Loose Coupling
    Two Classes, components or modules are coupled when at least one of them uses the other. The less these items know about each other, the looser they are coupled. A component that is only loosely coupled to its environment can be easily changed or replaced than a strongly coupled component.
  • High Cohesion
    is the degree to which elements of a whole belong together. Methods and fields in a single class and classes of a component should have high cohesion. High cohesion in classes and components results in simpler, more easily understandable code structure and design.
  • Change is Local
    When a software system has to be maintained, extended and changed for a long time, keeping changes local reduces involved costs and risks. Keeping change local means that there are boundaries in the design which changes do not cross.
  • It is Easy to Remove
    We normally build software by adding, extending or changing features. However removing elements is important so that the overall design can be kept as simple as possible. When a block gets too complicated, it has to be removed and replaced with one or more simpler blocks.

Code Smells when

  • Rigidity
    The software is difficult to change. A small change causes cascade of subsequent changes.
  • Fragility
    The software breaks in many places due to a single change.
  • Immobility
    You can't use part of the code in other project because of involved risk and high effort.
  • Viscosity of Environment
    Building, testing and other tasks take a long time. Therefore, these activities are not executed properly by everyone and technical debt is introduced.
  • Needless Repetition
    Code contains lots of code duplication: exact code duplications or design duplicates(doing the same thing in a different way). Making a change to a duplicated of code is more expensive and more error-prone because the change has to be made in several places with the risk that one place is not changed accordingly.
  • Opacity
    The code is hard to understand. Therefore, any change takes additional time to first reengineer the code and is more likely to result in defects due to not understanding the side effects.

Class Design

  • Single Responsibility Principles (SRP)
    A class should have one, and only one, reason to change.
  • Open Closed Principle (OCP)
    You should be able to extend a classes behaviour without modifying it.
  • Liskov Substitution Principle (LSP)
    Derived classes must be substitutable for their base classes.
  • Dependency Inversion Principle (DIP)
    Depends on abstraction, not on concretions.
  • Interface Segregation Principle (ISP)
    Make fine grained interfaces that are client-specific.
  • Classes should be small
    Smaller classes are easier to grasp. Classes should be smaller than about 100 lines of code, Otherwise, it is hard to spot how the class does its job and it probably does more than a single job.

Package Cohesion

  • Release Reuse Equivalency Principle (RREP)
    The granule of reuse is the granule of release.
  • Common Closure Principle
    Classes that changes together are packaged together.
  • Common Reuse Principle
    Classes that are used together are packaged together.

Package Coupling

  • Acyclic Dependencies Principle (ADP)
    The dependency graph of packages must have no cycles.
  • Stable Dependencies Principle (SDP)
    Depend in the direction of stability.
  • Stable Abstractions Principle (SAP)
    Abstractness increses with stability.

General

  • Follow Standard Convention
    Coding-, architecture-, design guidelines (check them with tools).
  • Keep it Simple, Stupid (KISS)
    Simpler is always better. Reduce complexity as much as possible.
  • Boy Scout Rule
    Leave the campground cleaner then you found it.
  • Root Cause Analysis
    Always look for the root cause of problem. Otherwise, it will get you again and again.
  • Overridden Safeties
    Do not override warnings, errors, exception handling - they will catch you.

Dependency Injection

  • Decouple Construction from Runtime
    Decoupling the construction phase completely from runtime helps to simplify the runtime behaviour.

Design

  • Keep Configurable Data at High Levels
    If you have a constant such as default or configuration value that is known and expected at high level of abstraction, do not bury it in a low-level function. Expose it as an argument to the low-level function called from the high-level function
  • Don't be Arbitrary
    Have a reason for the way you structure your code, and make sure that reason is communicated by the structure of the code. If a structure appears arbitrary, other will feel empowered to change it.
  • Structure over Convention
    Enforce design decisions with structure over convention. Naming conventions are good, but they are inferior to structures that force compliance.
  • Be Precise
    When you make a decision in your code, make sure you make it precisely. Know why you have made it and how you will deal with any exception.
  • Prefer Polymorphism To If/Else or Switch/Case
    "ONE SWITCH": There may be no more than one switch statement for a given type of selection. There cases in that switch statement must create polymorphic objects that take the place of other such switch statements in the rest of the system.
  • Symmetry/Analogy
    Favour symmetric designs (e.g. Load-Save) and design that follow analogies.
  • Separate Multi-Threading Code
    Do not mix code that handles multi-threading aspects with the rest of the code. Separate them into different classes.
  • Misplaced Responsibility
    Something put in the wrong place.
  • Code at Wrong Level of Abstraction
    Functionalities are at wrong level of abstraction.
  • Fields not defining State
    Fields holding data that does not belong to the state of the instance but are used to hold temporary data. Use local variables or extract to a class abstracting the performed action.
  • Over Configurability
    Prevent configuration just for the sake of it - or because nobody can decide how it should be. Otherwise, this will result in overly complex, unstable systems.
  • Micro Layers
    Do not add functionality on top, but simplify overall.

Dependencies

  • Make Logical Dependencies Physical
    If one module depends upon another, that dependency should be physical, no just logical. Don't make assumptions.
  • Singletons / Service Locator
    Use dependency injection, Singletons hide dependencies.
  • Base classes Depending On their derivatives
    Base classes should work with any derived class.
  • Too Much Information
    Minimize interface to minimize coupling
  • Feature Envy
    The methods of a class should be interested in the variables and functions of the class they belong to, and not the variables and functions of other classes. When a method uses accessors and mutators of some other object to manipulate the data within that object, then it envies the scope of the class of that other object. It wishes that it were inside that other class so that it could have direct access to the variables it is manipulating.
  • Artificial Coupling
    Things that don't depend upon each other should not be artificially coupled.
  • Hidden Temporal Coupling
    If, for example, the order of some method calls is important, then make sure that they cannot be called in the wrong order.
  • Transitive Navigation
    Aka Law of Demeter, writing shy code. A module should know only its direct dependencies.

Naming

  • Choose Descriptive / Unambiguous Names
    Names have to reflect what a variable, field, property stands for. Names have to be precise.
  • Choose Names at Appropriate Level of Abstraction
    Choose names that reflect the level of abstraction of the class or method you are working in.
  • Name Interfaces After Functionality They Abstract
    The name of an interface should be derived from its usage by the client.
  • Name Classes After How They Implement Their Interfaces
    The name of a class should reflect how it fulfills the functionality provided by its interface(s).
  • Name Method After What They Do
    The name of the method should describe what is done, not how it is done.
  • Use Long Names for Long Scopes
  • Names Describe Side Effects
    Names have to reflect the entire functionality
  • Standard Nomenclature Where Possible
    Don't invent your own language when there is a standard.
  • Encodings in Names
    No prefixes, no type/scope information

Understandability

  • Consistency
    If you do something a certain way, do all similar things in the same way: same variable name for same concepts, same naming pattern for corresponding concepts.
  • Use Explanatory Variables
    Use locals to give steps in algorithms names.
  • Encapsulate Boundary Conditions
    Boundary conditions are hard to keep track of. Put the processing of them in one place.
  • Prefer Dedicated Value Objects to Primitives Types
    Instead of passing primitives types, use dedicated primitive types.
  • Poorly Written Comment
    Comment does not add any value (redundant to code), is not well formed not correct grammar/spelling.
  • Obvious Behaviour is Unimplemented
    Violations of "the Principle of Least Astonishment". What you expect is what you get.
  • Hidden Logical Dependency
    A method can only work when invoked correctly depending on something else in the same class.

Methods

  • Methods Should Do One Thing
    Loops, exception handling, ...encapsulate in sub-methods.
  • Methods Should Descend 1 Level of Abstraction
    The statements within a method should all be written at the same level of abstraction, which should be one level below the operation described by the name of the function.
  • Method with Too Many Arguments
    Prefer fewer arguments. Maybe functionality can be outsourced to a dedicated class that holds the information in fields.
  • Method with Out/Ref Arguments
    Avoid usage. Return complex object holding all values, split into several method. If your method must change the state of something, have it change the state of the object it is called on.
  • Selector / Flag Arguments
    public int Foo(bool flag). Split method into several independent methods that can be called from client without the flag.
  • Inappropriate Static
    Static method that should be an instance method.

Source Code Structure

  • Vertical Separation
    Variables and methods should be defined close to where they are used. Local variables should be declared just above their usage and should have small vertical scope.
  • Nesting
    Nested code should be more specific or handle less probable scenarios than top-level code.
  • Structure Code into Namespaces by Future
    Keep everything belonging to the same feature together. Don't use namespaces communicating layers. A feature may use another feature; a business feature may use a core feature like logging.

Conditionals

  • Encapsulate Conditionals
    If(this.ShouldBeDeleted(timer)) is preferable to if(timer.HasExpired && !timer.IsRecurrent).
  • Positive Conditionals
    Positive Conditionals are easier to read than negative conditionals

Useless Stuff

  • Dead Comment, Code
    Delete unused things, you can find them in your version control systems.
  • Clutter
    Code that is not dead but does not add any functionality.
  • Inappropriate Information
    Comment holding information better held in a different kind of system: product backlog, Source control. Use code comments for technical notes only.

Maintainability Killers

  • Duplication
    Eliminate Duplication. Violation of the Don't repeat yourself (DRY) principle.
  • Magic Numbers / Strings
    Replace Magic Numbers and Strings with named constants to give them a meaningful name when meaning cannot be derived from the value itself.
  • Enums (Persistent or Defining Behaviour)
    Use reference codes instead of enums if they have to be persisted. Use polymorphism instead of enums if they define behaviour.

Exception Handling

  • Catch Specific Exceptions
    Catch exceptions as specific as possible. Catch only the exceptions for which you can react in a meaningful manner.
  • Catch Where You can React in Meaningful Way
    Only catch exceptions when you can react in a meaningful way. Otherwise, let someone up in the call stack react to it.
  • Use Exceptions instead of Return Codes of null
    In an exceptional case, throw an exception when your method cannot do its job. Don't accept or return null. Don't return error codes.
  • Fail Fast
    Exceptions should be thrown as early as possible after detecting an exceptional case. This helps to pinpoint the exact location of the problem by looking at the stack trace of the exception.
  • Using Exceptions for Control Flow
    Using Exceptions for control flow: has bad performance. is hard to understand and results in very hard handling of real exceptional cases.
  • Swallowing Exceptions
    Exceptions can be swallowed only if the exceptional case is completely resolved after leaving the catch block. Otherwise, the system is left in an inconsistent state.

From Legacy Code to Clean Code
Always have a Running System
Change your system in small steps, from a running state to a running state.

  1. Identify Features
    Identify the existing features in your code and prioritize them according to how relevant they are for future development (likelihood and risk of change).
  2. Introduce Boundary Interfaces for Testability
    Refactor the boundaries of your system to interfaces so that you can simulate the environment with test doubles (fakes, mocks, stubs, simulators).
  3. Write Feature Acceptance Tests
    Cover the feature with Acceptance Tests to establish a safety net for refactoring.

Clone this wiki locally