SlideShare a Scribd company logo
1 of 25
Clean Code
Chapter 3: Function
Kent Huang
Outline
• Case Study: HtmlUnit.java
• Small
• Switch
• Argument
• Error handle
• Structured Programming
• Conclusion
Case Studying
Sample Code
Listing 3-1
Sample Code
Listing 3-2
What’s different??
• What is it makes a function like Listing3-2 easy
to read and understand?
• How can we make a function communicate it
intent?
• What attribute can we give our functions
allow a casual reader to intuit the kind of
program they live inside?
Small
• Rules of functions:
– Should be small
– Should be smaller than that
• < 150 character per line
• < 20 lines
public static String renderPageWithSetupsAndTeardowns(
PageData pageData, boolean isSuite) throws Exception {
if (isTestPage(pageData))
includeSetupAndTeardownPages(pageData, isSuite);
return pageData.getHtml();
}
Do One Thing
• Functions should do one thing. They should do
it well. They should to it only.
• Listing 3-3 do three things
1. Determining whether the page is a test page.
2. If so, including setups and teardowns.
3. Rendering the page in HTML.
Is It?
• If a function does only those steps that are
one level below the stated name of the
function, then the function is doing one thing
• If you can extract another function from it
with a name that is not merely a restatement
of its implementation
One Level of Abstraction per Function
• In Listing3-1
– High level: getHtml(),PathParser.render(pagePath)
– Low level: .append(“n”)
• Broken windows
– Once details are mixed with essential concepts,
more and more details tend to accrete within the
function
Reading Code from Top to Bottom
• The Stepdown Rule:
– We can read the program, descending one level of
abstraction at a time as we read down the list of
functions
Switch Statements
public Money calculatePay(Employee e) throws InvalidEmployeeType {
switch (e.type) {
case COMMISSIONED:
return calculateCommissionedPay(e);
case HOURLY:
return calculateHourlyPay(e);
case SALARIED:
return calculateSalariedPay(e);
default:
throw new InvalidEmployeeType(e.type);
}
}
1. It’s large, and when new employee type are added, it will grow.
2. Does more than one thing.
3. Violates the Single Responsibility Principle
4. Violates the Open Closed Principle
5. There are an unlimited number of other functions will have same
structure.
public abstract class Employee {
public abstract boolean isPayday();
public abstract Money calculatePay();
public abstract void deliverPay(Money pay);
}
-----------------
public interface EmployeeFactory {
public Employee makeEmployee(EmployeeRecord r) throws InvalidEmployeeType;
}
-----------------
public class EmployeeFactoryImpl implements EmployeeFactory {
public Employee makeEmployee(EmployeeRecord r) throws InvalidEmployeeType {
switch (r.type) {
case COMMISSIONED:
return new CommissionedEmployee(r);
case HOURLY:
return new HourlyEmployee(r);
case SALARIED:
return new SalariedEmploye(r);
default:
throw new InvalidEmployeeType(r.type);
}
}
}
Use Descriptive Names
• Don’t be afraid to make a name long
• A long descriptive name is better than a long
descriptive comment
• Use the same phrases, nouns, and verbs in the
function names
– Ex: includeSetupAndTeardownPages, includeSetupPages,
includeSuiteSetupPage, includeSetupPage
Function Arguments
• The ideal number of arguments for a function
is zero (niladic).
0 > 1 > 2 > 3 >> 4
• Arguments are even harder from a testing
point of view.
Common Monadic Forms
• If a function is going to transform its input
argument, the transformation should appear
the return value
• StringBuffer transform(StringBuffer in)
• Void transform(StringBuffer out) 
Flag Arguments
• Flag arguments are ugly
rander(true) 
renderForSuite() 
renderForSingleTest() 
Dyadic Functions
• Function with two arguments is harder to
understand than one
– writeField(name) v.s writeField(outputStream, name)
• Some times, two arguments are appropriate.
– Point p = new Point(0,0);
• Still have problem
– assertEquals(expected, actual)
Triads
• Don’t use!!!
– assertEquals(message, expected, actual) 
• Argument Objects
– Circle makeCircle(double x, double y, double radius);
– Circle makeCircle(Point center, double radius);
Verbs and Keywords
• Choosing good names for a function can go a
long way toward explaining the intent of the
function and the order and intent of the
arguments.
– Write(name)
– WriteField(name)
– AssertEquals(expected, actual)
– AsertExpectedQqualsActual(expected,actual)
Have No Side Effects
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;
}
}
Output Arguments
• appendFooter(s);???
– public void appendFooter(StringBuffer report)
• report.appendFooter();
Command Query Separation
• if (set("username", "unclebob"))...
– public boolean set(String attribute, String value);
if (attributeExists("username")) {
setAttribute("username", "unclebob"); ...
}
Prefer Exceptions to Returning Error
Codes
if (deletePage(page) == E_OK) {
if (registry.deleteReference(page.name) == E_OK) {
if (configKeys.deleteKey(page.name.makeKey()) == E_OK){
logger.log("page deleted");
} else {
logger.log("configKey not deleted");
}
} else {
logger.log("deleteReference from registry failed"); }
} else {
logger.log("delete failed"); return E_ERROR;
}
try {
deletePage(page);
registry.deleteReference(page.name);
configKeys.deleteKey(page.name.makeKey());
}
catch (Exception e) {
logger.log(e.getMessage());
}
• Don’t Repeat Yourself
– Duplication may be the root of all evil in software
• Structured Programming
– Edsger Dijkstra’s rules
• One entry, one exist
• Never, ever, ant goto
– When function is small
• Multiple return, break, continue are ok
• Goto only makes sense in large functions
Conclusion
• Every system is built from a domain-specific
language
– Functions are the verbs of that language
– Classes are the nouns
• Master programmer do:
– Functions are short, well named and nicely
organized
– Never forget, your real goal is to tell the story of
the system
The End

