nerdschoolbergen / code-smells

Somewhere along the way code goes from good to bad. It's usually a combination of many small factors that when allowed to take hold in your project, makes it hard to work with and downright frustrating. Your code starts to smell... bad...
25 stars 58 forks source link

Clean code and refactoring

Somewhere along the way code goes from good to bad. It's usually a combination of many small factors that when allowed to take hold in your project, makes it hard to work with and downright frustrating. Your code starts to smell... bad...

Open presentation slides

Focus of this lesson

In this workshop you'll work together in a team. You'll get to know some of the most common code smells and how to fix them. After this workshop you'll know the basics of clean code and how to refactor your smelly code with test coverage.

What you need

How to get started

Exercise

Go to Exercise - Fix the smelly code to get started.

Helpful resources

Shortlist of code smells and ways to fix them

Collect into a single place, and adhere to the Single Responsibility Principle.

* Extract method.
* Extract class.
* Pull up method.
* Form template method.

Split into smaller methods. Make sure each does only one thing. Split into several classes, make sure each class has a Single Responsibility.

* Extract method.
* Replace temp with query.
* Replace method with method object.
* Decompose conditional.

Extract the clump into a class with the methods from the different classes.

* Extract class.
* Extract subclass.
* Extract interface.
* Replace data value with object.
* Introduce parameter object.
* Preserve whole object.

Look around the code for functionality that naturally belongs with the fields and move it into the class.

* Move method.
* Encapsulate field.
* Encapsulate collection.

Chances are, you are missing an object. Introduce one, so that changes to the idea can be expressed in a single place.

* Move method.
* Move field.

The functionality is in the wrong place Move it to the object with the values it wants to be with. You may need to move it to a new class, or merge classes.

* Move method.
* Move field.
* Extract method.

A programmer who thinks it’s too much overhead to use an object for just a few simple values. This is what compilers are for.

* Replace data value with object.
* Replace type code with class.

Consider replacing switch statement with polymorphism – make each value of the switching property determine a new subclass.

* Replace conditionals with polymorphism.
* Replace type code with subclasses.
* Replace parameter with explicit methods.
* Introduce null object.

You Ain't Gonna Need It. Take it out. Simple code is always better.

* Collapse hierarchy.
* Remove parameter.
* Rename method.
* Inline class.

Examples of how to employ common methods:

(google is your friend)