Lilit Mkrtchyan
 Meaningful Names
 Functions
 Comments
 Formatting
 Error Handling
 Use intention-revealing names
 Avoid disinformation
 Make meaningful distinctions
Bad Good
// elapsed time in days
int d;
int elapsedTimeInDays;
Bad Good
Set accountList; Set accounts;
public static void copyChars(char a1[], char a2[]) {
for (int i = 0; i < a1.length; i++) {
a2[i] = a1[i];
}
}
 Use pronounceable names
 Use searchable names
Bad Good
class DtaRcrd102 {
private Date genymdhms;
private Date modymdhms;
private final String pszqint = "102";
/* ... */
};
class Customer {
private Date generationTimestamp;
private Date modificationTimestamp;
private final String recordId = "102";
/* ... */
};
Bad Good
for (int j=0; j<34; j++) {
s += (t[j]*4)/5;
}
int realDaysPerIdealDay = 4;
const int WORK_DAYS_PER_WEEK = 5;
int sum = 0;
for (int j=0; j < NUMBER_OF_TASKS; j++) {
int realTaskDays = taskEstimate[j] * realDaysPerIdealDay;
int realTaskWeeks = (realdays / WORK_DAYS_PER_WEEK);
sum += realTaskWeeks;
}
 Avoid encodings (Member prefixes)
 Hungarian notation
 Avoid mental mapping
Bad Good
public class Part {
// The textual description
private String m_dsc;
void setName(String name) {
m_dsc = name;
}
}
public class Part {
String description;
void setDescription(String description) {
this.description = description;
}
}
Bad Good
PhoneNumber phoneString;
// name not changed when type changed!
PhoneNumber phone;
Bad Good
for (a = 0; a < 10; a++)
for (b = 0; b < 10; b++)
for (i = 0; i < 10; i++)
for (j = 0; j < 10; j++)
 Class names
 Method names
Bad Good
Manager, Processor, Data, Info Customer, WikiPage, Account
postPayment, deletePage, save
 Small
 Do one thing
 Do not repeat yourself
 Blocks and indenting
 Use Descriptive Names
 Function Arguments
 Common Monadic Forms
150 characters per line
20 lines
Bad Good
void transform(StringBuffer out) StringBuffer transform(StringBuffer in)
 Prefer Exceptions to returning error codes
Bad Good
if (deletePage(page) == E_OK) {
if (registry.deleteReference(page.name) == E_OK) {
if (configKeys.deleteKey(page.name.makeKey()) == E_OK){
logger.log("page deleted");
} else {
logger.log("configKey not deleted");
}
} else {
logger.log("deleteReference from registry failed");
}
} else {
logger.log("delete failed");
return E_ERROR;
}
try {
deletePage(page);
registry.deleteReference(page.name);
configKeys.deleteKey(page.name.makeKey());
} catch (Exception e) {
logger.log(e.getMessage());
}
 Extract try/catch blocks
public void delete(Page page) {
try {
deletePageAndAllReferences(page);
} catch (Exception e) {
logError(e);
}
}
private void deletePageAndAllReferences(Page page) throws Exception {
deletePage(page);
registry.deleteReference(page.name);
configKeys.deleteKey(page.name.makeKey());
}
private void logError(Exception e) {
logger.log(e.getMessage());
}
 Comments do not make up for bad code
 Explain yourself in code
 Informative comments
 Legal comments
 Public API comments
 TODO comments
Bad Good
// Check to see if the employee is eligible for full
benefits
if ((employee.flags & HOURLY_FLAG) &&
(employee.age > 65))
if (employee.isEligibleForFullBenefits())
Bad Good
// Returns an instance of the Responder being tested.
protected abstract Responder responderInstance();
// renaming the function: responderBeingTested
// format matched kk:mm:ss EEE, MMM dd, yyyy
Pattern timeMatcher = Pattern.compile("d*:d*:d* w*, w* d*, d*");
 Journal Comments
 Noise comments
 Too Much Information
 Function Headers
 HTML Comments
 Commented-Out Code
 Attributions and Bylines
 Javadocs in Nonpublic Code
Bad
/**
* Default constructor.
*/
protected AnnualDateRule() { }
/** The day of the month. */
private int dayOfMonth;
 Vertical Distance
 Horizontal Alignment
Variables
Instance variables
Dependent functions
Bad Good
private Socket socket;
private InputStream input;
private OutputStream output;
private Socket socket;
private InputStream input;
private OutputStream output;
 Extract Try/Catch Blocks
 Error Handling Is One Thing
 Don’t Return Null
 Don’t Pass Null
Bad Good
List<Employee> employees = getEmployees();
if (employees != null) {
for(Employee e : employees) {
totalPay += e.getPay();
}
}
List<Employee> employees = getEmployees();
for(Employee e : employees) {
totalPay += e.getPay();
}
public List<Employee> getEmployees() {
if( .. there are no employees .. )
return Collections.emptyList();
}
Clean code