More Related Content

What's hot

Clean Code Principles
Clean Code PrinciplesClean Code Principles
Clean Code PrinciplesYeurDreamin'
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable codeGeshan Manandhar
 
The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean codeVictor Rentea
 
Clean Lambdas & Streams in Java8
Clean Lambdas & Streams in Java8Clean Lambdas & Streams in Java8
Clean Lambdas & Streams in Java8Victor Rentea
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentationBhavin Gandhi
 
Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerIgor Crvenov
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript TutorialBui Kiet
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous JavascriptGarrett Welson
 
Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best PracticesTheo Jungeblut
 
The lazy programmer's guide to writing thousands of tests
The lazy programmer's guide to writing thousands of testsThe lazy programmer's guide to writing thousands of tests
The lazy programmer's guide to writing thousands of testsScott Wlaschin
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic FunctionsWebStackAcademy
 
The Clean Architecture
The Clean ArchitectureThe Clean Architecture
The Clean ArchitectureDmytro Turskyi
 
Railway Oriented Programming
Railway Oriented ProgrammingRailway Oriented Programming
Railway Oriented ProgrammingScott Wlaschin
 

What's hot (20)

Clean code
Clean codeClean code
Clean code
 
Clean Code Principles
Clean Code PrinciplesClean Code Principles
Clean Code Principles
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean code
Clean codeClean code
Clean code
 
Clean Code
Clean CodeClean Code
Clean Code
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable code
 
The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean code
 
Clean code
Clean codeClean code
Clean code
 
Clean Lambdas & Streams in Java8
Clean Lambdas & Streams in Java8Clean Lambdas & Streams in Java8
Clean Lambdas & Streams in Java8
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentation
 
Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin Fowler
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
 
Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best Practices
 
Clean code
Clean code Clean code
Clean code
 
The lazy programmer's guide to writing thousands of tests
The lazy programmer's guide to writing thousands of testsThe lazy programmer's guide to writing thousands of tests
The lazy programmer's guide to writing thousands of tests
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
 
The Clean Architecture
The Clean ArchitectureThe Clean Architecture
The Clean Architecture
 
Railway Oriented Programming
Railway Oriented ProgrammingRailway Oriented Programming
Railway Oriented Programming
 

Viewers also liked

Information Technology Project Management - part 10
Information Technology Project Management - part 10Information Technology Project Management - part 10
Information Technology Project Management - part 10Rizwan Khurram
 
Reverse eningeering
Reverse eningeeringReverse eningeering
Reverse eningeeringKent Huang
 
Windows internals Essentials
Windows internals EssentialsWindows internals Essentials
Windows internals EssentialsJohn Ombagi
 
Information Technology Project Management - part 07
Information Technology Project Management - part 07Information Technology Project Management - part 07
Information Technology Project Management - part 07Rizwan Khurram
 
