OnClean Code
Taming the spaghetti monster
Presented By:
Fernando Zamora
Company Confidential – Do Not Duplicate 1
Agenda
What is clean code
Why it’s important
Philosophy
Cover a few topics on how to write cleaner code
– Names
– Functions
– Comments
Read code
Have Fun – there is no such thing as perfect code!!!!!
Exercises
Company Confidential – Do Not Duplicate 2
Clean Code What is it?
Testable and tested
Elegant
Efficient
Expressive
Expected
Readable
Minimal Dependencies
Maintainable
Self Documenting
Simple Company Confidential – Do Not Duplicate 3
Bad Code – What is it?
• Inappropriate Information (Regions)
• Obsolete Comments
• Redundant Comments
• Poorly Written Comments
• Commented out code
• Too many arguments
• Output arguments
• Flag arguments
• Dead functions
• Duplication
• Incorrect Behavior and Boundaries
• Code at wrong level of abstraction
• Base classes depending on their derivatives
• Too much information
• ….
Company Confidential – Do Not Duplicate 4
Why is Clean Code Important
1. Maintains fast productivity
2. It is costly to own a mess
3. Productivity decreases asymptotically eventually down to 0
4. Boy Scout Rule: Leave the code better than you found it
5. As the old saying goes:"Write your code as if the person that's going to
maintain it is a psychotic serial killer who knows where you live.“
6. Happier Developers
Company Confidential – Do Not Duplicate 5
Philosophy
1. Just like martial arts has many masters with different styles, so does Clean
Code **
Jeet Kune Do Drunken Master? Wing Chun
Code Complete S.O.L.I.D
TDD
Company Confidential – Do Not Duplicate 6
Philosophy
1. Principles and techniques
2. Code is a living design
3. Treat writing code as a craftsman
S.O.L.I.D REFACTOR
TDD DRY
Boy Scout
Company Confidential – Do Not Duplicate 7
Choosing Names
1. Meaningful names
2. Avoid Disinformation – hp,
3. Avoid small variations in names – s1, s2
4. Meaningful Distinctions
– if (!fundsAvailable || availableFunds < -0.004m)
5. Pronounceable Names - rptparam
6. Searchable Names – MAX_DAYS instead of 999
7. Avoid Encodings – e.g. Hungarian notation strName, strFName, Compiler
8. Function Names are verbs
9. Data fields are nouns
Company Confidential – Do Not Duplicate 8
Choosing Names
1. Interfaces and implementations – IShapeFactory, ShapeFactory
2. Avoid mental mapping – i, a, b, c
3. Class names should have noun names
4. Functions should have verb names
5. With overloaded constructors use static factory methods instead
6. Don’t be cute – e.g. EatMyShorts instead of Abort
7. One word per concept – get, fetch, retrieve
8. Use solution domain names – JobsQueue
9. Use problem domain names –
10. Avoid gratuitous content – Gas Station Deluxe gsdAccount, gsdName, …
11. Method names should describe everything they do in their name
1. Hint: If your method name is funky than probably your implementation is
as well
Company Confidential – Do Not Duplicate 9
Exercises Part I
1. Create method with implementation
Class Name: you decide
Method Name: MeetsMinimumAgeRequirements
Return Value: boolean
Parameters: Date of Birth, Minimum Age, Today’s Date
2. Create a method that calls a protected method
void PlaceOrder(string productId, int qty)
Class Name (hint): Order Service
Method Name: Replenish
Return Value: void
Parameters: you decide
Hint: Ordering service must be determine how much to order based on
existing quantity and optimum on hand quanities
Company Confidential – Do Not Duplicate 10
Functions Rules
1. Small
2. Smaller
3. Do one thing
4. Do it well
5. Do it only
6. One level of abstraction
7. Read from the top down like a set of To paragraphs
Company Confidential – Do Not Duplicate 11
Exercise Part 2 – Fix This Code
Scenario A: You have been tasked to find a bug in the
code. The users have identified that users cannot log in.
Whenever they try to login with a valid user name and
password the system just stays on the login screen.
Whenever they enter an invalid user or password they get
a message indicating that the login is not valid.
Scenario B: The users have also complained that when
logging in from the handheld, they don’t get a message in
either case. Instead the application throws a time out
exception without allowing them to log in.
You discovered the function where the bug occurs and you
discover that the function is shared by both logins.
Company Confidential – Do Not Duplicate 12
Exercise Part 2 – Fix This Code
• public bool CheckLogin(string userNme, string pwd, out string msg)
• {
• bool result = false;
• User usr = _repository.GetUser(userNme);
• msg = [Link];
• if(usr != null){
• if(_passwdHashSvc.HashMatches([Link], pwd)){
•
• }
• else{
• msg = "Invalid user or password";
• result = false;
• }
• }
• else{
• msg = "Invalid user or password";
• result = false;
• }
• if()
• [Link](msg);
• return false;
• }
Company Confidential – Do Not Duplicate 13
•
Function Rules
8. - Switch Statements
1. Reduce switch statements to single location by factory and polymorphism
2. Use polymorphic classes
9. Use Descriptive Names
3. Describe what the function is doing
4. Don’t be afraid to make it long
10. Be consistent in your names
11. Function Arguments
5. Ideal number is zero (nidalic)
6. One (monadic) – To transform is ok, but not as flag
7. Two (dyadic)
8. Three should be avoided where possible
12. Have no side effects
13. Return, Break, Continue do not have bad effect on small functions (Structured
Programming)
Company Confidential – Do Not Duplicate 14
Comments
1. Failure to express ourselves in code
2. Comments Lie
3. Comments are hard to maintain
4. The real truth is in the code
5. Don’t comment - Clean your code instead
//Check to see if order qualifies for a discount
If( [Link] == DISCOUNT_ITEM &&
[Link] == PREFERRED_CUSTOMER)
If([Link]())
Company Confidential – Do Not Duplicate 15
Comments
if (_RCCde == "D” || _RCCde == "L” || _RCCde == "K”)
{
…Do something
}
//The function name is more expressive … using domain language
//Makes RecoverableItem searchable also
if (IsRecoverableItem())
{
…Do Something
}
Company Confidential – Do Not Duplicate 16
Acceptable Comments
Acceptable Comments
1. Legal Comments – Copyright, etc
2. Informative Comments
3. Explanation of intent
4. Warning of consequences
5. TODO
6. Amplification
7. Self Documentation – Javadocs
Company Confidential – Do Not Duplicate 17
Unacceptable Comments
1. Mumbling
2. Redundant
3. Misleading Comments
4. Mandated Comments
5. Journal Comments – Not necessary with source control systems**
6. Noise Comments
7. Position Markers
8. Closing Brace Comments – Shorter Functions Instead
9. Attributions by line – Use Source Control
10. Commented out code
11. Too Much Information
12. …
Company Confidential – Do Not Duplicate 18
About Fernando Zamora
Sr. Software Engineer @ McLane Advanced Technologies
Personal Blog, Etc:
[Link]
Email:
[Link]@[Link]
[Link]@[Link]
Twitter:
@fernandozamoraj
Company Confidential – Do Not Duplicate LLC 19
Copyright 2008 McLane Advanced Technologies,