# Topic covered
* Clean Code
* Why Clean Code?
* Why write bad code?
* Meaningful Names
* Functions rules
* Comments rules
* Code smells

2.1 Clean Code

Code Review

The very first step towards creating long-lasting software is figuring out how to write clean code.

  • Clean code can be understood easily – by everyone on the team.
  • Clean code is simple and direct. Clean code reads like well-written prose
  • Clean code always looks like it was written by someone who cares.

With understandability comes readability, changeability, extensibility and maintainability.

2.2 Why Clean Code

  • The total cost of owning a mess compounds over time.
  • Can go fast on Clean code.
    • In messy codebases it can take days or weeks to accomplish tasks that should only take hours.
  • Clean code does one thing well. Bad code tries to do too much.
  • Clean code is well-tested.
  • When reading well-written code, every function does pretty much what you expected.
  • Code is read far more often than it is written. Code that is easier to read is easier to change.

2.3 Why write bad code?

  • Are you in a rush?
  • Do you try to go “fast”?
  • Don’t you have time to do a good job?
  • Are you tired of work in the same program/module?
  • Does your Boss push you to finish soon?

2.4 Meaningful Names

1. Use Intention-Revealing Names

  • The name d reveals nothing.
int d; // elapsed time in days
  • We should choose a name that specifies what is being measured and the unit of that measurement
int elapsedTimeInDays;
int daysSinceCreation;

2. Avoid Disinformation

Do not refer to a grouping of accounts as an accountList unless it’s actually a List. The word List means something specific to programmers.

If the container holding the accounts is not actually a List, it may lead to false conclusions. So accountGroup or bunchOfAccounts or just plain accounts would be better.

3. Make Meaningful Distinctions

You can’t use the same name to refer to two different things in the same scope, you might be tempted to change one name in an arbitrary way or using Noise words.

Imagine that you have a Product class. If you have another called ProductInfo or ProductData, you have made the names different without making them mean anything different. Info and Data are indistinct noise words like a, an, and the .

4. Uses general words

  • Don’t use the name whack() to mean kill(). Don’t tell little culture-dependent jokes like eatMyShorts() to mean abort().
* Choose descriptive and unambiguous names.
* Make meaningful distinction.
* Use pronounceable names.
* Use searchable names.
* Replace magic numbers with named constants.
* Avoid encodings. Don't append prefixes or type information.

5. Class and Method Names

  • Classes and objects should have noun or noun phrase names like Customer, WikiPage, Account, and AddressParser
  • Methods should have verb or verb phrase names like postPayment, deletePage or save

2.5 Functions rules

Functions are the verbs of that language, and classes are the nouns.

1. Do one thing

  • Function should be Small.
  • Function should do one thing, do it well, do it only.

2. Use descriptive names

  • A long descriptive name is better than a short enigmatic name and long descriptive comment
  • It should explain what the function is doing

3. Prefer fewer arguments

  • Limit the number of arguments a function accepts, max 3.

4. Don’t use flag arguments

  • Split method into several independent methods that can be called from the client without the flag.

2.6 Comments rules

1. Explain yourself in code not in comments

// Check to see if the employee is eligible for full benefits
if ((employee.flags & HOURLY_FLAG) && (employee.age > 65))

// Or this?
if (employee.isEligibleForFullBenefits())

2. Good Comments

  • Legal Comments
// Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved.
// Released under the terms of the GNU General Public License version 2 or later.
  • Informative Comments
// Returns an instance of the Responder being tested.
protected abstract Responder responderInstance();
  • Warning of Consequences
// Don't run unless you have some time to kill.
public void _testWithReallyBigFile()
{
writeLinesToFile(10000000);
....
}


public static SimpleDateFormat makeStandardHttpDateFormat()
{
//SimpleDateFormat is not thread safe,
//so we need to create each instance independently.
SimpleDateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
return df;
}

3. Bad Comments

  • Mandated Comments
    • It is just plain silly to have a rule that says that every function must have a doc, or every variable must have a comment.
/**
* @param title The title of the CD
* @param author The author of the CD
*/
public void addCD(String title, String author,
int tracks, int durationInMinutes) {
CD cd = new CD();
cd.title = title;
cd.author = author;
}
  • Journal Comments
    • Sometimes people add a comment to the start of a module every time they edit it.
    • This is handled by git
  • Commented-Out Code
    • Don’t keep commented code
    • Others who see that commented-out code won’t have the courage to delete it.
    • They’ll think it is there for a reason and is too important to delete.
    • So commented-out code gathers like dregs at the bottom of a bad bottle of wine.
InputStreamResponse response = new InputStreamResponse();
response.setBody(formatter.getResultStream(), formatter.getByteCount());
// InputStream resultsStream = formatter.getResultStream();
// StreamReader reader = new StreamReader(resultsStream);
// response.setContent(reader.read(formatter.getByteCount()));

2.7 Code smells

  • Rigidity
    • The software is difficult to change. A small change causes a cascade of subsequent changes.
  • Fragility
    • The software breaks in many places due to a single change.
  • Immobility
    • You cannot reuse parts of the code in other projects because of involved risks and high effort.
  • Needless Complexity
  • Needless Repetition
  • Opacity
    • The code is hard to understand.

2.8 Clean Code - Uncle Bob / Lesson 3

  • Don’t ship shit
    • When you release code, you will know it works, don’t guess it.
  • We will always be ready
    • Shorter sprint length might be better, cause we document well, test it, integrate it more frequently, and is ready to deploy it.
    • shippable, deployable, deliverable
  • Stable productivity
    • the longer the project goes, the slower you don’t get
    • if you do, because something is a mess
  • Inexpensive Adaptability
    • Be cheap and easy to make changes to the system. the cost of the change = k × the scope of the change
    • software = changable product, if not , it’s hardware
  • Continuous Improvement of the system
    • code to get better with time.
  • Fearless Competence
    • if code need to clean, clean it, don’t leave it.Test it.
    • Get green little test buttom
  • QA will(should) find nothing
    • Let QA automated
  • We cover for each other
    • Make sure someone can cover for you
    • Pairing - so code reviewing might consider to cancel
  • Honest Estimates
    • define the shape of what we don’t know
    • 3 number: best case, nominal case, worst case

2.9 Clean Code - Uncle Bob / Lesson 4

Test-driven development

  • Don’t write code until you write a test that fails, because the code doesn’t exist.
  • Don’t write more of a test that is sufficient to fail and “not compiling” is the failure.
  • Don’t write code that is sufficient to pass the failing test.
  • Test but don’t debug
  • Test code is the code example
  • testable ←→ decoupled
  • TDD is double entry bookkeeping, they both do it twice.
  • Mutation test
  • Production code → more general, Test code → more specific
  • Don’t run into the gold when writing test code, as long as you can.
  • Learn TDD externally at first.

Reference