SlideShare a Scribd company logo
CLEAN CODE A handbook of agile
software craftsmanship
THE BOOK
WHAT IS CLEAN CODE?
GOOD VS BAD?
for (int j=0; j<34; j++) {
s += (t[j]*4)/5;
}
int realDaysPerIdealDay = 4;
const int WORK_DAYS_PER_WEEK = 5;
int sum = 0;
for (int j=0; j < NUMBER_OF_TASKS; j++) {
int realTaskDays = taskEstimate[j] * realDaysPerIdealDay;
int realTaskWeeks = (realdays /
WORK_DAYS_PER_WEEK);
sum += realTaskWeeks;
}
NAMING
1) Use intention-revealing names
2) The bigger the scope of the variable, the longer the name should
be
3) Use pronounceable and searchable names
4) Class and object names should be nouns or noun phrases
5) Method names should be verbs or verb phrases
WHAT IS THE PROBLEM?
public class UserValidator {
private Cryptographer cryptographer;
public boolean checkPassword(String userName, String password) {
User user = UserGateway.findByName(userName);
if (user != User.NULL) {
String codedPhrase = user.getPhraseEncodedByPassword();
String phrase = cryptographer.decrypt(codedPhrase, password);
if ("Valid Password".equals(phrase)) {
Session.initialize();
return true;
}
}
return false;
}
}
FUNCTIONS
1) Function should be small. Ask yourself can it be smaller?
2) Should do only one thing
3) Should have descriptive names
4) Optimally should have zero arguments or 1 or 2. Avoid function
with more than 2 arguments => easy to read, reason and test
5) Avoid flag arguments
6) Have no side effects
7) Arguments should be inputs not outputs:
appendFooter(report) vs report.appendFooter()
8) Prefer exceptions to returning error codes to avoid deep nested
structures and Enum class
9) Extract error handling
DO YOU NEED COMMENTS?
// Check to see if the employee is eligible
for full benefits
if ((employee.flags & HOURLY_FLAG)
&& (employee.age > 65))
if (employee.isEligibleForFullBenefits())
WHEN DO WE NEED COMMENTS
1) Legal terms (copyright, …)
2) Explanation, clarification
// format matched kk:mm:ss EEE, MMM dd, yyyy
Pattern timeMatcher = Pattern.compile("d*:d*:d* w*, w* d*, d*");
3) Warning of bad consequence
expedia engine
4) TODO comments
5) Javadocs for public APIs
FORMATTING
1) Vertical openness between concepts
2) Lines of code that are tightly related should appear vertically dense
3) Variables should be declared as close to their usage as possible
4) If one function calls another, they should be vertically close
5) Indentation based on hierarchy of scopes
python enforces it
HOW CAN YOU IMPROVE THIS
CODE?ACMEPort port = new ACMEPort(12);
try {
port.open();
} catch (DeviceResponseException e) {
reportPortError(e);
logger.log("Device response exception", e);
} catch (ATM1212UnlockedException e) {
reportPortError(e);
logger.log("Unlock exception", e);
} catch (GMXError e) {
reportPortError(e);
logger.log("Device response exception");
} finally {
…
}
ERROR HANDLING
1) Better raise exception than returning error codes
2) Provide context with the exceptions through error message or log
message
3) Define custom exceptions in terms of caller’s needs
4) Don’t return null
3 LAWS OF TDD
First Law You may not write production code until you have written a
failing unit test.
Second Law You may not write more of a unit test than is sufficient to
fail, and not compiling is failing.
Third Law You may not write more production code than is sufficient
to pass the currently failing test.
UNIT TEST
1) 1 assert per test?
2) Single concept per test
3) Unit tests should be F.I.R.S.T
Fast Tests should be fast. They should run quickly
Independent Tests should not depend on each other.
Repeatable Tests should be repeatable in any environment.
Self-Validating The tests should have a boolean output. Either they
pass or fail.
Timely The tests need to be written in a timely fashion. Unit tests
should be written just before the production code that makes them
pass.
CLASS
1) Class should be small
2) High cohesion between instance variables and methods
3) Open for extension, closed for changes
Is out FlightsTestCaseGenerator too big?

