Bitpath

Clean Code & Refactoring

Learn to see what makes code hard to read: names that lie, functions that do two jobs, duplication, tangled conditions and data that drifts. Then change working code in small, checked steps so it gets easier to live with and never behaves differently.

  • Beginner
  • 4 units, 12 lessons, 137 exercises
  • Your language
  • Builds on Algorithm Foundations

Unit 01 · 3 lessons

Say what you mean

Write code a stranger can follow without opening every function

  1. > start01Names
  2. 02Functions
  3. BOSSMake it readable
Unit prize
  1. 01
    Names

    A name is a promise to the reader

  2. 02
    Functions

    One job, few arguments, no surprises

  3. BOSS
    Make it readable

    One tangled function, cleaned up without changing a result

Read the unit guide

Code is read far more often than it is written, and usually by someone who does not have the author's head. Every name is a small promise to that reader. A good name says what a thing holds or does, so nobody has to open it to find out. A bad name says nothing (data, tmp2) or, worse, says something false.

Names carry more than a noun. Put the unit in the name when a number has one (timeout_ms), make a yes/no value read like a question (is_empty), and let length follow scope: a loop counter that lives for two lines can be i, a setting read across the project cannot.

A function should do one job at one level of detail. Describe it in a sentence: if you need "and", it is two functions. Keep working something out apart from printing or saving it, and the part that computes can be reused and checked anywhere. Handle special cases first with a guard clause and return, so the ordinary case is not buried in nesting.

Watch the arguments. A bare true at a call site hides a second function behind a flag, and six positional arguments invite two of them to be swapped. A function named like a question must not quietly change what it was asked about.

Comments are for reasons. The code already says what happens; a comment that repeats it goes stale. Keep the ones that say why: why 14 days, why a cap. Name the numbers that carry a decision, and delete code that can never run: version control remembers it.

The classic pitfall is "tidying" that changes behaviour. Before you touch a tangled function, write down what it returns for a few inputs. After every small step, run them again.

Unit 02 · 3 lessons

Smells

Spot the shapes in code that make the next change hurt

  1. 01Duplication
  2. 02Conditionals
  3. BOSSBreak up a long function
Unit prize
  1. 01
    Duplication

    One fact, one place: and when a copy is fine

  2. 02
    Conditionals

    Flatten, tabulate and name your conditions

  3. BOSS
    Break up a long function

    Extract, inline and reorder without changing the bill

Read the unit guide

A smell is not a bug. The code works; the smell is a sign that the next change will be slow or risky. Learn the common ones and you know where to look before you edit.

Duplication is the first. When the same rule is written in two places, a change must find both, and the day it misses one the program disagrees with itself without crashing. Give each fact one home: a named constant, one function. But duplication is about knowledge, not matching text. Two rules that look alike today and change for different reasons should stay apart, and it is usually worth waiting for a third copy before extracting. A shared helper that has grown a flag per caller is the wrong abstraction: split it back up.

Conditionals are the second. Nested ifs make the reader hold every open condition in their head. Turn failing cases into guard clauses and the cases read as a flat list. A long chain that compares one value against constants is data pretending to be logic: use a lookup table, and mind the order of its rows when the tests are ranges. Give a tangled and/or expression names, and return a condition directly instead of branching to true and false.

Long functions are the third. A comment that labels a block is a function name waiting to be used. Extract the block: what it reads becomes parameters, what it produces is returned. Extract a variable to name an expression. Inline a helper whose name says no more than its body.

Do one step at a time. Check, change one thing, check again, commit. A failure then has exactly one possible cause.

The classic pitfall is an extraction that forgets to hand its result back, or a reordering of steps that feed each other. Both look like tidying and both change the answer. An input near a limit, such as the free-shipping mark, is the one that shows it.

Unit 03 · 3 lessons

Data and state

Shape data so mistakes cannot hide, and keep changes where you can see them

  1. 01Data shapes
  2. 02Mutation and side effects
  3. BOSSWhen it goes wrong
Unit prize
  1. 01
    Data shapes

    Group what travels together; make wrong values impossible

  2. 02
    Mutation and side effects

    Who changed this list? Pure functions and copies

  3. BOSS
    When it goes wrong

    A bad row in a payments file, from silence to a useful report

Read the unit guide

Much unclear code is unclear because of its data. When values that belong together travel apart, every function that touches them has to keep them in step by hand, and one day one of them does not.

Group what travels together. Two lists that match by position fall out of step the first time one is sorted; a list of records sorts as one. A value picked out by position in a tuple breaks when a field is inserted; a named field does not. Give a field with a few legal values a fixed set of them, so a typo is rejected where it is written. And do not store what you can compute: a count kept next to its list is one fact written twice.

Then watch who changes what. A pure function works only from its arguments and only returns a value: same input, same output. A function that sorts the list it was handed, or reads a setting anyone can edit, gives answers that depend on what ran before. Assigning a list to a second name does not copy it, and a copy made with one call is one level deep: inner lists are still shared.

When something goes wrong, the worst reply is a quiet default. A bad amount turned into 0 joins the sum and the report is wrong with no error anywhere. Fail early and loudly: stop where you first can tell, and name the bad value and where it came from.

Tell expected outcomes from broken assumptions. A lookup that finds nothing is ordinary: return a value that says so and cannot be mistaken for real data, which rules out -1 for an age. A missing required file is not ordinary: stop.

The classic pitfall is a try wrapped around a whole loop. One bad row ends the loop and the rows after it are never looked at. Give each row its own try, keep the bad ones for a report, and nothing is swallowed.

Unit 04 · 3 lessons

Changing code safely

Reshape working code in small checked steps, and know when to stop

  1. 01A safety net
  2. 02Where code lives
  3. BOSSCode nobody wants to touch
Unit prize
  1. 01
    A safety net

    Record what the code does today, then move in small steps

  2. 02
    Where code lives

    Cohesion, coupling and which way the arrows point

  3. BOSS
    Code nobody wants to touch

    Find a seam, pin it, change one thing, repeat

Read the unit guide

Refactoring changes the shape of code and never its behaviour. Every move from the earlier units, a rename, an extraction, a guard clause, is a refactoring only if the program does exactly what it did before. So before you change the shape, you need a way to tell.

That way is a safety net: a handful of inputs with the outputs the code gives today, written down and quick to run. Record what it does, not what it should do. An odd result may be a bug, and some caller may depend on it; deciding that is a separate change. Pin effects as well as return values, and include the awkward inputs: amounts that do not divide evenly, values right at a limit, doubled spaces.

Then take small steps. Run the pins after each edit and a failure has one suspect. Keep reshaping and new behaviour in separate commits: in a refactoring any changed result is a mistake, in a feature some results change on purpose, and mixed together you cannot tell which is which. Prefer this to a rewrite from nothing, which throws away every small fix the old code has collected.

Where code lives matters as much as how it reads. A module should hold things that change for the same reason, and know little about other modules. Point dependencies at what is stable, avoid cycles, and keep the public surface small: whatever nobody outside can call, you can reshape freely. A function that uses only the data of another module wants to move there.

For code nobody wants to touch, the routine is: find a seam where a part can be split off without changing the result, pin that part, change one thing, repeat. Keep the old name as a thin wrapper so callers move one at a time and every state in between can be released.

The pitfall is not knowing when to stop. Clean the path your change travels through. Code that works and that nobody needs to change earns nothing from being tidied.

Learn Clean Code & Refactoring on your phone.

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy