We’ve all had those projects, the salvage project, the legacy project that we picked up, and wished we never had.
Was it written 5 years ago by that young dev with lots of passion but no big picture vision.
Was it written 6 months ago by another team, by a top gun developer who knows all the design patterns, and tried to future proof the app, only succeeding in making it impossible for anyone else to understand.
Or was it you, 2 years ago, before you joined the community and learned more about best (better) practices and you almost cannot comprehend how you used to code.
Long story short, we have all been there, but the past is history, how do we proceed from here, that’s the key. We’ll look at some of the ways you can clean up your code, and walk through some examples, and walk the journey to software craftsmanship
5 main points
What is clean code
Reading vs Writing Code
Don’t suffocate your code, let it breathe
Simple & Self Documenting Code
Lower the Cognitive Load
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE
1. AN EXERCISE IN CLEANER CODE
FROM LEGACY TO MAINTAINABLE
Gavin Pickin
cf.Objective() 2017
2. 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.
3. 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
4. What is Clean Code
Not 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.
5. "Any fool can write code that a
computer can understand.
Good programmers write code that
humans can understand."
- Martin Fowler
6. Lower the Cognitive Load
In 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
7. Lower the Cognitive Load
When 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
8. 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.
9. 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.
10. 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
11. 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.
12. Naming - Meaningful distinct name
-- Do This --
customerAddress = getCustomerAddress()
dangerColor = ‘##FF0000’
-- Not this --
Ca = CustAddDetails()
redColor = “##FF0000”
13. Naming - Constants
They 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";
14. Naming - Acronyms and Abbreviations
-- DO THIS --
URLScanner.cfc
parseHTTPString()
-- NOT THIS --
url-scanner.cfc
UrlScanner.cfc
parseHttpString()
ParseHttpString()
15. Naming - avoid prefixes suffixes
-- Do This --
dayOfWeek = “thursday”
aUsers = getUsers( { active = true } );
-- Not this --
strDow = “thursday”
User-array = getUsers( { active = true } );
16. 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
17. Functions - Too many arguments
--Do this --
searchCars( { seats=4, minPrice = 20,000 } )
-- Not this --
searchCars( seats, color, maxPrice, minPrice, type, make )
18. Functions - Avoid Side Effects
https://github.com/ryanmcdermott/clean-code-javascript#avoid-side-effects-part-1
19. Functions - Don’t use Flags - Bad
function createFile(name, temp) {
if (temp) {
fs.create(`./temp/${name}`);
} else {
fs.create(name);
}
}
20. Functions - Don’t use Flags - Good
function createFile(name) {
fs.create(name);
}
function createTempFile(name) {
createFile(`./temp/${name}`);
}
21. 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/BaseCom
mand.cfc
○ http://apidocs.ortussolutions.com/commandbox/3.7.0/index.html
22. 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
23. 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
25. Too much text
Not enough code?
Lets try a live example - live code
- we’re living dangerously
https://github.com/elpete/cb-module-
template/blob/master/commands/mo
dule/scaffold.cfc