AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE - CFObjective() 2017

Preview:

Citation preview

AN EXERCISE IN CLEANER CODEFROM LEGACY TO MAINTAINABLE

Gavin Pickincf.Objective() 2017

Who am I?Gavin Pickin – developing Web Apps since late 90s

● Software Consultant for Ortus Solutions● ContentBox Evangelist

What else do you need to know?

● Blog - http://www.gpickin.com● Twitter – http://twitter.com/gpickin● Github - https://github.com/gpickin

Let’s get on with the show.

Agenda

● What is clean code?● Lowering Cognitive Load● General Rules of Clean Code● Naming, Functions, Comments● Source Code, Formatting● Let’s look at some code

What is Clean CodeNot everyone can agree on what clean code is… but often people reference Uncle Bob’s book.

Robert C. Martin stated in his book Clean Code: A Handbook of Agile Software Craftsmanship, “Clean code is code that has been taken care of. Someone has taken the time to keep it simple and orderly. They have paid appropriate attention to details. They have cared.”

Simply, it is a quest for code that is easy to understand and easy to maintain.

"Any fool can write code that a computer can understand.

Good programmers write code that humans can understand."

- Martin Fowler

Lower the Cognitive LoadIn cognitive psychology, cognitive load refers to the total amount of mental effort being used in the working memory. Cognitive load theory was developed out of the study of problem solving by John Sweller in the late 1980s

Wikipedia: https://en.wikipedia.org/wiki/Cognitive_load

Lower the Cognitive LoadWhen reading code, make it easier on yourself:

● Abstract complexity● Single responsibility● Short, sweet and to the point● Be Consistent● Explanatory Variables and Function Names● Structure your Code to help readability● Use Coding Conventions

Don’t suffocate your code, let it breathe● When reading code, white space can be your friend.

● Let whitespace separate code that should be separated

● Let the lack of whitespace help you decide what code is connected.

General Rules of Clean Code● Remember, you write code one time, while the same code might be read

hundreds of times… code for the primary use case… make it readable. ● Decide on conventions, and stick to them. ● Coding by yourself overtime isn’t easy, in a team, it can be a nightmare.● KISS - Keep it Simple Stupid● Boy Scout Rules - Leave it cleaner than you found it● Look past the symptom, find the root problem or cause.

Naming Rules

There is a saying, that there are 2 really hard things in software engineering

● Cache Invalidation● Naming things● And 1 off errors

They were right, naming things is really hard.Let’s look at some rules to help with Naming

Naming Rules● Choose descriptive and unambiguous names.● Make names meaningful and distinct.● Use pronounceable names.● Use searchable names.● Replace magic numbers with named constants.● Try to avoid encodings and prefixes or type information● Don’t use Acronyms unless they are universal like URL.

Naming - Meaningful distinct name-- Do This --

customerAddress = getCustomerAddress()

dangerColor = ‘##FF0000’

-- Not this --

Ca = CustAddDetails()

redColor = “##FF0000”

Naming - ConstantsThey should all be in uppercase separated by underscores "_". Examples:

-- DO THIS --

INTERCEPTOR_POINTS = "";

LINE_SEP = "-";

MAX = "123";

-- NOT THIS --

interceptor-points = "";

line_sep = "d";

max = "123";

Naming - Acronyms and Abbreviations-- DO THIS --

URLScanner.cfc

parseHTTPString()

-- NOT THIS --

url-scanner.cfc

UrlScanner.cfc

parseHttpString()

ParseHttpString()

Naming - avoid prefixes suffixes-- Do This --

dayOfWeek = “thursday”

aUsers = getUsers( { active = true } );

-- Not this --

strDow = “thursday”

User-array = getUsers( { active = true } );

Functions● Keep the function Short and Sweet● Single responsibility - do one thing● Functions have names, use the same rules for naming functions● Try not to have too many arguments - use structs for more options.● Keep side effects to a minimum● Don’t use Flag arguments

○ Use separate methods that can be called from the client

● Use functions to hide complexity, to keep other functions short, sweet, and easier to understand

Functions - Too many arguments--Do this --

searchCars( { seats=4, minPrice = 20,000 } )

-- Not this --

searchCars( seats, color, maxPrice, minPrice, type, make )

Functions - Avoid Side Effectshttps://github.com/ryanmcdermott/clean-code-javascript#avoid-side-effects-part-1

Functions - Don’t use Flags - Bad

function createFile(name, temp) {

if (temp) {

fs.create(`./temp/${name}`);

} else {

fs.create(name);

}

}

Functions - Don’t use Flags - Good

function createFile(name) {

fs.create(name);

}

function createTempFile(name) {

createFile(`./temp/${name}`);

}

Comments● Try and let code speak for you where possible● Comments should add value and meaning to the code● Don’t add a comment that is redundant - ie save user● Don’t add comments just to add them, add value● Add comments in advance, not on closing braces● Don’t comment out code, remove it, that’s what Git is for● Explain the intent, not the actual implementation● Useful when explaining consequences or ramifications● ColdDoc will generate docs from javadoc styled comments

○ https://github.com/Ortus-Solutions/commandbox/blob/development/src/cfml/system/BaseCommand.cfc

○ http://apidocs.ortussolutions.com/commandbox/3.7.0/index.html

Structuring your Source Code● Separate your Code Concepts vertically in your Files● Variables should be declared close to where they are being used

○ This has changed from the old days, where top of the function was the preference. Although, which a short function, top should be close ;)

● Functions that are Dependant should be close to each other● Similar functions should be close to each other● Use indention consistently

Formatting● Everyone in the team should use the same conventions● If the language has conventions, use that

○ CFML doesn’t, that’s why Ortus has made theirs public.https://github.com/Ortus-Solutions/coding-standards

● Keep Lines short● Don’t modify a file just to format it… if you are adding to the file, then

format it

Resources

Ortus Conventions:https://github.com/Ortus-Solutions/coding-standards

Uncle Bob’s Clean Code on Amazon:http://amzn.to/2tfKL9C

Javascript Clean Code:https://github.com/ryanmcdermott/clean-code-javascript

Clean Code course on Pluralsight:https://www.pluralsight.com/courses/writing-clean-code-humans