SlideShare une entreprise Scribd logo
1  sur  83
CODE QUALITY
What is clean code?
How do you define good quality code?
What is Clean Code?
I like my code to be elegant and efficient. Clean code does one thing
well
Bjarne Stroustrup, inventor of C++
Clean code always looks like it was written by someone who cares
Michael Feathers
If you want your code to be easy to write, make it easy to read
Robert C. Martin, Co-author of Agile Manifesto
Why should you care?
1. Personally
Good enough,
is not good enough.
EXCELLENCE.
2. Cost
Cost of fixing bugs
3. Time
Software life-cycle
4. Professionally
Why should you care?
For yourself
Dev time = 60% reading and 40% writing
Easier to fix bugs
Easier to estimate new features
Easier to maintain
Why should you care?
For other co-workers
New member joins
Maintenance
Hand-over
Making the life easier for
everyone involved in the project
CODING IS NOT A SPRINT,.
IT’S A MARATHON..
How to get started.
LONG, HARD.
JOURNEY..
Rule 1. Follow the style guide
Rule 1. Follow the style guide
What is it?
Coding conventions are a set of guidelines for a specific programming
language that recommend programming style, practices, and methods for
each aspect of a program written in that language.
Coding conventions are only applicable to the human maintainers and peer
reviewers of a software project.
Wikipedia
Rule 1. Follow the style guide
1. Read the guide carefully
2. Learn the basics by heart
3. Look up corner cases
4. Apply the rules religiously
Result: your programs will be better
than those written by the majority
of university graduates.
Rule 1. Follow the style guide
Many resources out there.
Examples
1. Java: Google Java style guide
https://google.github.io/styleguide/javaguide.html
2. C#: Microsoft coding conventions
https://docs.microsoft.com/en-us/dotnet/csharp/.../coding-conventions
3. PHP: PSR-2
http://www.php-fig.org/psr/psr-2/
Rule 2: Create descriptive names
Rule 2: Create descriptive names
1. Class and type names should be nouns.
2. Methods names should contain a verb.
3. Function names should describe what the function returns.
4. Use long descriptive names - help you and colleagues understand what
the code does.
5. Give accurate names - Did you mean highestPrice, rather than bestPrice?
6. Give specific names - Should it be getBestPrice, rather than getBest?
Rule 3: Comment and document
Example
This is bad:
protected $d; // elapsed time in days
This is good:
protected $elapsedTimeInDays;
Rule 3: Comment and document
Example
This is good:
class Product {
private $price;
public function increasePrice($dollarsToAddToPrice) {
$this->price += $dollarsToAddToPrice;
}
}
Rule 3: Comment and document
Rule 3: Comment and document
Don’t comment, let code be you comment
1. Code should explain itself
2. If code is readable you don’t need comments
3. Comments do not make up your code & may contain lies
Rule 3: Comment and document
Example
This is bad:
// Check to see if the employee is eligible for full benefits
if ($employee->flags && self::HOURLY_FLAG && $employee->age > 65)
This is good:
if ($employee->isEligibleForFullBenefits())
Rule 3: Comment and document
So when do you write a comment?
1. Explain your intention in comments
For example:
// if we sort the array here the logic becomes
Simpler in calculatePayment() method
Rule 3: Comment and document
So when do you write a comment?
2. Warn of consequences in comments
For example:
// this script will take a very long time to run
Rule 3: Comment and document
So when do you write a comment?
3. Emphasize important points in comments
For example:
// The trim function is very important, in
most cases the username has a trailing space
Rule 4: Don't repeat yourself
Rule 4: Don't repeat yourself
Also known as DRY
1. Never copy-and-paste code in the same project.
2. Abstract the common parts into a routine or class, with appropriate
parameters.
Rule 5: The smaller the better
Rule 5: The smaller the better
Split your Code into Short, Focused Units
1. A function should only do one thing
2. No nested control structure
3. Less arguments are better (3 or less if possible)
For example:
Circle makeCircle(Point center, double radius);
Is better than
Circle makeCircle(double x, double y, double radius);
Rule 5: The smaller the better
Split your Code into Short, Focused Units
3. No side effects - Functions do what the name suggests and nothing else.
4. Avoid output arguments - If returning something is not enough then your
function is probably doing more than one thing.
For example:
email.addSignature();
Is better than
addSignature(email);
Rule 5: The smaller the better
Split your Code into Short, Focused Units
5. Error Handling is one thing - Throwing exceptions is better than returning
different codes dependent on errors.
Rule 6: Don't overdesign
Rule 6: Don't overdesign
1. Keep your design focused on today's needs.
2. Your code can be general to accommodate future evolution, but only if
that doesn't make it more complex.
3. You can't guess what tomorrow will bring.
4. When the code's structure no longer fits the task, refactoring it to a more
appropriate design.
Rule 7: Other code smells and heuristics
Rule 7: Other code smells and heuristics
There are a lot more that you can do to identify and avoid bad code. Here is a
list of some code smells and anti-patterns to avoid.
1. Dead code
2. Large classes
3. God object - an object that knows too much or does too much.
4. Multiple languages in one file
5. Framework core modifications
6. Magic numbers - replace with const or var
Rule 7: Other code smells and heuristics
7. Long if conditions - replace with function
8. Call super’s overwritten methods
9. Circular dependency
10. Circular references
11. Sequential coupling
12. Hard-coding
13. Too much inheritance - composition is better than inheritance
Quality automation.
THE MOST POWERFUL.
TOOL WE HAVE AS.
DEVELOPERS IS.
AUTOMATION..
- Scott Hanselman.
Unit testing
Unit Testing
What is it?
Unit testing is a software testing method by which individual units of source
code, sets of one or more computer program modules together with
associated control data, [...], are tested to determine whether they are fit for
use.
Wikipedia
Unit Testing
The complexity of modern software makes it expensive and difficult to
continually manually test.
Unit tests allow:
1. A more productive approach is to accompany every small part of your
code with tests that verify its correct function.
2. This approach simplifies debugging by allowing you to catch errors early,
close to their source.
3. Unit testing also allows you to refactor the code with confidence.
Unit Testing
Many resources out there.
Examples
1. Java - JUnit:
http://junit.org/junit5/
2. C# - XUnit:
https://xunit.github.io/
3. PHP: PHPUnit:
https://phpunit.de/
Test driven development
Test driven development
1. Add a test - Each new feature begins with writing a test
Writing unit tests before the code is written makes the you focus on the
requirements before writing the code, an important value.
1. Write a test that defines a function or improvements of a function, which
should be very clear and short.
2. Clearly understand the feature's specification and requirements.
3. Create use cases and user stories to cover the requirements and
exception conditions.
4. Write the tests.
Test driven development
2. Run all tests and see if the new test fails
1. This validates that the tests are working correctly.
2. It shows that the new test does not pass without requiring new code
because the required behavior already exists, and it rules out the
possibility that the new test is flawed and will always pass.
3. The new test should fail for the expected reason. This step increases the
developer's confidence in the new test.
Test driven development
3. Write the code
You must not write code that is beyond the functionality that the test checks.
1. Write code that causes the tests to pass.
2. The new code written at this stage is not perfect and may, for example,
pass the test in an inelegant way. That is acceptable because it will be
improved in Step 5.
3. At this point, the only purpose of the written code is to pass the tests.
Test driven development
4. Run tests
1. If all test cases now pass, the programmer can be confident that the new
code meets the test requirements.
2. The new code also does not break or degrade any existing features since
past tests should still pass.
3. If other any tests are now failing, the new code must be adjusted until
they pass.
Test driven development
5. Refactor code
1. The growing code base must be cleaned up regularly.
2. New code can be moved from where it was convenient for passing a test
to where it more logically belongs. Duplication must be removed.
3. Clean the code following the rules discussed in the presentation.
4. Inheritance hierarchies may be rearranged to be more logical and helpful,
and perhaps to benefit from recognized design patterns.
5. By continually re-running the test cases throughout each refactoring
phase, the developer can be confident that process is not altering any
existing functionality.
Test driven development
6. Repeat
1. Starting with another new test, the cycle is then repeated to push forward
the functionality.
2. The size of the steps should always be small, with as few as 1 to 10 edits
between each test run.
3. If new code does not rapidly satisfy a new test, or other tests fail
unexpectedly, the programmer should undo or revert in preference to
excessive debugging.
Test automation tools
Automated code review
They provide automated capability to show health of an application and
highlight coding issues.
Tools such as:
● SonarQube (free):
https://www.sonarqube.org/
● CodeClimate:
https://codeclimate.com/
● Codacy:
https://www.codacy.com/
IDE - Integrated development environment
The craftsman's essential tool
1. Integrate all these tools we talked about directly into your IDE.
Automated code review, build tools for TDD, etc.
2. Get to know all the features.
3. Try to do it all without using the mouse.
APM - Application performance management
What is it?
APM is the monitoring and management of performance and availability of
software applications. APM tries to detect and diagnose complex application
performance problems to maintain an expected level of service.
Tools such as:
● New Relic:
https://newrelic.com/
● Sentry:
https://sentry.io/welcome/
Peer code review
Peer Code Review
Code review is systematic examination (sometimes referred to as peer review)
of computer source code. It is intended to find mistakes overlooked in
software development, improving the overall quality of software. Reviews are
done in various forms such as pair programming, informal walkthroughs, and
formal inspections.[1]
Wikipedia
HUMAN INTELLIGENCE..
Conclusion
How clean should it be?
Less code-smells
The boy scout rule.
"Always check [code] in
cleaner than when you
checked it out."
- Robert C. Martin
Conclusion
Books on art don’t promise
to make you an artist.
“Continuous effort - not
strength or intelligence - is
the key to unlocking our
potential.”
-Winston Churchill
Books
Clean Code - A Handbook of Agile
Software Craftsmanship
by Robert C. Martin
Code Complete 2
by Steve McConnell
Craftman
by Robert C. Martin
Sites
References
- http://www.informit.com/articles/article.aspx?p=2223710
- https://www.butterfly.com.au/blog/website-development/clean-high-quali
ty-code-a-guide-on-how-to-become-a-better-programmer
- https://confluence.sakaiproject.org/display/BOOT/Best+Practices+for+Hig
h+Quality+Code