Clean code

  • 1.
  • 2.
     Meaningful Names Functions  Comments  Formatting  Error Handling
  • 4.
     Use intention-revealingnames  Avoid disinformation  Make meaningful distinctions Bad Good // elapsed time in days int d; int elapsedTimeInDays; Bad Good Set accountList; Set accounts; public static void copyChars(char a1[], char a2[]) { for (int i = 0; i < a1.length; i++) { a2[i] = a1[i]; } }
  • 5.
     Use pronounceablenames  Use searchable names Bad Good class DtaRcrd102 { private Date genymdhms; private Date modymdhms; private final String pszqint = "102"; /* ... */ }; class Customer { private Date generationTimestamp; private Date modificationTimestamp; private final String recordId = "102"; /* ... */ }; Bad Good for (int j=0; j<34; j++) { s += (t[j]*4)/5; } int realDaysPerIdealDay = 4; const int WORK_DAYS_PER_WEEK = 5; int sum = 0; for (int j=0; j < NUMBER_OF_TASKS; j++) { int realTaskDays = taskEstimate[j] * realDaysPerIdealDay; int realTaskWeeks = (realdays / WORK_DAYS_PER_WEEK); sum += realTaskWeeks; }
  • 6.
     Avoid encodings(Member prefixes)  Hungarian notation  Avoid mental mapping Bad Good public class Part { // The textual description private String m_dsc; void setName(String name) { m_dsc = name; } } public class Part { String description; void setDescription(String description) { this.description = description; } } Bad Good PhoneNumber phoneString; // name not changed when type changed! PhoneNumber phone; Bad Good for (a = 0; a < 10; a++) for (b = 0; b < 10; b++) for (i = 0; i < 10; i++) for (j = 0; j < 10; j++)
  • 7.
     Class names Method names Bad Good Manager, Processor, Data, Info Customer, WikiPage, Account postPayment, deletePage, save
  • 8.
     Small  Doone thing  Do not repeat yourself  Blocks and indenting  Use Descriptive Names  Function Arguments  Common Monadic Forms 150 characters per line 20 lines Bad Good void transform(StringBuffer out) StringBuffer transform(StringBuffer in)
  • 9.
     Prefer Exceptionsto returning error codes Bad Good if (deletePage(page) == E_OK) { if (registry.deleteReference(page.name) == E_OK) { if (configKeys.deleteKey(page.name.makeKey()) == E_OK){ logger.log("page deleted"); } else { logger.log("configKey not deleted"); } } else { logger.log("deleteReference from registry failed"); } } else { logger.log("delete failed"); return E_ERROR; } try { deletePage(page); registry.deleteReference(page.name); configKeys.deleteKey(page.name.makeKey()); } catch (Exception e) { logger.log(e.getMessage()); }
  • 10.
     Extract try/catchblocks public void delete(Page page) { try { deletePageAndAllReferences(page); } catch (Exception e) { logError(e); } } private void deletePageAndAllReferences(Page page) throws Exception { deletePage(page); registry.deleteReference(page.name); configKeys.deleteKey(page.name.makeKey()); } private void logError(Exception e) { logger.log(e.getMessage()); }
  • 11.
     Comments donot make up for bad code  Explain yourself in code  Informative comments  Legal comments  Public API comments  TODO comments Bad Good // Check to see if the employee is eligible for full benefits if ((employee.flags & HOURLY_FLAG) && (employee.age > 65)) if (employee.isEligibleForFullBenefits()) Bad Good // Returns an instance of the Responder being tested. protected abstract Responder responderInstance(); // renaming the function: responderBeingTested // format matched kk:mm:ss EEE, MMM dd, yyyy Pattern timeMatcher = Pattern.compile("d*:d*:d* w*, w* d*, d*");
  • 12.
     Journal Comments Noise comments  Too Much Information  Function Headers  HTML Comments  Commented-Out Code  Attributions and Bylines  Javadocs in Nonpublic Code Bad /** * Default constructor. */ protected AnnualDateRule() { } /** The day of the month. */ private int dayOfMonth;
  • 13.
     Vertical Distance Horizontal Alignment Variables Instance variables Dependent functions Bad Good private Socket socket; private InputStream input; private OutputStream output; private Socket socket; private InputStream input; private OutputStream output;
  • 14.
     Extract Try/CatchBlocks  Error Handling Is One Thing  Don’t Return Null  Don’t Pass Null Bad Good List<Employee> employees = getEmployees(); if (employees != null) { for(Employee e : employees) { totalPay += e.getPay(); } } List<Employee> employees = getEmployees(); for(Employee e : employees) { totalPay += e.getPay(); } public List<Employee> getEmployees() { if( .. there are no employees .. ) return Collections.emptyList(); }