Information Technology Project Management - part 12
Information Technology Project Management - part 12Information Technology Project Management - part 12
Information Technology Project Management - part 12Rizwan Khurram
 
Information Technology Project Management - part 09
Information Technology Project Management - part 09Information Technology Project Management - part 09
Information Technology Project Management - part 09Rizwan Khurram
 
Information Technology Project Management - part 08
Information Technology Project Management - part  08Information Technology Project Management - part  08
Information Technology Project Management - part 08Rizwan Khurram
 
Information Technology Project Management - part 04
Information Technology Project Management - part 04Information Technology Project Management - part 04
Information Technology Project Management - part 04Rizwan Khurram
 
Information Technology Project Management - part 05
Information Technology Project Management - part 05Information Technology Project Management - part 05
Information Technology Project Management - part 05Rizwan Khurram
 
Windows Internal - Ch9 memory management
Windows Internal - Ch9 memory managementWindows Internal - Ch9 memory management
Windows Internal - Ch9 memory managementKent Huang
 
Information Technology Project Management - part 01
Information Technology Project Management - part 01Information Technology Project Management - part 01
Information Technology Project Management - part 01Rizwan Khurram
 
Information Technology Project Management - part 11
Information Technology Project Management - part 11Information Technology Project Management - part 11
Information Technology Project Management - part 11Rizwan Khurram
 
Information Technology Project Management - part 02
Information Technology Project Management - part 02Information Technology Project Management - part 02
Information Technology Project Management - part 02Rizwan Khurram
 
Information Technology Project Management
Information Technology Project ManagementInformation Technology Project Management
Information Technology Project ManagementGoutama Bachtiar
 

Viewers also liked (14)

Information Technology Project Management - part 10
Information Technology Project Management - part 10Information Technology Project Management - part 10
Information Technology Project Management - part 10
 
Reverse eningeering
Reverse eningeeringReverse eningeering
Reverse eningeering
 
Windows internals Essentials
Windows internals EssentialsWindows internals Essentials
Windows internals Essentials
 
Information Technology Project Management - part 07
Information Technology Project Management - part 07Information Technology Project Management - part 07
Information Technology Project Management - part 07
 
Information Technology Project Management - part 12
Information Technology Project Management - part 12Information Technology Project Management - part 12
Information Technology Project Management - part 12
 
Information Technology Project Management - part 09
Information Technology Project Management - part 09Information Technology Project Management - part 09
Information Technology Project Management - part 09
 
Information Technology Project Management - part 08
Information Technology Project Management - part  08Information Technology Project Management - part  08
Information Technology Project Management - part 08
 
Information Technology Project Management - part 04
Information Technology Project Management - part 04Information Technology Project Management - part 04
Information Technology Project Management - part 04
 
Information Technology Project Management - part 05
Information Technology Project Management - part 05Information Technology Project Management - part 05
Information Technology Project Management - part 05
 
Windows Internal - Ch9 memory management
Windows Internal - Ch9 memory managementWindows Internal - Ch9 memory management
Windows Internal - Ch9 memory management
 
Information Technology Project Management - part 01
Information Technology Project Management - part 01Information Technology Project Management - part 01
Information Technology Project Management - part 01
 
Information Technology Project Management - part 11
Information Technology Project Management - part 11Information Technology Project Management - part 11
Information Technology Project Management - part 11
 
Information Technology Project Management - part 02
Information Technology Project Management - part 02Information Technology Project Management - part 02
Information Technology Project Management - part 02
 
Information Technology Project Management
Information Technology Project ManagementInformation Technology Project Management
Information Technology Project Management
 

Similar to Clean Code: Chapter 3 Function

Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy codeShriKant Vashishtha
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
 
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfSummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfARORACOCKERY2111
 
NLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by OrdinaNLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by OrdinaMartijn Blankestijn
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003R696
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiRan Mizrahi
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme SwiftMovel
 
"Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin "Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin Vasil Remeniuk
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basicsLovelitJose
 
BITM3730 10-17.pptx
BITM3730 10-17.pptxBITM3730 10-17.pptx
BITM3730 10-17.pptxMattMarino13
 
BITM3730 10-3.pptx
BITM3730 10-3.pptxBITM3730 10-3.pptx
BITM3730 10-3.pptxMattMarino13
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVAMuskanSony
 
Paying off technical debt with PHPSpec
Paying off technical debt with PHPSpecPaying off technical debt with PHPSpec
Paying off technical debt with PHPSpecLewis Wright
 