More Related Content

What's hot

C++ decision making
C++ decision makingC++ decision making
C++ decision makingZohaib Ahmed
 
Data structure scope of variables
Data structure scope of variablesData structure scope of variables
Data structure scope of variablesSaurav Kumar
 
Storage classes in c language
Storage classes in c languageStorage classes in c language
Storage classes in c languagetanmaymodi4
 
5. using variables, data, expressions and constants
5. using variables, data, expressions and constants5. using variables, data, expressions and constants
5. using variables, data, expressions and constantsCtOlaf
 
Virtual function
Virtual functionVirtual function
Virtual functionzindadili
 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c languagetanmaymodi4
 
Virtual function complete By Abdul Wahab (moon sheikh)
Virtual function complete By Abdul Wahab (moon sheikh)Virtual function complete By Abdul Wahab (moon sheikh)
Virtual function complete By Abdul Wahab (moon sheikh)MoonSheikh1
 
Presentation on nesting of loops
Presentation on nesting of loopsPresentation on nesting of loops
Presentation on nesting of loopsbsdeol28
 
Looping and switch cases
Looping and switch casesLooping and switch cases
Looping and switch casesMeoRamos
 
Frege Tutorial at JavaOne 2015
Frege Tutorial at JavaOne 2015Frege Tutorial at JavaOne 2015
Frege Tutorial at JavaOne 2015Dierk König
 
Storage classes in c++
Storage classes in c++Storage classes in c++
Storage classes in c++Jaspal Singh
 
C programming-apurbo datta
C programming-apurbo dattaC programming-apurbo datta
C programming-apurbo dattaApurbo Datta
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)Ritika Sharma
 
Preprocessor directives in c language
Preprocessor directives in c languagePreprocessor directives in c language
Preprocessor directives in c languagetanmaymodi4
 
Control Statements, Array, Pointer, Structures
Control Statements, Array, Pointer, StructuresControl Statements, Array, Pointer, Structures
Control Statements, Array, Pointer, Structuresindra Kishor
 

What's hot (19)

C++ decision making
C++ decision makingC++ decision making
C++ decision making
 
Data structure scope of variables
Data structure scope of variablesData structure scope of variables
Data structure scope of variables
 
Storage classes in c language
Storage classes in c languageStorage classes in c language
Storage classes in c language
 
5. using variables, data, expressions and constants
5. using variables, data, expressions and constants5. using variables, data, expressions and constants
5. using variables, data, expressions and constants
 
Virtual function
Virtual functionVirtual function
Virtual function
 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c language
 
Lecture 13 - Storage Classes
Lecture 13 - Storage ClassesLecture 13 - Storage Classes
Lecture 13 - Storage Classes
 
Unit3 cspc
Unit3 cspcUnit3 cspc
Unit3 cspc
 
Virtual function complete By Abdul Wahab (moon sheikh)
Virtual function complete By Abdul Wahab (moon sheikh)Virtual function complete By Abdul Wahab (moon sheikh)
Virtual function complete By Abdul Wahab (moon sheikh)
 
Presentation on nesting of loops
Presentation on nesting of loopsPresentation on nesting of loops
Presentation on nesting of loops
 
Looping and switch cases
Looping and switch casesLooping and switch cases
Looping and switch cases
 
Frege Tutorial at JavaOne 2015
Frege Tutorial at JavaOne 2015Frege Tutorial at JavaOne 2015
Frege Tutorial at JavaOne 2015
 
Lecture 14 - Scope Rules
Lecture 14 - Scope RulesLecture 14 - Scope Rules
Lecture 14 - Scope Rules
 
3 Function Overloading
3 Function Overloading3 Function Overloading
3 Function Overloading
 
Storage classes in c++
Storage classes in c++Storage classes in c++
Storage classes in c++
 