Contenu connexe

Tendances

Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
bhochhi
 
Tdd in php a brief example
Tdd in php   a brief exampleTdd in php   a brief example
Tdd in php a brief example
Jeremy Kendall
 

Tendances (20)

TDD- Test Driven Development
TDD- Test Driven DevelopmentTDD- Test Driven Development
TDD- Test Driven Development
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Coding standards and guidelines
Coding standards and guidelinesCoding standards and guidelines
Coding standards and guidelines
 
Tdd in php a brief example
Tdd in php   a brief exampleTdd in php   a brief example
Tdd in php a brief example
 
Test Driven Development - Overview and Adoption
Test Driven Development - Overview and AdoptionTest Driven Development - Overview and Adoption
Test Driven Development - Overview and Adoption
 
FluentSelenium Presentation Code Camp09
FluentSelenium Presentation Code Camp09FluentSelenium Presentation Code Camp09
FluentSelenium Presentation Code Camp09
 
Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin Fowler
 
TDD - Test Driven Development
TDD - Test Driven DevelopmentTDD - Test Driven Development
TDD - Test Driven Development
 
Unit testing & TDD concepts with best practice guidelines.
Unit testing & TDD concepts with best practice guidelines.Unit testing & TDD concepts with best practice guidelines.
Unit testing & TDD concepts with best practice guidelines.
 