BITM3730 10-4.pptx
BITM3730 10-4.pptxBITM3730 10-4.pptx
BITM3730 10-4.pptxMattMarino13
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to JavascriptAnjan Banda
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMMario Fusco
 

Similar to Clean Code: Chapter 3 Function (20)

Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfSummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
 
NLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by OrdinaNLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by Ordina
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
 
"Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin "Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basics
 
BITM3730 10-17.pptx
BITM3730 10-17.pptxBITM3730 10-17.pptx
BITM3730 10-17.pptx
 
BITM3730 10-3.pptx
BITM3730 10-3.pptxBITM3730 10-3.pptx
BITM3730 10-3.pptx
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
 
Paying off technical debt with PHPSpec
Paying off technical debt with PHPSpecPaying off technical debt with PHPSpec
Paying off technical debt with PHPSpec
 
BITM3730 10-4.pptx
BITM3730 10-4.pptxBITM3730 10-4.pptx
BITM3730 10-4.pptx
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Structure on a freeform world
Structure on a freeform worldStructure on a freeform world
Structure on a freeform world
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 

Recently uploaded

UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROmotivationalword821
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 

Recently uploaded (20)

UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTRO
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 

Clean Code: Chapter 3 Function

  • 1. Clean Code Chapter 3: Function Kent Huang
  • 2. Outline • Case Study: HtmlUnit.java • Small • Switch • Argument • Error handle • Structured Programming • Conclusion
  • 3. Case Studying Sample Code Listing 3-1 Sample Code Listing 3-2
  • 4. What’s different?? • What is it makes a function like Listing3-2 easy to read and understand? • How can we make a function communicate it intent? • What attribute can we give our functions allow a casual reader to intuit the kind of program they live inside?
  • 5. Small • Rules of functions: – Should be small – Should be smaller than that • < 150 character per line • < 20 lines public static String renderPageWithSetupsAndTeardowns( PageData pageData, boolean isSuite) throws Exception { if (isTestPage(pageData)) includeSetupAndTeardownPages(pageData, isSuite); return pageData.getHtml(); }
  • 6. Do One Thing • Functions should do one thing. They should do it well. They should to it only. • Listing 3-3 do three things 1. Determining whether the page is a test page. 2. If so, including setups and teardowns. 3. Rendering the page in HTML.
  • 7. Is It? • If a function does only those steps that are one level below the stated name of the function, then the function is doing one thing • If you can extract another function from it with a name that is not merely a restatement of its implementation
  • 8. One Level of Abstraction per Function • In Listing3-1 – High level: getHtml(),PathParser.render(pagePath) – Low level: .append(“n”) • Broken windows – Once details are mixed with essential concepts, more and more details tend to accrete within the function
  • 9. Reading Code from Top to Bottom • The Stepdown Rule: – We can read the program, descending one level of abstraction at a time as we read down the list of functions
  • 10. Switch Statements public Money calculatePay(Employee e) throws InvalidEmployeeType { switch (e.type) { case COMMISSIONED: return calculateCommissionedPay(e); case HOURLY: return calculateHourlyPay(e); case SALARIED: return calculateSalariedPay(e); default: throw new InvalidEmployeeType(e.type); } } 1. It’s large, and when new employee type are added, it will grow. 2. Does more than one thing. 3. Violates the Single Responsibility Principle 4. Violates the Open Closed Principle 5. There are an unlimited number of other functions will have same structure.
  • 11. public abstract class Employee { public abstract boolean isPayday(); public abstract Money calculatePay(); public abstract void deliverPay(Money pay); } ----------------- public interface EmployeeFactory { public Employee makeEmployee(EmployeeRecord r) throws InvalidEmployeeType; } ----------------- public class EmployeeFactoryImpl implements EmployeeFactory { public Employee makeEmployee(EmployeeRecord r) throws InvalidEmployeeType { switch (r.type) { case COMMISSIONED: return new CommissionedEmployee(r); case HOURLY: return new HourlyEmployee(r); case SALARIED: return new SalariedEmploye(r); default: throw new InvalidEmployeeType(r.type); } } }
  • 12. Use Descriptive Names • Don’t be afraid to make a name long • A long descriptive name is better than a long descriptive comment • Use the same phrases, nouns, and verbs in the function names – Ex: includeSetupAndTeardownPages, includeSetupPages, includeSuiteSetupPage, includeSetupPage
  • 13. Function Arguments • The ideal number of arguments for a function is zero (niladic). 0 > 1 > 2 > 3 >> 4 • Arguments are even harder from a testing point of view.
  • 14. Common Monadic Forms • If a function is going to transform its input argument, the transformation should appear the return value • StringBuffer transform(StringBuffer in) • Void transform(StringBuffer out) 
  • 15. Flag Arguments • Flag arguments are ugly rander(true)  renderForSuite()  renderForSingleTest() 
  • 16. Dyadic Functions • Function with two arguments is harder to understand than one – writeField(name) v.s writeField(outputStream, name) • Some times, two arguments are appropriate. – Point p = new Point(0,0); • Still have problem – assertEquals(expected, actual)
  • 17. Triads • Don’t use!!! – assertEquals(message, expected, actual)  • Argument Objects – Circle makeCircle(double x, double y, double radius); – Circle makeCircle(Point center, double radius);
  • 18. Verbs and Keywords • Choosing good names for a function can go a long way toward explaining the intent of the function and the order and intent of the arguments. – Write(name) – WriteField(name) – AssertEquals(expected, actual) – AsertExpectedQqualsActual(expected,actual)
  • 19. Have No Side Effects 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; } }
  • 20. Output Arguments • appendFooter(s);??? – public void appendFooter(StringBuffer report) • report.appendFooter();
  • 21. Command Query Separation • if (set("username", "unclebob"))... – public boolean set(String attribute, String value); if (attributeExists("username")) { setAttribute("username", "unclebob"); ... }
  • 22. Prefer Exceptions to Returning Error Codes if (deletePage(page) == E_OK) { if (registry.deleteReference(page.name) == E_OK) { if (configKeys.deleteKey(page.name.makeKey()) == E_OK){ logger.log("page deleted"); } else { logger.log("configKey not deleted"); } } else { logger.log("deleteReference from registry failed"); } } else { logger.log("delete failed"); return E_ERROR; } try { deletePage(page); registry.deleteReference(page.name); configKeys.deleteKey(page.name.makeKey()); } catch (Exception e) { logger.log(e.getMessage()); }
  • 23. • Don’t Repeat Yourself – Duplication may be the root of all evil in software • Structured Programming – Edsger Dijkstra’s rules • One entry, one exist • Never, ever, ant goto – When function is small • Multiple return, break, continue are ok • Goto only makes sense in large functions
  • 24. Conclusion • Every system is built from a domain-specific language – Functions are the verbs of that language – Classes are the nouns • Master programmer do: – Functions are short, well named and nicely organized – Never forget, your real goal is to tell the story of the system