C programming-apurbo datta
C programming-apurbo dattaC programming-apurbo datta
C programming-apurbo datta
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)
 
Preprocessor directives in c language
Preprocessor directives in c languagePreprocessor directives in c language
Preprocessor directives in c language
 
Control Statements, Array, Pointer, Structures
Control Statements, Array, Pointer, StructuresControl Statements, Array, Pointer, Structures
Control Statements, Array, Pointer, Structures
 

Viewers also liked

Viewers also liked (14)

Effective engineer
Effective engineerEffective engineer
Effective engineer
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean code
Clean codeClean code
Clean code
 
Apache (XAMPP)
Apache (XAMPP)Apache (XAMPP)
Apache (XAMPP)
 
Nutas presentation
Nutas presentationNutas presentation
Nutas presentation
 
3Com 3C13634A
3Com 3C13634A3Com 3C13634A
3Com 3C13634A
 
The asquith group case study some statistics
The asquith group case study some statisticsThe asquith group case study some statistics
The asquith group case study some statistics
 
Informe final
Informe finalInforme final
Informe final
 
Presentation1
Presentation1Presentation1
Presentation1
 
Go4 set locker software official 2
Go4 set locker software official 2Go4 set locker software official 2
Go4 set locker software official 2
 
Anaesthesia for cdh
Anaesthesia for cdhAnaesthesia for cdh
Anaesthesia for cdh
 
TECNOLOGÍA
TECNOLOGÍA TECNOLOGÍA
TECNOLOGÍA
 
SALADARITY – sldrt.com
SALADARITY – sldrt.com SALADARITY – sldrt.com
SALADARITY – sldrt.com
 
Compromiso organizacional
Compromiso organizacionalCompromiso organizacional
Compromiso organizacional
 

Similar to Clean code

Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003R696
 
Finding bugs that matter with Findbugs
Finding bugs that matter with FindbugsFinding bugs that matter with Findbugs
Finding bugs that matter with FindbugsCarol McDonald
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Jeremiah Caballero - Introduction of Clean Code
Jeremiah Caballero - Introduction of Clean CodeJeremiah Caballero - Introduction of Clean Code
Jeremiah Caballero - Introduction of Clean CodeAwesome Ars Academia
 
Eric Lafortune - ProGuard: Optimizer and obfuscator in the Android SDK
Eric Lafortune - ProGuard: Optimizer and obfuscator in the Android SDKEric Lafortune - ProGuard: Optimizer and obfuscator in the Android SDK
Eric Lafortune - ProGuard: Optimizer and obfuscator in the Android SDKGuardSquare
 
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...Droidcon Berlin
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)David McCarter
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial javaTpoint s
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summaryEduardo Bergavera
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8Vince Vo
 
Stranger in These Parts. A Hired Gun in the JS Corral (JSConf US 2012)
Stranger in These Parts. A Hired Gun in the JS Corral (JSConf US 2012)Stranger in These Parts. A Hired Gun in the JS Corral (JSConf US 2012)
Stranger in These Parts. A Hired Gun in the JS Corral (JSConf US 2012)Igalia
 
OWF12/PAUG Conf Days Pro guard optimizer and obfuscator for android, eric l...
OWF12/PAUG Conf Days Pro guard   optimizer and obfuscator for android, eric l...OWF12/PAUG Conf Days Pro guard   optimizer and obfuscator for android, eric l...
OWF12/PAUG Conf Days Pro guard optimizer and obfuscator for android, eric l...Paris Open Source Summit
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Guillaume Laforge
 

Similar to Clean code (20)

Clean code
Clean codeClean code
Clean code
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
 
Rits Brown Bag - TypeScript
Rits Brown Bag - TypeScriptRits Brown Bag - TypeScript
Rits Brown Bag - TypeScript
 
Finding bugs that matter with Findbugs
Finding bugs that matter with FindbugsFinding bugs that matter with Findbugs
Finding bugs that matter with Findbugs
 
