Loading presentation...

Present Remotely

Send the link below via email or IM

Copy

Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.

DeleteCancel

Make your likes visible on Facebook?

Connect your Facebook account to Prezi and let your likes appear on your timeline.
You can change this under Settings & Account at any time.

No, thanks

CleanCode

No description
by

elieone choiseul

on 10 February 2014

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of CleanCode

Carmelita G. Relles
Clean Coding
PROVIDING
COMMENTS

GOOD FORMATTING
Clean Code
SMALL & USEFUL
FUNCTIONS

THANKS
FOR LISTENING!
QUESTIONS?
UNIT
TESTING
ERROR
HANDLING
OBJECTS AND
DATASTRUCTS


Create Team Rules
Measurement in terms of columns (number of character)
Herman Hollerith’s 80 characters is arbitrary
Ideally less than 100, not more than 120

Horizontal Formatting
Measurement in terms of lines / rows
Ideally 50-100 lines, should not be more than 500 lines
Smaller files are usually easier to understand

Vertical Formatting
if(isPaid() || (!isPaid() && isScholar()){

//int x = y;

}
Omit Unnecessary Codes
SOLID
Principle

depend upon Abstractions, not upon concretions
SOLID
Principle

many client specific interfaces are better than one general purpose interface
SOLID
Principle

objects in a program should be replaceable with instances
of their subtypes without altering the correctness of that program
SOLID
Principle

software entities should be open for extension, but closed for modification
SOLID
Principle

an object should
have only a single responsibility
SOLID
Principle
Methods
Must start with a verb
Mixed case, starting with lowercase
Starts with “get” or “set” when appropriate, “is” when it returns a boolean
e.g. isPassingGrade(), getCustomerId(), setName()
General
Acronyms are written in mixed case
e.g. exportHtmlSource(), generatePdf()
Commonly Used
Naming Conventions
Classes
Noun, mixed case, starting with uppercase
e.g. ClientInformation
Variables
Noun, mixed case, starting with lowercase
e.g. activeCustomer
Constants
All uppercase, with underscores to separate words
e.g. MAX_MEMORY_CAPACITY
Commonly Used
Naming Conventions
MEANINGFUL
NAMES
try
{
int balance =
Interger.parseInt(inputString);

}catch(Exception e){
/*DO NOTHING*/
}

Never A Lazy Catch

Avoid Deep Nesting
int a = 1;
if (O == l)
a = O1;
else
l = 01;

Avoid Disinformation
Readable
Extensible
Atomic
Testable
Objects with no other methods aside from those which gets / sets the values of its attributes
class Subscriber{
String name;
int age;

getName(){return name;}
getAge(){return age;}
setName(String name){this.name = name;}
setAge(int age){this.age = age;}
}
Use Data Transfer Objects
FACT: The ratio of time spent in reading VS. writing code is 10:1
TO GO FAST IS TO GO WELL.
@Test
public void testGetVolume(){

int resultingVolume =
RectangularPrism.getVolume(1,2,3);

assertEquals(6, resultingVolume);

}
//Class RectangularPrism

public static int getVolume(
int length, int width, int height){

return length*width*height;

}

Maintain a Set of Tests
try
{
int balance =
Interger.parseInt(inputString);

}catch(Exception e){
/*DO NOTHING*/
}
try
{
int balance =
Interger.parseInt(inputString);

}catch(Exception e){
return null;
}

Do Not Return a Null Value
public int getTotalBalance()
throws InvalidValueException
{
if(type == CUSTOMER_TENANT){
/*CODE HERE*/
}
else if (type==CUSTOMER_OWNER){
/*DIFFERENT CODE HERE*/
}
else{
throw InvalidValueException();
}
}
public int getTotalBalance()
{
if(type == CUSTOMER_TENANT){
/*CODE HERE*/
}
else if (type==CUSTOMER_OWNER){
/*DIFFERENT CODE HERE*/
}
else{
return ERROR_INVALID;
}
}
Throw Exceptions instead of
Returning Error Codes
abstract class Customer{
abstract int getTotalBalance();
}

class Tenant extends Customer{
public int getTotalBalance(){…}
}

class Owner extends Customer{
public int getTotalBalance(){…}
}
class Customer{

public void getTotalBalance(){
if(type == CUSTOMER_TENANT){
/*CODE HERE*/
}
else if (type==CUSTOMER_OWNER){
/*DIFFERENT CODE HERE*/
}
else{

}
}
}

Maximize Use of Polymorphism
public void sortMail(){

if(mailBox.isEmpty)
return;
for(Mail mail : mailBox){
if(mail.isWorkRelated()){
putInWorkFolder(mail);
}
else if(mail.isFromFamily);
putInPersonalFolder();
}

} //Missing bracket!
public void sortMail()
{
if(mailBox.isEmpty)
return;
for(Mail mail : mailBox){
if(mail.isWorkRelated()){
putInWorkFolder(mail);
}else if(mail.isFromFamily);
putInPersonalFolder();
}

Observe Proper Indents
if(employee.isEligibleForBenefit())
{
//TODO:
//add implementation once formula is ready
}

TODO Comments
if(employee.isEligibleForBenefit())
{
/*CODE HERE*/
}
//Check to see if the employee is
//eligible for benefit
if(employee.flags & HOURLY_FLAG) && (employee.getAge() > 65)
{
/*CODE HERE*/
}

Explain Yourself In Code
//THIS IS BETTER:
myCollection.remove(object);
boolean present = myCollection.remove(object);

Don't preserve return values you don't use
public int getVolume(int length,
int width, int height){

return length*width*height;

}
public void getVolume(int volume,
int area, int length, int width, int height){

area = length*height;
volume = length*width*height;

}

Avoid Output Arguments
public void enrollOldStudent(int studentId)
{
Student student = Student.getRecord(studentId);

if(student.hasFailingGrades(){

} else {

}
}
public void enrollOldStudent(int studentId, boolean hasFailingGrades)
{
if(hasFailingGrades){

} else {

}
}

Do Not Use Boolean Parameters
public void doMorningRoutine()
{
haveBreakfast();
brushTeeth();
takeBath();
}
public void haveBreakfast()
{
eat();
drink();
}
public void haveBreakfast()
{
eat(Food chosenFood);
drink(Drink chosenDrink);
brushTeethAndTakeBath();
}

Methods should do
ONLY ONE thing
Date generationTimeStamp;
Date modificationTimeStamp;
int recordId = 0;
Date genymdhms;
Date modymdhms;
int pzqint = 0;

Use Pronounceable Names
Customer customer = new Customer();

customer.setName();
customer.setAddress();
Customer customer = new Customer();

customer.setCustomerName();
customer.setCustomerAddress();
int daysElapsed;

double accumulatedInterest
= ( amountPayable * interest ) * (daysElapsed);
int d; //days elapsed

double x = ( a * b ) * (d);

Use Intention-Revealing Names
Types of Functions Based On Arguments

NILADIC – zero argument
MONADIC – one argument
DYADIC – two arguments
TRIADIC – three arguments
POLYADIC – more than three arguments
public void addNumbers(int … x){}

public void displayCustomerDetails( Customer customer ){}
public void addNumbers(int x, int x1, int x2, int x3, int x4){}

public void displayCustomerDetails(String name, String contactInfo, int age
/*more arguments here */){}

Avoid Too Much Parameters
System.out.println(Constants.LOG_NAME + customer.name);
System.out.println(Constants.LOG_ADDRESS + customer.address);
System.out.println(Constants.LOG_CONTACT_INFO + customer.contactInfo);
//CLASS: Constants
public static final LOG_NAME= “Name: ”;
public static final LOG_ADDRESS = “Address: ”;
public static final LOG_CONTACT_INFO = “Contact Info: ”;
System.out.println(“Name: “ + customer.name);
System.out.println(“Address: “ + customer.address);
System.out.println(“Contact Info: “ + customer.contactInfo);

Reuse Strings As Much As Possible
//CONSTANTS.class
public static final ACCOUNT_STATE_INACTIVE = 1;
public static final ACCOUNT_STATE_ACTIVE = 2;
public static final ACCOUNT_STATE_TERMINATED = 3;
int accountState;

accountState = Constants.ACCOUNT_STATE_ACTIVE;
int accountState;

accountState = 2;
Avoid Mental Mapping
compute();
add();
delete();
doThis();
computeAverageGrade();
addCustomerToActiveList();
deleteSubscriberFromDB();
executeMemoryCleanUp();
asdf();
eto();
kagebunshin();
chuvaness();

Make Clear Distinctions
public boolean comparePolynomials(int x) {
//DECLARE VARIABLES, PARAMETERS
float  y_line, y_quadratic;
float  lineParam   = [0.1, 0.3];
float  quadParam = [2.1, 5.3, 0.22];

//CALCULATE THE LINE AND QUADRATIC VALUES AT X
y_line      = lineParam[0]*x + lineParam[1];
y_quadratic = quadParam[0]*x^2 + quadParam[1]*x + quadParam[2];

//COMPARE THE FUNCTIONS, RETURNING A BOOLEAN
return(y_line > y_quadratic);
}
public boolean comppoly (int x) {
float y1, y2;
float a1=0.1, b1=0.3, a2=2.1, b2=5.3, c=0.22;
y1 = a1*x + b1;
y2 = a1*x^2 + b2*x + c;
return(y2>y1);
}
Law of Demeter states that a class should know nothing about the innards of object it manipulates
Processor.getSubscriberBalance();

public int getSubscriberBalance(){
transaction.getSubscriberBalance();
}

public int getSubscriberBalance(){
subscriber.getBalance();
}
Processor.getTransaction().getSubsriber() .getBalance();
Avoid Train Wrecks
WHY DID YOU WRITE IT?

Imports

Class variables

Instance variables

Constructors


Static methods


Object methods

Vertical Ordering
/*Once upon a time in a far, far away land, a girl named Cinderella was cleaning their house*/
public void cleanHouse (){}
// ACTIONS ////////////////////////
public void eatMyDust (){

}
//Check if employee is eligible for
//the benefit
if(employee.isEligibleForBenefit())
{
//TODO: use method from groupmate
}
/*This Method gets the Name of the Student*/
public void getStudentName(){

}

Comments to Avoid
int average1 = calcAverage(array1);
int average2 = calcAverage(array2);

int calcAverage (int* arrayOfIntegers)
{
int sum = 0;
for (int i = 0; i < arrayOfIntegers.size(); i++)
{
sum += arrayOfIntegers[i];
}
return sum/arrayOfIntegers.size();
}
int sum1 = 0, sum2 = 0;
int average1 = 0, average2 = 0;

for (int i = 0; i < 4; i++)
{
sum1 += array1[i];
}
average1 = sum1/4;

for (int i = 0; i < 4; i++)
{
sum2 += array2[i];
}
average2 = sum2/4;
Don’t Repeat Yourself (DRY)
a.k.a. Duplication is Evil (DIE)
A blank space
in between sections
In between methods

Vertical Distance
HAVE YOU EVER
BEEN IMPEDED BY
BAD CODE?
“Hello World!”
“Hello!”
HEAP
STACK
customerName
System.out.println(“Name: “ + customer.name);
System.out.println(“Address: “ + customer.address);
System.out.println(“Contact Info: “ + customer.contactInfo);

Reuse Strings As Much As Possible
PROFESSION
a set of rules that you follow;
a discipline to do a certain job well.
February 11, 2014
PART OF OUR PROFESSION
IS TO WRITE CLEAN CODE.
WE ARE CLOSE TO THE END
..OF CODE.
THERE WILL BE CODE.
Grand Redesign
What is
CLEAN CODE?
How to measure
CODE QUALITY

Methods
should do that
ONE THING well.
THANKS FOR LISTENING!
Full transcript