Best Practices of Software Development
Best Practices of Software DevelopmentBest Practices of Software Development
Best Practices of Software Development
 
Refactoring legacy code driven by tests - ENG
Refactoring legacy code driven by tests - ENGRefactoring legacy code driven by tests - ENG
Refactoring legacy code driven by tests - ENG
 
Introduction to TDD (Test Driven development) - Ahmed Shreef
Introduction to TDD (Test Driven development) - Ahmed ShreefIntroduction to TDD (Test Driven development) - Ahmed Shreef
Introduction to TDD (Test Driven development) - Ahmed Shreef
 
Code review guidelines
Code review guidelinesCode review guidelines
Code review guidelines
 
Getting Unstuck: Working with Legacy Code and Data
Getting Unstuck: Working with Legacy Code and DataGetting Unstuck: Working with Legacy Code and Data
Getting Unstuck: Working with Legacy Code and Data
 
TDD (Test Driven Design)
TDD (Test Driven Design)TDD (Test Driven Design)
TDD (Test Driven Design)
 
Code coverage
Code coverageCode coverage
Code coverage
 
Unit testing legacy code
Unit testing legacy codeUnit testing legacy code
Unit testing legacy code
 
Pair programming and introduction to TDD
Pair programming and introduction to TDDPair programming and introduction to TDD
Pair programming and introduction to TDD
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Presentation slides: "How to get 100% code coverage"
Presentation slides: "How to get 100% code coverage" Presentation slides: "How to get 100% code coverage"
Presentation slides: "How to get 100% code coverage"
 