Clean Code 2
Clean Code 2Clean Code 2
Clean Code 2
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Jeremiah Caballero - Introduction of Clean Code
Jeremiah Caballero - Introduction of Clean CodeJeremiah Caballero - Introduction of Clean Code
Jeremiah Caballero - Introduction of Clean Code
 
Eric Lafortune - ProGuard: Optimizer and obfuscator in the Android SDK
Eric Lafortune - ProGuard: Optimizer and obfuscator in the Android SDKEric Lafortune - ProGuard: Optimizer and obfuscator in the Android SDK
Eric Lafortune - ProGuard: Optimizer and obfuscator in the Android SDK
 
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summary
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8
 
Generics_RIO.ppt
Generics_RIO.pptGenerics_RIO.ppt
Generics_RIO.ppt
 
Java generics final
Java generics finalJava generics final
Java generics final
 
Stranger in These Parts. A Hired Gun in the JS Corral (JSConf US 2012)
Stranger in These Parts. A Hired Gun in the JS Corral (JSConf US 2012)Stranger in These Parts. A Hired Gun in the JS Corral (JSConf US 2012)
Stranger in These Parts. A Hired Gun in the JS Corral (JSConf US 2012)
 
What's in a name
What's in a nameWhat's in a name
What's in a name
 
Core java
Core javaCore java
Core java
 
OWF12/PAUG Conf Days Pro guard optimizer and obfuscator for android, eric l...
OWF12/PAUG Conf Days Pro guard   optimizer and obfuscator for android, eric l...OWF12/PAUG Conf Days Pro guard   optimizer and obfuscator for android, eric l...
OWF12/PAUG Conf Days Pro guard optimizer and obfuscator for android, eric l...
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 

Recently uploaded

Scaling in conventional MOSFET for constant electric field and constant voltage
Scaling in conventional MOSFET for constant electric field and constant voltageScaling in conventional MOSFET for constant electric field and constant voltage
Scaling in conventional MOSFET for constant electric field and constant voltageRCC Institute of Information Technology
 
Natalia Rutkowska - BIM School Course in Kraków
Natalia Rutkowska - BIM School Course in KrakówNatalia Rutkowska - BIM School Course in Kraków
Natalia Rutkowska - BIM School Course in Krakówbim.edu.pl
 
NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...
NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...
NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...Amil baba
 
Laundry management system project report.pdf
Laundry management system project report.pdfLaundry management system project report.pdf
Laundry management system project report.pdfKamal Acharya
 
Construction method of steel structure space frame .pptx
Construction method of steel structure space frame .pptxConstruction method of steel structure space frame .pptx
Construction method of steel structure space frame .pptxwendy cai
 
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical SolutionsRS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical SolutionsAtif Razi
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234AafreenAbuthahir2
 
KIT-601 Lecture Notes-UNIT-3.pdf Mining Data Stream
KIT-601 Lecture Notes-UNIT-3.pdf Mining Data StreamKIT-601 Lecture Notes-UNIT-3.pdf Mining Data Stream
KIT-601 Lecture Notes-UNIT-3.pdf Mining Data StreamDr. Radhey Shyam
 
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdf
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdfONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdf
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdfKamal Acharya
 
Arduino based vehicle speed tracker project
Arduino based vehicle speed tracker projectArduino based vehicle speed tracker project
Arduino based vehicle speed tracker projectRased Khan
 
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptxCloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptxMd. Shahidul Islam Prodhan
 
2024 DevOps Pro Europe - Growing at the edge
2024 DevOps Pro Europe - Growing at the edge2024 DevOps Pro Europe - Growing at the edge
2024 DevOps Pro Europe - Growing at the edgePaco Orozco
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwoodseandesed
 
KIT-601 Lecture Notes-UNIT-5.pdf Frame Works and Visualization
KIT-601 Lecture Notes-UNIT-5.pdf Frame Works and VisualizationKIT-601 Lecture Notes-UNIT-5.pdf Frame Works and Visualization
KIT-601 Lecture Notes-UNIT-5.pdf Frame Works and VisualizationDr. Radhey Shyam
 
Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdfKamal Acharya
 
