Clean Code Cheat Sheet

ADVERTISEMENT

Why Clean Code
Smells
General
Fields Not Defining State
Code is clean if it can be understood easily – by everyone on the team. With
Rigidity
Follow Standard Conventions
+
Fields holding data that does not belong to the state of the instance but are
understandability comes readability, changeability, extensibility and
used to hold temporary data. Use local variables or extract to a class
The software is difficult to change. A small change causes a cascade of
Coding-, architecture-, design guidelines (check them with tools)
maintainability. All the things needed to keep a project going over a long
abstracting the performed action.
subsequent changes.
Keep it Simple, Stupid (KISS)
+
time without accumulating up a large amount of technical debt.
Over Configurability
Fragility
Simpler is always better. Reduce complexity as much as possible.
Prevent configuration just for the sake of it – or because nobody can decide
The software breaks in many places due to a single change.
Boy Scout Rule
+
optimal Responsiveness
how it should be. Otherwise, this will result in overly complex, unstable
Immobility
Leave the campground cleaner than you found it.
systems.
You cannot reuse parts of the code in other projects because of involved
Root Cause Analysis
+
Micro Layers
Responsiveness to change
risks and high effort.
actual
Always look for the root cause of a problem. Otherwise, it will get you again
Do not add functionality on top, but simplify overall.
Viscosity of Design
and again.
CoC
Dependencies
Taking a shortcut and introducing technical debt requires less effort than
Multiple Languages in One Source File
doing it right.
Make Logical Dependencies Physical
+
C#, Java, JavaScript, XML, HTML, XAML, English, German …
If one module depends upon another, that dependency should be physical,
Viscosity of Environment
Environment
not just logical. Don’t make assumptions.
Building, testing and other tasks take a long time. Therefore, these activities
Project Build Requires Only One Step
+
are not executed properly by everyone and technical debt is introduced.
Singletons / Service Locator
Check out and then build with a single command.
Needless Complexity
Use dependency injection. Singletons hide dependencies.
Technical Debt
Executing Tests Requires Only One Step
+
The design contains elements that are currently not useful. The added
Base Classes Depending On Their Derivatives
complexity makes the code harder to comprehend. Therefore, extending
Optimal CoC
Run all unit tests with a single command.
Base classes should work with any derived class.
and changing the code results in higher effort than necessary.
Source Control System
+
Too Much Information
Needless Repetition
time
Always use a source control system.
Minimise interface to minimise coupling
Code contains lots of code duplication: exact code duplications or design
Continuous Integration
+
Feature Envy
duplicates (doing the same thing in a different way). Making a change to a
Writing clean code from the start in a project is an investment in keeping
Assure integrity with Continuous Integration
The methods of a class should be interested in the variables and functions
the cost of change as constant as possible throughout the lifecycle of a
duplicated piece of code is more expensive and more error-prone because
of the class they belong to, and not the variables and functions of other
software product. Therefore, the initial cost of change is a bit higher when
the change has to be made in several places with the risk that one place is
Overridden Safeties
not changed accordingly.
classes. When a method uses accessors and mutators of some other object
writing clean code (grey line) than quick and dirty programming (black line),
Do not override warnings, errors, exception handling – they will catch you.
to manipulate the data within that object, then it envies the scope of the
but is paid back quite soon. Especially if you keep in mind that most of the
Opacity
class of that other object. It wishes that it were inside that other class so
cost has to be paid during maintenance of the software. Unclean code
Dependency Injection
The code is hard to understand. Therefore, any change takes additional time
that it could have direct access to the variables it is manipulating.
results in technical debt that increases over time if not refactored into clean
Decouple Construction from Runtime
+
to first reengineer the code and is more likely to result in defects due to not
code. There are other reasons leading to Technical Debt such as bad
Artificial Coupling
understanding the side effects.
Decoupling the construction phase completely from the runtime helps to
processes and lack of documentation, but unclean code is a major driver. As
Things that don’t depend upon each other should not be artificially coupled.
simplify the runtime behaviour.
a result, your ability to respond to changes is reduced (red line).
Class Design
Hidden Temporal Coupling
In Clean Code, Bugs Cannot Hide
Design
Single Responsibility Principle (SRP)
+
If, for example, the order of some method calls is important, then make
Keep Configurable Data at High Levels
+
Most software defects are introduced when changing existing code. The
A class should have one, and only one, reason to change.
sure that they cannot be called in the wrong order.
reason behind this is that the developer changing the code cannot fully
If you have a constant such as default or configuration value that is known
Open Closed Principle (OCP)
+
Transitive Navigation
grasp the effects of the changes made. Clean code minimises the risk of
and expected at a high level of abstraction, do not bury it in a low-level
You should be able to extend a classes behaviour without modifying it.
introducing defects by making the code as easy to understand as possible.
Aka Law of Demeter, writing shy code.
function. Expose it as an argument to the low-level function called from the
Liskov Substitution Principle (LSP)
+
A module should know only its direct dependencies.
high-level function.
Principles
Derived classes must be substitutable for their base classes.
Don’t Be Arbitrary
+
Naming
Loose Coupling
+
Dependency Inversion Principle (DIP)
+
Have a reason for the way you structure your code, and make sure that
Choose Descriptive / Unambiguous Names
+
Two classes, components or modules are coupled when at least one of
reason is communicated by the structure of the code. If a structure appears
Depend on abstractions, not on concretions.
them uses the other. The less these items know about each other, the
Names have to reflect what a variable, field, property stands for. Names
arbitrary, others will feel empowered to change it.
looser they are coupled.
have to be precise.
Interface Segregation Principle (ISP)
+
Be Precise
+
A component that is only loosely coupled to its environment can be more
Make fine grained interfaces that are client-specific.
Choose Names at Appropriate Level of Abstraction
+
easily changed or replaced than a strongly coupled component.
When you make a decision in your code, make sure you make it precisely.
Classes Should be Small
+
Choose names that reflect the level of abstraction of the class or method
Know why you have made it and how you will deal with any exceptions.
High Cohesion
+
you are working in.
Smaller classes are easier to grasp. Classes should be smaller than about
Structure over Convention
+
Cohesion is the degree to which elements of a whole belong together.
100 lines of code. Otherwise, it is hard to spot how the class does its job and
Name Interfaces After Functionality They Abstract
+
Enforce design decisions with structure over convention. Naming
Methods and fields in a single class and classes of a component should have
it probably does more than a single job.
The name of an interface should be derived from its usage by the client,
high cohesion. High cohesion in classes and components results in simpler,
conventions are good, but they are inferior to structures that force
such as IStream.
Package Cohesion
compliance.
more easily understandable code structure and design.
Name Classes After How They Implement Their Interfaces
Release Reuse Equivalency Principle (RREP)
+
Prefer Polymorphism To If/Else or Switch/Case
+
Change is Local
+
+
The granule of reuse is the granule of release.
“ONE SWITCH”: There may be no more than one switch statement for a
When a software system has to be maintained, extended and changed for a
The name of a class should reflect how it fulfils the functionality provided by
long time, keeping change local reduces involved costs and risks. Keeping
Common Closure Principle (CCP)
+
given type of selection. The cases in that switch statement must create
its interface(s), such as MemoryStream : IStream
polymorphic objects that take the place of other such switch statements in
change local means that there are boundaries in the design which changes
Classes that change together are packaged together.
the rest of the system.
do not cross.
Name Methods After What They Do
+
Common Reuse Principle (CRP)
+
Symmetry / Analogy
+
It is Easy to Remove
+
The name of a method should describe what is done, not how it is done.
Classes that are used together are packaged together.
Favour symmetric designs (e.g. Load – Save) and designs that follow
We normally build software by adding, extending or changing features.
Use Long Names for Long Scopes
+
However, removing elements is important so that the overall design can be
Package Coupling
analogies (e.g. same design as found in .NET framework).
fields parameters locals loop variables
kept as simple as possible. When a block gets too complicated, it has to be
short
Acyclic Dependencies Principle (ADP)
+
Separate Multi-Threading Code
+
long
removed and replaced with one or more simpler blocks.
The dependency graph of packages must have no cycles.
Do not mix code that handles multi-threading aspects with the rest of the
Names Describe Side Effects
+
code. Separate them into different classes.
Stable Dependencies Principle (SDP)
+
Names have to reflect the entire functionality.
Misplaced Responsibility
Depend in the direction of stability.
Standard Nomenclature Where Possible
+
Something put in the wrong place.
Stable Abstractions Principle (SAP)
+
Don’t invent your own language when there is a standard.
Code at Wrong Level of Abstraction
Abstractness increases with stability
Encodings in Names
Functionality is at wrong level of abstraction, e.g. a PercentageFull property
No prefixes, no type/scope information
on a generic IStack<T>.

ADVERTISEMENT

00 votes

Related Articles

Related forms

Related Categories

Parent category: Education
Go
Page of 4