Introducing 

Prezi AI.

Your new presentation assistant.

Refine, enhance, and tailor your content, source relevant images, and edit visuals quicker than ever before.

Loading…
Transcript

Clean code

Naming

an introduction to Robert C. Martins

Classnames should be nouns: Customer

Methodnames should contain verbs: getName()

No abbrevations

Christian Engvall (@crilleengvall)

http://www.christianengvall.se/

int d; // elapsed time in days

Bad:

Good:

int elapsedTimeInDays;

Comments are lies

They get old and misleading over time

As small as possible!

Max 10 lines of code

Methods

Do only one thing

If/else

if(myBool) {

callToMethod();

}

else {

callToAnotherMethod();

}

The book

The site

Try/catch

arguments

Pass no more than three arguments

http://www.cleancoders.com/

http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/

public void delete(Customer customer) {

try{

deleteCustomer(customer);

}

catch(Exception error) {

logError(error);

}

}

No output arguments

private void logError(Exception error)

{

logger.log(error);

}

Don't pass booleans

Thoughts

DeleteEmployee(“Bob”, false, true);

Refresh your clean code habits now and then

You will probably thank yourself when needing to maintain the code you just wrote.

After a while it's easy to cut corners when clean coding, especially when maintaining legacy systems.

Example

code from http://softhouseeducation.com/produkt/clean-code-fem-minuter

return

The boy scout rule

Only one exit

Always leave the campground cleaner than you found it.

public void setupCall(PhoneNumber number) {

Exchange exchange = findExchange(number);

exchange.dial(number);

}

public class PhoneNumber {

private String number;

public PhoneNumber(String number) throws InvalidNumber {

validate(number);

this.number = number;

}

private validate(string number) {

hasCorrectLength(number);

containsOnlyDigits(number);

}

}

Don't return null

public void setupCall(String phoneNo) {

// Validate that number has correct length

if ( phoneNo.length() < 10 || phoneNo.length() > 18 ) {

throw new CallException(“Phone number must be between 10-18 digits long!”);

}

// Validate that number only has digits

if ( ! Pattern.matches(“^\\d*$”, phoneNo) ) {

throw new CallException(“Phone number is not a digit!”);

}

String countryCode = null; String areaCode;

if ( phoneNo.startsWith(“00”) ) { // International number

countryCode = phoneNo.substring(2, 2);

areaCode = phoneNo.substring(3,3);

} else {

areaCode = phoneNo.substring(0, 3);

}

Exchange exchange = findExchange(countryCode, areaCode);

exchange.dial(phoneNo);

}

No need to check for null:

unnecessary:

List <Employee> employees = getEmployees();

foreach(employee in employees) {

employee.raiseSalary();

}

List<Employee> employees = getEmployees();

if(employees != null) {

foreach(employee in employees){

employee.raiseSalary();

}

}

Learn more about creating dynamic, engaging presentations with Prezi