Editor's Notes

  1. Intuit 意會
  2. Blocks and Indenting This implies that the blocks within if statements, else statements, while statements, and so on should be one line long. Probably that line should be a function call. Not only does this keep the enclosing function small, but it also adds documentary value because the function called within the block can have a nicely descriptive name. This also implies that functions should not be large enough to hold nested structures. Therefore, the indent level of a function should not be greater than one or two. This, of course, makes the functions easier to read and understand.
  3. The problem with this statement is that it is hard to know what “one thing” is.
  4. In order to make sure our functions are doing “one thing,” we need to make sure that the statements within our function are all at the same level of abstraction. It is easy to see how Listing 3-1 violates this rule. There are concepts in there that are at a very high level of abstraction, such as getHtml(); others that are at an intermediate level of abstraction, such as: String pagePathName = PathParser.render(pagePath); and still others that are remark- ably low level, such as: .append("\n"). Mixing levels of abstraction within a function is always confusing. Readers may not be able to tell whether a particular expression is an essential concept or a detail. Worse, like broken windows, once details are mixed with essential concepts, more and more details tend to accrete within the function.
  5. It’s hard to make a small switch statement. By their nature, switch statements always do N things we can make sure that each switch statement is buried in a low-level class and is never repeated SRP: A class should have only one reason to change. OCP: Software entities (class, modules, functions, etc.) should be open for extension, but closed for modification. 一個軟體個體應該要夠開放使得它可以被擴充,但是也要夠封閉以避免不必要的修改
  6. It immediately complicates the signature of the method, loudly proclaiming that this function does more than one thing.
  7. Two arguments There are times, of course, where two arguments are appropriate.
  8. Dijkstra’s rules: no break and continue