Similaire à [DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo, Founder & President at Code Engine Studio

Test driven development
Test driven developmentTest driven development
Test driven development
Harry Potter
 
Test driven development
Test driven developmentTest driven development
Test driven development
Luis Goldster
 
Test driven development
Test driven developmentTest driven development
Test driven development
Tony Nguyen
 
Test driven development
Test driven developmentTest driven development
Test driven development
Young Alista
 
Test driven development
Test driven developmentTest driven development
Test driven development
James Wong
 
Test driven development
Test driven developmentTest driven development
Test driven development
Fraboni Ec
 
Code Review
Code ReviewCode Review
Code Review
Ravi Raj
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@
Alex Borsuk
 
TDD — Are you sure you properly test code?
TDD — Are you sure you properly test code?TDD — Are you sure you properly test code?
TDD — Are you sure you properly test code?
Dmitriy Nesteryuk
 
Test-Driven Development Reference Card
Test-Driven Development Reference CardTest-Driven Development Reference Card
Test-Driven Development Reference Card
Seapine Software
 
Agile korea 2013 유석문
Agile korea 2013 유석문Agile korea 2013 유석문
Agile korea 2013 유석문
Sangcheol Hwang
 

Similaire à [DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo, Founder & President at Code Engine Studio (20)

Clean code: understanding Boundaries and Unit Tests
Clean code: understanding Boundaries and Unit TestsClean code: understanding Boundaries and Unit Tests
Clean code: understanding Boundaries and Unit Tests
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Clean Code - Part 2
Clean Code - Part 2Clean Code - Part 2
Clean Code - Part 2
 
YAGNI Principle and Clean Code
YAGNI Principle and Clean CodeYAGNI Principle and Clean Code
YAGNI Principle and Clean Code
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Code Review
Code ReviewCode Review
Code Review
 
Code smells quality of code
Code smells   quality of codeCode smells   quality of code
Code smells quality of code
 
Ddc2011 효과적으로레거시코드다루기
Ddc2011 효과적으로레거시코드다루기Ddc2011 효과적으로레거시코드다루기
Ddc2011 효과적으로레거시코드다루기
 
Code review best practice
Code review best practiceCode review best practice
Code review best practice
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@
 
Software coding and testing
Software coding and testingSoftware coding and testing
Software coding and testing
 
TDD — Are you sure you properly test code?
TDD — Are you sure you properly test code?TDD — Are you sure you properly test code?
TDD — Are you sure you properly test code?
 
Test-Driven Development Reference Card
Test-Driven Development Reference CardTest-Driven Development Reference Card
Test-Driven Development Reference Card
 
Agile korea 2013 유석문
Agile korea 2013 유석문Agile korea 2013 유석문
Agile korea 2013 유석문
 

Plus de DevDay.org

Plus de DevDay.org (20)

[DevDay2019] Lean UX - By Bryant Castro, Bryant Castro at Wizeline
[DevDay2019] Lean UX - By  Bryant Castro,  Bryant Castro at Wizeline[DevDay2019] Lean UX - By  Bryant Castro,  Bryant Castro at Wizeline
[DevDay2019] Lean UX - By Bryant Castro, Bryant Castro at Wizeline
 
[DevDay2019] Why you'll lose without UX Design - By Szilard Toth, CTO at e·pi...
[DevDay2019] Why you'll lose without UX Design - By Szilard Toth, CTO at e·pi...[DevDay2019] Why you'll lose without UX Design - By Szilard Toth, CTO at e·pi...
[DevDay2019] Why you'll lose without UX Design - By Szilard Toth, CTO at e·pi...
 
[DevDay2019] Things i wish I knew when I was a 23-year-old Developer - By Chr...
[DevDay2019] Things i wish I knew when I was a 23-year-old Developer - By Chr...[DevDay2019] Things i wish I knew when I was a 23-year-old Developer - By Chr...
[DevDay2019] Things i wish I knew when I was a 23-year-old Developer - By Chr...
 
[DevDay2019] Designing design teams - Christopher Nguyen, UX Manager at Wizeline
[DevDay2019] Designing design teams - Christopher Nguyen, UX Manager at Wizeline[DevDay2019] Designing design teams - Christopher Nguyen, UX Manager at Wizeline
[DevDay2019] Designing design teams - Christopher Nguyen, UX Manager at Wizeline
 
[DevDay2019] Growth Hacking - How to double the benefits of your startup with...
[DevDay2019] Growth Hacking - How to double the benefits of your startup with...[DevDay2019] Growth Hacking - How to double the benefits of your startup with...
[DevDay2019] Growth Hacking - How to double the benefits of your startup with...
 
[DevDay2019] Collaborate or die: The designers’ guide to working with develop...
[DevDay2019] Collaborate or die: The designers’ guide to working with develop...[DevDay2019] Collaborate or die: The designers’ guide to working with develop...
[DevDay2019] Collaborate or die: The designers’ guide to working with develop...
 
[DevDay2019] How AI is changing the future of Software Testing? - By Vui Nguy...
[DevDay2019] How AI is changing the future of Software Testing? - By Vui Nguy...[DevDay2019] How AI is changing the future of Software Testing? - By Vui Nguy...
[DevDay2019] How AI is changing the future of Software Testing? - By Vui Nguy...
 
[DevDay2019] Hands-on Machine Learning on Google Cloud Platform - By Thanh Le...
[DevDay2019] Hands-on Machine Learning on Google Cloud Platform - By Thanh Le...[DevDay2019] Hands-on Machine Learning on Google Cloud Platform - By Thanh Le...
[DevDay2019] Hands-on Machine Learning on Google Cloud Platform - By Thanh Le...
 
[DevDay2019] Micro Frontends Architecture - By Thang Pham, Senior Software En...
[DevDay2019] Micro Frontends Architecture - By Thang Pham, Senior Software En...[DevDay2019] Micro Frontends Architecture - By Thang Pham, Senior Software En...
[DevDay2019] Micro Frontends Architecture - By Thang Pham, Senior Software En...
 
[DevDay2019] Power of Test Automation and DevOps combination - One click savi...
[DevDay2019] Power of Test Automation and DevOps combination - One click savi...[DevDay2019] Power of Test Automation and DevOps combination - One click savi...
[DevDay2019] Power of Test Automation and DevOps combination - One click savi...
 
[DevDay2019] How do I test AI models? - By Minh Hoang, Senior QA Engineer at KMS
[DevDay2019] How do I test AI models? - By Minh Hoang, Senior QA Engineer at KMS[DevDay2019] How do I test AI models? - By Minh Hoang, Senior QA Engineer at KMS
[DevDay2019] How do I test AI models? - By Minh Hoang, Senior QA Engineer at KMS
 
[DevDay2019] How to quickly become a Senior Engineer - By Tran Anh Minh, CEO ...
[DevDay2019] How to quickly become a Senior Engineer - By Tran Anh Minh, CEO ...[DevDay2019] How to quickly become a Senior Engineer - By Tran Anh Minh, CEO ...
[DevDay2019] How to quickly become a Senior Engineer - By Tran Anh Minh, CEO ...
 
[Devday2019] Dev start-up - By Le Trung, Founder & CEO at Hifiveplus and Edu...
[Devday2019]  Dev start-up - By Le Trung, Founder & CEO at Hifiveplus and Edu...[Devday2019]  Dev start-up - By Le Trung, Founder & CEO at Hifiveplus and Edu...
[Devday2019] Dev start-up - By Le Trung, Founder & CEO at Hifiveplus and Edu...
 
[DevDay2019] Web Development In 2019 - A Practical Guide - By Hoang Nhu Vinh,...
[DevDay2019] Web Development In 2019 - A Practical Guide - By Hoang Nhu Vinh,...[DevDay2019] Web Development In 2019 - A Practical Guide - By Hoang Nhu Vinh,...
[DevDay2019] Web Development In 2019 - A Practical Guide - By Hoang Nhu Vinh,...
 
[DevDay2019] Opportunities and challenges for human resources during the digi...
[DevDay2019] Opportunities and challenges for human resources during the digi...[DevDay2019] Opportunities and challenges for human resources during the digi...
[DevDay2019] Opportunities and challenges for human resources during the digi...
 
[DevDay2019] Python Machine Learning with Jupyter Notebook - By Nguyen Huu Th...
[DevDay2019] Python Machine Learning with Jupyter Notebook - By Nguyen Huu Th...[DevDay2019] Python Machine Learning with Jupyter Notebook - By Nguyen Huu Th...
[DevDay2019] Python Machine Learning with Jupyter Notebook - By Nguyen Huu Th...
 
[DevDay2019] Do you dockerize? Are your containers safe? - By Pham Hong Khanh...
[DevDay2019] Do you dockerize? Are your containers safe? - By Pham Hong Khanh...[DevDay2019] Do you dockerize? Are your containers safe? - By Pham Hong Khanh...
[DevDay2019] Do you dockerize? Are your containers safe? - By Pham Hong Khanh...
 
[DevDay2019] Develop a web application with Kubernetes - By Nguyen Xuan Phong...
[DevDay2019] Develop a web application with Kubernetes - By Nguyen Xuan Phong...[DevDay2019] Develop a web application with Kubernetes - By Nguyen Xuan Phong...
[DevDay2019] Develop a web application with Kubernetes - By Nguyen Xuan Phong...
 
[DevDay2019] Paradigm shift towards effective Scrum - By Tam Doan, Agile Coac...
[DevDay2019] Paradigm shift towards effective Scrum - By Tam Doan, Agile Coac...[DevDay2019] Paradigm shift towards effective Scrum - By Tam Doan, Agile Coac...
[DevDay2019] Paradigm shift towards effective Scrum - By Tam Doan, Agile Coac...
 
[DevDay2019] JAM Stack - By Ngo Thi Ni, Web Developer at Agility IO
[DevDay2019] JAM Stack - By Ngo Thi Ni, Web Developer at Agility IO[DevDay2019] JAM Stack - By Ngo Thi Ni, Web Developer at Agility IO
[DevDay2019] JAM Stack - By Ngo Thi Ni, Web Developer at Agility IO
 

Dernier

Dernier (20)

What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 

[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo, Founder & President at Code Engine Studio

  • 2.
  • 3.
  • 4.
  • 6. How do you define good quality code?
  • 7. What is Clean Code? I like my code to be elegant and efficient. Clean code does one thing well Bjarne Stroustrup, inventor of C++ Clean code always looks like it was written by someone who cares Michael Feathers If you want your code to be easy to write, make it easy to read Robert C. Martin, Co-author of Agile Manifesto
  • 10.
  • 11. Good enough, is not good enough.
  • 18. Why should you care? For yourself Dev time = 60% reading and 40% writing Easier to fix bugs Easier to estimate new features Easier to maintain
  • 19. Why should you care? For other co-workers New member joins Maintenance Hand-over Making the life easier for everyone involved in the project
  • 20. CODING IS NOT A SPRINT,. IT’S A MARATHON..
  • 21. How to get started.
  • 23. Rule 1. Follow the style guide
  • 24. Rule 1. Follow the style guide What is it? Coding conventions are a set of guidelines for a specific programming language that recommend programming style, practices, and methods for each aspect of a program written in that language. Coding conventions are only applicable to the human maintainers and peer reviewers of a software project. Wikipedia
  • 25. Rule 1. Follow the style guide 1. Read the guide carefully 2. Learn the basics by heart 3. Look up corner cases 4. Apply the rules religiously Result: your programs will be better than those written by the majority of university graduates.
  • 26. Rule 1. Follow the style guide Many resources out there. Examples 1. Java: Google Java style guide https://google.github.io/styleguide/javaguide.html 2. C#: Microsoft coding conventions https://docs.microsoft.com/en-us/dotnet/csharp/.../coding-conventions 3. PHP: PSR-2 http://www.php-fig.org/psr/psr-2/
  • 27. Rule 2: Create descriptive names
  • 28. Rule 2: Create descriptive names 1. Class and type names should be nouns. 2. Methods names should contain a verb. 3. Function names should describe what the function returns. 4. Use long descriptive names - help you and colleagues understand what the code does. 5. Give accurate names - Did you mean highestPrice, rather than bestPrice? 6. Give specific names - Should it be getBestPrice, rather than getBest?
  • 29. Rule 3: Comment and document Example This is bad: protected $d; // elapsed time in days This is good: protected $elapsedTimeInDays;
  • 30. Rule 3: Comment and document Example This is good: class Product { private $price; public function increasePrice($dollarsToAddToPrice) { $this->price += $dollarsToAddToPrice; } }
  • 31. Rule 3: Comment and document
  • 32. Rule 3: Comment and document Don’t comment, let code be you comment 1. Code should explain itself 2. If code is readable you don’t need comments 3. Comments do not make up your code & may contain lies
  • 33. Rule 3: Comment and document Example This is bad: // Check to see if the employee is eligible for full benefits if ($employee->flags && self::HOURLY_FLAG && $employee->age > 65) This is good: if ($employee->isEligibleForFullBenefits())
  • 34. Rule 3: Comment and document So when do you write a comment? 1. Explain your intention in comments For example: // if we sort the array here the logic becomes Simpler in calculatePayment() method
  • 35. Rule 3: Comment and document So when do you write a comment? 2. Warn of consequences in comments For example: // this script will take a very long time to run
  • 36. Rule 3: Comment and document So when do you write a comment? 3. Emphasize important points in comments For example: // The trim function is very important, in most cases the username has a trailing space
  • 37. Rule 4: Don't repeat yourself
  • 38. Rule 4: Don't repeat yourself Also known as DRY 1. Never copy-and-paste code in the same project. 2. Abstract the common parts into a routine or class, with appropriate parameters.
  • 39. Rule 5: The smaller the better
  • 40. Rule 5: The smaller the better Split your Code into Short, Focused Units 1. A function should only do one thing 2. No nested control structure 3. Less arguments are better (3 or less if possible) For example: Circle makeCircle(Point center, double radius); Is better than Circle makeCircle(double x, double y, double radius);
  • 41. Rule 5: The smaller the better Split your Code into Short, Focused Units 3. No side effects - Functions do what the name suggests and nothing else. 4. Avoid output arguments - If returning something is not enough then your function is probably doing more than one thing. For example: email.addSignature(); Is better than addSignature(email);
  • 42. Rule 5: The smaller the better Split your Code into Short, Focused Units 5. Error Handling is one thing - Throwing exceptions is better than returning different codes dependent on errors.
  • 43. Rule 6: Don't overdesign
  • 44. Rule 6: Don't overdesign 1. Keep your design focused on today's needs. 2. Your code can be general to accommodate future evolution, but only if that doesn't make it more complex. 3. You can't guess what tomorrow will bring. 4. When the code's structure no longer fits the task, refactoring it to a more appropriate design.
  • 45. Rule 7: Other code smells and heuristics
  • 46. Rule 7: Other code smells and heuristics There are a lot more that you can do to identify and avoid bad code. Here is a list of some code smells and anti-patterns to avoid. 1. Dead code 2. Large classes 3. God object - an object that knows too much or does too much. 4. Multiple languages in one file 5. Framework core modifications 6. Magic numbers - replace with const or var
  • 47. Rule 7: Other code smells and heuristics 7. Long if conditions - replace with function 8. Call super’s overwritten methods 9. Circular dependency 10. Circular references 11. Sequential coupling 12. Hard-coding 13. Too much inheritance - composition is better than inheritance
  • 49. THE MOST POWERFUL. TOOL WE HAVE AS. DEVELOPERS IS. AUTOMATION.. - Scott Hanselman.
  • 51. Unit Testing What is it? Unit testing is a software testing method by which individual units of source code, sets of one or more computer program modules together with associated control data, [...], are tested to determine whether they are fit for use. Wikipedia
  • 52. Unit Testing The complexity of modern software makes it expensive and difficult to continually manually test. Unit tests allow: 1. A more productive approach is to accompany every small part of your code with tests that verify its correct function. 2. This approach simplifies debugging by allowing you to catch errors early, close to their source. 3. Unit testing also allows you to refactor the code with confidence.
  • 53. Unit Testing Many resources out there. Examples 1. Java - JUnit: http://junit.org/junit5/ 2. C# - XUnit: https://xunit.github.io/ 3. PHP: PHPUnit: https://phpunit.de/
  • 55.
  • 56. Test driven development 1. Add a test - Each new feature begins with writing a test Writing unit tests before the code is written makes the you focus on the requirements before writing the code, an important value. 1. Write a test that defines a function or improvements of a function, which should be very clear and short. 2. Clearly understand the feature's specification and requirements. 3. Create use cases and user stories to cover the requirements and exception conditions. 4. Write the tests.
  • 57.
  • 58. Test driven development 2. Run all tests and see if the new test fails 1. This validates that the tests are working correctly. 2. It shows that the new test does not pass without requiring new code because the required behavior already exists, and it rules out the possibility that the new test is flawed and will always pass. 3. The new test should fail for the expected reason. This step increases the developer's confidence in the new test.
  • 59.
  • 60. Test driven development 3. Write the code You must not write code that is beyond the functionality that the test checks. 1. Write code that causes the tests to pass. 2. The new code written at this stage is not perfect and may, for example, pass the test in an inelegant way. That is acceptable because it will be improved in Step 5. 3. At this point, the only purpose of the written code is to pass the tests.
  • 61.
  • 62. Test driven development 4. Run tests 1. If all test cases now pass, the programmer can be confident that the new code meets the test requirements. 2. The new code also does not break or degrade any existing features since past tests should still pass. 3. If other any tests are now failing, the new code must be adjusted until they pass.
  • 63.
  • 64. Test driven development 5. Refactor code 1. The growing code base must be cleaned up regularly. 2. New code can be moved from where it was convenient for passing a test to where it more logically belongs. Duplication must be removed. 3. Clean the code following the rules discussed in the presentation. 4. Inheritance hierarchies may be rearranged to be more logical and helpful, and perhaps to benefit from recognized design patterns. 5. By continually re-running the test cases throughout each refactoring phase, the developer can be confident that process is not altering any existing functionality.
  • 65.
  • 66. Test driven development 6. Repeat 1. Starting with another new test, the cycle is then repeated to push forward the functionality. 2. The size of the steps should always be small, with as few as 1 to 10 edits between each test run. 3. If new code does not rapidly satisfy a new test, or other tests fail unexpectedly, the programmer should undo or revert in preference to excessive debugging.
  • 67.
  • 69. Automated code review They provide automated capability to show health of an application and highlight coding issues. Tools such as: ● SonarQube (free): https://www.sonarqube.org/ ● CodeClimate: https://codeclimate.com/ ● Codacy: https://www.codacy.com/
  • 70.
  • 71. IDE - Integrated development environment The craftsman's essential tool 1. Integrate all these tools we talked about directly into your IDE. Automated code review, build tools for TDD, etc. 2. Get to know all the features. 3. Try to do it all without using the mouse.
  • 72. APM - Application performance management What is it? APM is the monitoring and management of performance and availability of software applications. APM tries to detect and diagnose complex application performance problems to maintain an expected level of service. Tools such as: ● New Relic: https://newrelic.com/ ● Sentry: https://sentry.io/welcome/
  • 73.
  • 75. Peer Code Review Code review is systematic examination (sometimes referred to as peer review) of computer source code. It is intended to find mistakes overlooked in software development, improving the overall quality of software. Reviews are done in various forms such as pair programming, informal walkthroughs, and formal inspections.[1] Wikipedia
  • 78. How clean should it be? Less code-smells
  • 79. The boy scout rule. "Always check [code] in cleaner than when you checked it out." - Robert C. Martin
  • 80. Conclusion Books on art don’t promise to make you an artist. “Continuous effort - not strength or intelligence - is the key to unlocking our potential.” -Winston Churchill
  • 81. Books Clean Code - A Handbook of Agile Software Craftsmanship by Robert C. Martin Code Complete 2 by Steve McConnell Craftman by Robert C. Martin
  • 82.