Toll tax management system project report..pdf
Toll tax management system project report..pdfToll tax management system project report..pdf
Toll tax management system project report..pdfKamal Acharya
 
Online resume builder management system project report.pdf
Online resume builder management system project report.pdfOnline resume builder management system project report.pdf
Online resume builder management system project report.pdfKamal Acharya
 
Peek implant persentation - Copy (1).pdf
Peek implant persentation - Copy (1).pdfPeek implant persentation - Copy (1).pdf
Peek implant persentation - Copy (1).pdfAyahmorsy
 
Explosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdfExplosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdf884710SadaqatAli
 
Digital Signal Processing Lecture notes n.pdf
Digital Signal Processing Lecture notes n.pdfDigital Signal Processing Lecture notes n.pdf
Digital Signal Processing Lecture notes n.pdfAbrahamGadissa
 

Recently uploaded (20)

Scaling in conventional MOSFET for constant electric field and constant voltage
Scaling in conventional MOSFET for constant electric field and constant voltageScaling in conventional MOSFET for constant electric field and constant voltage
Scaling in conventional MOSFET for constant electric field and constant voltage
 
Natalia Rutkowska - BIM School Course in Kraków
Natalia Rutkowska - BIM School Course in KrakówNatalia Rutkowska - BIM School Course in Kraków
Natalia Rutkowska - BIM School Course in Kraków
 
NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...
NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...
NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...
 
Laundry management system project report.pdf
Laundry management system project report.pdfLaundry management system project report.pdf
Laundry management system project report.pdf
 
Construction method of steel structure space frame .pptx
Construction method of steel structure space frame .pptxConstruction method of steel structure space frame .pptx
Construction method of steel structure space frame .pptx
 
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical SolutionsRS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
KIT-601 Lecture Notes-UNIT-3.pdf Mining Data Stream
KIT-601 Lecture Notes-UNIT-3.pdf Mining Data StreamKIT-601 Lecture Notes-UNIT-3.pdf Mining Data Stream
KIT-601 Lecture Notes-UNIT-3.pdf Mining Data Stream
 
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdf
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdfONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdf
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdf
 
Arduino based vehicle speed tracker project
Arduino based vehicle speed tracker projectArduino based vehicle speed tracker project
Arduino based vehicle speed tracker project
 
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptxCloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
 
2024 DevOps Pro Europe - Growing at the edge
2024 DevOps Pro Europe - Growing at the edge2024 DevOps Pro Europe - Growing at the edge
2024 DevOps Pro Europe - Growing at the edge
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 
KIT-601 Lecture Notes-UNIT-5.pdf Frame Works and Visualization
KIT-601 Lecture Notes-UNIT-5.pdf Frame Works and VisualizationKIT-601 Lecture Notes-UNIT-5.pdf Frame Works and Visualization
KIT-601 Lecture Notes-UNIT-5.pdf Frame Works and Visualization
 
Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdf
 
Toll tax management system project report..pdf
Toll tax management system project report..pdfToll tax management system project report..pdf
Toll tax management system project report..pdf
 
Online resume builder management system project report.pdf
Online resume builder management system project report.pdfOnline resume builder management system project report.pdf
Online resume builder management system project report.pdf
 
Peek implant persentation - Copy (1).pdf
Peek implant persentation - Copy (1).pdfPeek implant persentation - Copy (1).pdf
Peek implant persentation - Copy (1).pdf
 
Explosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdfExplosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdf
 
Digital Signal Processing Lecture notes n.pdf
Digital Signal Processing Lecture notes n.pdfDigital Signal Processing Lecture notes n.pdf
Digital Signal Processing Lecture notes n.pdf
 

