Clean Code
*all examples were taken from this book
*
• Naming • Designing methods • Code formatting • Commenting code
Let’s talk about…
Naming
Intention-revealing names
Bad
int d; // elapsed time in days
Good
int elapsedTimeInDays;
Good
Avoid disinformation
Bad
int a = l; if ( O == l )
a=O1;else
l=01;
Don’t use noise words (1)
Bad
getActiveAccount(); getActiveAccounts(); getActiveAccountInfo();
Use nouns when naming classesBad
class Manager { … }
class Processor { … }
class Provider { … }
GoodGoodclass UserManager { … }
class PaymentProcessor { … }
class LogParser { … }
Use verbs when naming methodsBad
public int sum(){ … }
public void valid() { … }
private void value() { … }
GoodGood
public int calculateSum() { … }
public boolean isValid() { … }
private setValue() { … }
Designingfunctions/methods
Bad
Do one thing at a time
…
if (isTestPage(pageData)) include(pageData, isSuite); return pageData.getHtml(); …
Bad
Use exceptions over control flow (1)
Good
Use exceptions over control flow (2)
Code formatting
Vertical space between concepts (1)
Bad
Good
Vertical space between concepts (2)
Optimal line length
• Python: <79 • Java: <80 • C++ (Google, GCC): <80 • Javascript: <80 • PHP: 75-85, <120
Use clear naming instead of comments
Bad
GoodGood
Good
Informative comments
Do you really need TODOs?
Javadoc for each function?
Bad
Noise comments
Comments are dangerous!
Comments are dangerous!