Clean code

  • 1. CLEAN CODE A handbook of agile software craftsmanship
  • 4. GOOD VS BAD? for (int j=0; j<34; j++) { s += (t[j]*4)/5; } int realDaysPerIdealDay = 4; const int WORK_DAYS_PER_WEEK = 5; int sum = 0; for (int j=0; j < NUMBER_OF_TASKS; j++) { int realTaskDays = taskEstimate[j] * realDaysPerIdealDay; int realTaskWeeks = (realdays / WORK_DAYS_PER_WEEK); sum += realTaskWeeks; }
  • 5. NAMING 1) Use intention-revealing names 2) The bigger the scope of the variable, the longer the name should be 3) Use pronounceable and searchable names 4) Class and object names should be nouns or noun phrases 5) Method names should be verbs or verb phrases
  • 6. WHAT IS THE PROBLEM? public class UserValidator { private Cryptographer cryptographer; public boolean checkPassword(String userName, String password) { User user = UserGateway.findByName(userName); if (user != User.NULL) { String codedPhrase = user.getPhraseEncodedByPassword(); String phrase = cryptographer.decrypt(codedPhrase, password); if ("Valid Password".equals(phrase)) { Session.initialize(); return true; } } return false; } }
  • 7. FUNCTIONS 1) Function should be small. Ask yourself can it be smaller? 2) Should do only one thing 3) Should have descriptive names 4) Optimally should have zero arguments or 1 or 2. Avoid function with more than 2 arguments => easy to read, reason and test 5) Avoid flag arguments 6) Have no side effects 7) Arguments should be inputs not outputs: appendFooter(report) vs report.appendFooter() 8) Prefer exceptions to returning error codes to avoid deep nested structures and Enum class 9) Extract error handling
  • 8. DO YOU NEED COMMENTS? // Check to see if the employee is eligible for full benefits if ((employee.flags & HOURLY_FLAG) && (employee.age > 65)) if (employee.isEligibleForFullBenefits())
  • 9. WHEN DO WE NEED COMMENTS 1) Legal terms (copyright, …) 2) Explanation, clarification // format matched kk:mm:ss EEE, MMM dd, yyyy Pattern timeMatcher = Pattern.compile("d*:d*:d* w*, w* d*, d*"); 3) Warning of bad consequence expedia engine 4) TODO comments 5) Javadocs for public APIs
  • 10. FORMATTING 1) Vertical openness between concepts 2) Lines of code that are tightly related should appear vertically dense 3) Variables should be declared as close to their usage as possible 4) If one function calls another, they should be vertically close 5) Indentation based on hierarchy of scopes python enforces it
  • 11. HOW CAN YOU IMPROVE THIS CODE?ACMEPort port = new ACMEPort(12); try { port.open(); } catch (DeviceResponseException e) { reportPortError(e); logger.log("Device response exception", e); } catch (ATM1212UnlockedException e) { reportPortError(e); logger.log("Unlock exception", e); } catch (GMXError e) { reportPortError(e); logger.log("Device response exception"); } finally { … }
  • 12. ERROR HANDLING 1) Better raise exception than returning error codes 2) Provide context with the exceptions through error message or log message 3) Define custom exceptions in terms of caller’s needs 4) Don’t return null
  • 13. 3 LAWS OF TDD First Law You may not write production code until you have written a failing unit test. Second Law You may not write more of a unit test than is sufficient to fail, and not compiling is failing. Third Law You may not write more production code than is sufficient to pass the currently failing test.
  • 14. UNIT TEST 1) 1 assert per test? 2) Single concept per test 3) Unit tests should be F.I.R.S.T Fast Tests should be fast. They should run quickly Independent Tests should not depend on each other. Repeatable Tests should be repeatable in any environment. Self-Validating The tests should have a boolean output. Either they pass or fail. Timely The tests need to be written in a timely fashion. Unit tests should be written just before the production code that makes them pass.
  • 15. CLASS 1) Class should be small 2) High cohesion between instance variables and methods 3) Open for extension, closed for changes Is out FlightsTestCaseGenerator too big?