How to code CLEAN?
Shreyas Patil
shreyaspatil.dev
@imShreyasPatil
Let’s write a code which humans can understand!👨💻
You’re here for two reasons -
First you’re a programmer and second you want to be a
better programmer👨💻.
What is Clean Code? 🤔
What is Clean Code? 🤔
- Simple
- Readable
- Considerate (For future consumers)
- Maintainable
- Tested
- Practiced
- Refactored
- S.O.L.I.D.
What is S.O.L.I.D.? 🤔
- Single Responsibility Principle:
Class should have only and only one reason to change.
- Open/Closed Principle:
You should be able to extend a classes behavior, without modifying it.
- Liskov Substitution Principle:
Derived classes must be substitutable for their base classes.
What is S.O.L.I.D.? 🤔
- Interface Segregation Principle:
Make fine grained interfaces that are client specific.
- Dependency Inversion Principle:
Depend on abstractions, not on concretions.
“I like my code to be elegant and efficient. The logic should be
straightforward and make it hard for bugs to hide, the dependencies
minimal to ease maintenance, error handling complete according to an
articulated strategy, and performance close to optimal so as not to tempt
people to make the code messy with unprincipled optimizations. Clean
code does one thing well.”
~ Bjarne Stroustrup
Why Clean code?
Let’s understand WHY to code clean?
Why Clean Code?🤔
“Any fool can write code that
a computer can understand.
Good programmer write code
that humans can understand”
~ Martin Fowler
You after code review :(
When you’re working in the organization/team then...
Let’s see how to Code Clean? 😀
Now we’ll see how to code clean
Let’s Start
Meaningful
Names
Meaningful Names
- Names: Variables, Functions, Class, Package, Source file, Directory
name, etc.
- Let’ see simple rules for creating good names...
Use Intention Revealing Names
When we started programming, our first program be like...
Use Intention Revealing Names
What it should be?
Use Intention Revealing Names
Use Intention Revealing Names
Choosing name which reveals intent can make it much easier to understand and change the code.
What is purpose of this code?
Use Intention Revealing
Names
Use Intention Revealing
Names
Avoid Disinformation
- Avoid words whose meaning varies from intended meaning.
- For e.g. Don’t use name ‘accountList’ unless it’s actually a list.
Use Pronounceable Names
- Humans are good at words.
- See this one...
You Other
Use Pronounceable Names
You now !
Use Searchable Names
- Single-letter names or numeric constants are not easy to locate in body of text sometimes.
- One might easily search MAX_NUMBER but the number 7 could be more troublesome.
- Let’s code again.
Use Searchable Names
- Now it’s simple to read than previous one.
Class names
- Classes or objects should have noun or noun phrase names like Customer, WikiPage,
Account, AddressParser, etc.
- Avoid words like Manager, Processor, Data, Info, etc.
- A class name should not be a verb.
Method names
- Methods should have verb phrases like postPayment, deletePage, save, edit, etc.
- Accessor, mutator, predicates should be named with prefixes get, set & is as javabean
standard.
Don’t Pun
- Avoid using same name for two purposes.
- For e.g. Let’s say you have two add() methods in single class. One is
doing addition and another is adding element in list.
- Try to avoid such confusion.
Don’t be Cute
- Don’t be cute or don’t use offensive words in method names.
- whack(), kill(), eatMyShorts() VS deleteAllItems(), abort()
Add Meaningful Context
- Imagine you’ve variable name firstName, lastName, street, houseNumber, city, state,
zipcode.
- ‘State’ is being used alone.
- You can add prefixes like addrFirstName, addrStreet, addState and so on...
That’s all about names!
Functions
Let’s give good names to functions and give correct
meaning for their work.
Small
Blocks and intending
Blocks and intending
Do one thing
- Function should do one thing.
- They should do it well.
- They should do it only.
Use descriptive name
- A long descriptive name is better than short mysterious name.
- Don’t afraid to make a name long.
- Don’t afraid to spend time choosing a name.
Can’t say what exactly doing Long name but easy to understand.
Function Arguments
- Functions should have small number of arguments.
- No arguments is best, followed by one, two and three.
- More than three is questionable and should be avoided with prejudice.
Confusing Perfect!
Common Monadic forms
- There are two reasons to pass single arguments to function:
1. You maybe asking question about argument. For e.g. isVowel(Char ch).
2. You maybe operating that argument, transforming it into something else
and returning it. For e.g. openFile(String filename).
Flag Arguments
- Flag arguments are ugly.
- Passing a boolean into function is terrible practice.
- It does one thing if flag it true and other thing if it’s false.
Dyadic Arguments
- Function with two arguments.
- Complex to understand than monadic functions.
- For example:
- Point(int x, int y),
- copy(String destination, String source).
Triads
- Function with three arguments.
- Harder to understand than dyads.
- For example:
- Point3D(int x, int y, int z),
- assertEquals(String message, Object expected, Object actual).
Verbs and keywords
- Explain the intent of function.
- For e.g. write(name) is confusing. Whatever this “name” thing is, it is being “written”. Better
name would be writeField(name) which tells that name thing is a “field”.
- More examples - createTicket(ticket), updatePhone(phone), updateXYZ(something), etc.
Have No Side Effects
- Your function promises to do one thing but it also does other hidden things.
- Sometimes it does unexpected things.
- Spot side effect in below snippet.
Prefer Exceptions to returning error
codes
Deeply nested structure :( Separate error processing and simplified
code :)
Don’t Repeat Yourself (DRY)
- Duplication in logic should be eliminated via abstraction.
- For e.g. Copy-paste programming or poor understanding of how to apply abstraction.
- It decreases quality of code.
That’s all about functions!
Comments
Let’s write GOOD comments!
Comments
If that’s all you can
say then that’s a BAD
sign!
:(
Source: Pluralsight Blog
- You won’t need comments if you code clean and properly
Comments do not makeup for bad
code
- Clear and expressive code with few comments is far superior to cluttered and complex code.
Explain yourself in code
Informative comments
- It’s sometime useful to provide basic information with a comment. For e.g. consider this
comment which explains the return value of abstract method.
Explanation of Intent
- Sometimes it provides intent behind decision.
Explanation of Intent
- Once upon a time, I wrote this code
Explanation of Intent
- I got comment in the review
Explanation of Intent
- Then added a comment. Looks good, isn’t it?
Clarification
- Sometimes it useful to translate the meaning of some argument or return value
Warning of consequences
- Sometimes it’s useful to warn other programmers about consequences
Noise Comments
Avoid noisy comments…. Like below
That’s all about
Comments
Error Handling
Do handle errors with care :)
Error Handling
Define the normal flow
- Separation of business logic and error handling.
Don’t return or pass `null`
That’s some little about
Error Handling
Classes
Let’s design good classes...
Classes should be small
- First rule: Classes should be small.
- Second rule: They should be smaller than that.
Single Responsibility Principle
- Module should have one and only one reason to change.
Cohesion
- Class should have small number of instance variables.
- Break large functions into smaller functions.
Cohesion
In the below image, we can see that in low cohesion only one class is responsible to execute lots
of job which are not in common which reduces the chance of re-usability and maintenance. But in
high cohesion there is a separate class for all the jobs to execute a specific job, which result better
usability and maintenance.
Source: GeeksForGeeks
Coupling
- Tight coupling is not good at the test-ability.
- Modules should be loosely coupled.
Source: GeeksForGeeks
That’s some little about
Classes
Emergence
Run All Tests
- Run all tests and all tests should pass.
Refactoring
- Keep code and classes clean.
- Increase cohesion and decrease coupling, separate concerns, modularize system concerns,
shrink function and classes, choose better names and so on.
No Duplication
That’s some little about
Emergence
Code Smell
Less code smells, better code
Code smell
Code smell
- It’s a characteristic in source code of a program that indicates a deeper problem.
- Examples:
- Long method or parameter list
- Large class
- Temporary field
- Dead code
- Bad comments
- Lazy class
- Feature envy - Accessing other’s data than its own
- So on...
Code smell
- See this for more details about code smell.
Once you’re a clean coder, you be like 😀
Code Reviewer
You
What is peace other than this? 😀
That’s all
BUT
That’s not enough about
Clean Code.
Reference 📚
- “Clean Code” - Book by Robert C. Martin
- Google Style Guides
- Design Patterns & Refactoring
Here’s everything you need
ⓘ Start presenting to display the audience questions on this slide.
Audience Q&A Session
ⓘ Start presenting to display the poll results on this slide.
What you liked in this session?
See you in next session...
Thanks for being
Amazing audience
😎
Thank You!
Shreyas Patil
shreyaspatil.dev
@imShreyasPatil

Clean code - DSC DYPCOE

  • 1.
    How to codeCLEAN? Shreyas Patil shreyaspatil.dev @imShreyasPatil Let’s write a code which humans can understand!👨💻
  • 2.
    You’re here fortwo reasons - First you’re a programmer and second you want to be a better programmer👨💻.
  • 4.
    What is CleanCode? 🤔
  • 5.
    What is CleanCode? 🤔 - Simple - Readable - Considerate (For future consumers) - Maintainable - Tested - Practiced - Refactored - S.O.L.I.D.
  • 6.
    What is S.O.L.I.D.?🤔 - Single Responsibility Principle: Class should have only and only one reason to change. - Open/Closed Principle: You should be able to extend a classes behavior, without modifying it. - Liskov Substitution Principle: Derived classes must be substitutable for their base classes.
  • 7.
    What is S.O.L.I.D.?🤔 - Interface Segregation Principle: Make fine grained interfaces that are client specific. - Dependency Inversion Principle: Depend on abstractions, not on concretions.
  • 8.
    “I like mycode to be elegant and efficient. The logic should be straightforward and make it hard for bugs to hide, the dependencies minimal to ease maintenance, error handling complete according to an articulated strategy, and performance close to optimal so as not to tempt people to make the code messy with unprincipled optimizations. Clean code does one thing well.” ~ Bjarne Stroustrup
  • 9.
    Why Clean code? Let’sunderstand WHY to code clean?
  • 10.
    Why Clean Code?🤔 “Anyfool can write code that a computer can understand. Good programmer write code that humans can understand” ~ Martin Fowler
  • 13.
    You after codereview :( When you’re working in the organization/team then...
  • 14.
    Let’s see howto Code Clean? 😀 Now we’ll see how to code clean Let’s Start
  • 15.
  • 18.
    Meaningful Names - Names:Variables, Functions, Class, Package, Source file, Directory name, etc. - Let’ see simple rules for creating good names...
  • 19.
    Use Intention RevealingNames When we started programming, our first program be like...
  • 20.
    Use Intention RevealingNames What it should be?
  • 21.
  • 22.
    Use Intention RevealingNames Choosing name which reveals intent can make it much easier to understand and change the code. What is purpose of this code?
  • 23.
  • 24.
  • 25.
    Avoid Disinformation - Avoidwords whose meaning varies from intended meaning. - For e.g. Don’t use name ‘accountList’ unless it’s actually a list.
  • 26.
    Use Pronounceable Names -Humans are good at words. - See this one... You Other
  • 27.
  • 28.
    Use Searchable Names -Single-letter names or numeric constants are not easy to locate in body of text sometimes. - One might easily search MAX_NUMBER but the number 7 could be more troublesome. - Let’s code again.
  • 29.
    Use Searchable Names -Now it’s simple to read than previous one.
  • 30.
    Class names - Classesor objects should have noun or noun phrase names like Customer, WikiPage, Account, AddressParser, etc. - Avoid words like Manager, Processor, Data, Info, etc. - A class name should not be a verb.
  • 31.
    Method names - Methodsshould have verb phrases like postPayment, deletePage, save, edit, etc. - Accessor, mutator, predicates should be named with prefixes get, set & is as javabean standard.
  • 32.
    Don’t Pun - Avoidusing same name for two purposes. - For e.g. Let’s say you have two add() methods in single class. One is doing addition and another is adding element in list. - Try to avoid such confusion.
  • 33.
    Don’t be Cute -Don’t be cute or don’t use offensive words in method names. - whack(), kill(), eatMyShorts() VS deleteAllItems(), abort()
  • 34.
    Add Meaningful Context -Imagine you’ve variable name firstName, lastName, street, houseNumber, city, state, zipcode. - ‘State’ is being used alone. - You can add prefixes like addrFirstName, addrStreet, addState and so on...
  • 35.
  • 36.
    Functions Let’s give goodnames to functions and give correct meaning for their work.
  • 37.
  • 38.
  • 39.
  • 40.
    Do one thing -Function should do one thing. - They should do it well. - They should do it only.
  • 41.
    Use descriptive name -A long descriptive name is better than short mysterious name. - Don’t afraid to make a name long. - Don’t afraid to spend time choosing a name. Can’t say what exactly doing Long name but easy to understand.
  • 42.
    Function Arguments - Functionsshould have small number of arguments. - No arguments is best, followed by one, two and three. - More than three is questionable and should be avoided with prejudice. Confusing Perfect!
  • 43.
    Common Monadic forms -There are two reasons to pass single arguments to function: 1. You maybe asking question about argument. For e.g. isVowel(Char ch). 2. You maybe operating that argument, transforming it into something else and returning it. For e.g. openFile(String filename).
  • 44.
    Flag Arguments - Flagarguments are ugly. - Passing a boolean into function is terrible practice. - It does one thing if flag it true and other thing if it’s false.
  • 45.
    Dyadic Arguments - Functionwith two arguments. - Complex to understand than monadic functions. - For example: - Point(int x, int y), - copy(String destination, String source).
  • 46.
    Triads - Function withthree arguments. - Harder to understand than dyads. - For example: - Point3D(int x, int y, int z), - assertEquals(String message, Object expected, Object actual).
  • 47.
    Verbs and keywords -Explain the intent of function. - For e.g. write(name) is confusing. Whatever this “name” thing is, it is being “written”. Better name would be writeField(name) which tells that name thing is a “field”. - More examples - createTicket(ticket), updatePhone(phone), updateXYZ(something), etc.
  • 48.
    Have No SideEffects - Your function promises to do one thing but it also does other hidden things. - Sometimes it does unexpected things. - Spot side effect in below snippet.
  • 49.
    Prefer Exceptions toreturning error codes Deeply nested structure :( Separate error processing and simplified code :)
  • 50.
    Don’t Repeat Yourself(DRY) - Duplication in logic should be eliminated via abstraction. - For e.g. Copy-paste programming or poor understanding of how to apply abstraction. - It decreases quality of code.
  • 51.
  • 52.
  • 53.
    Comments If that’s allyou can say then that’s a BAD sign! :( Source: Pluralsight Blog - You won’t need comments if you code clean and properly
  • 54.
    Comments do notmakeup for bad code - Clear and expressive code with few comments is far superior to cluttered and complex code.
  • 55.
  • 56.
    Informative comments - It’ssometime useful to provide basic information with a comment. For e.g. consider this comment which explains the return value of abstract method.
  • 57.
    Explanation of Intent -Sometimes it provides intent behind decision.
  • 58.
    Explanation of Intent -Once upon a time, I wrote this code
  • 59.
    Explanation of Intent -I got comment in the review
  • 60.
    Explanation of Intent -Then added a comment. Looks good, isn’t it?
  • 61.
    Clarification - Sometimes ituseful to translate the meaning of some argument or return value
  • 62.
    Warning of consequences -Sometimes it’s useful to warn other programmers about consequences
  • 63.
    Noise Comments Avoid noisycomments…. Like below
  • 64.
  • 65.
    Error Handling Do handleerrors with care :)
  • 67.
  • 68.
    Define the normalflow - Separation of business logic and error handling.
  • 69.
    Don’t return orpass `null`
  • 70.
    That’s some littleabout Error Handling
  • 71.
  • 72.
    Classes should besmall - First rule: Classes should be small. - Second rule: They should be smaller than that.
  • 73.
    Single Responsibility Principle -Module should have one and only one reason to change.
  • 74.
    Cohesion - Class shouldhave small number of instance variables. - Break large functions into smaller functions.
  • 75.
    Cohesion In the belowimage, we can see that in low cohesion only one class is responsible to execute lots of job which are not in common which reduces the chance of re-usability and maintenance. But in high cohesion there is a separate class for all the jobs to execute a specific job, which result better usability and maintenance. Source: GeeksForGeeks
  • 76.
    Coupling - Tight couplingis not good at the test-ability. - Modules should be loosely coupled. Source: GeeksForGeeks
  • 77.
    That’s some littleabout Classes
  • 78.
  • 79.
    Run All Tests -Run all tests and all tests should pass.
  • 80.
    Refactoring - Keep codeand classes clean. - Increase cohesion and decrease coupling, separate concerns, modularize system concerns, shrink function and classes, choose better names and so on.
  • 81.
  • 82.
    That’s some littleabout Emergence
  • 83.
    Code Smell Less codesmells, better code
  • 84.
  • 85.
    Code smell - It’sa characteristic in source code of a program that indicates a deeper problem. - Examples: - Long method or parameter list - Large class - Temporary field - Dead code - Bad comments - Lazy class - Feature envy - Accessing other’s data than its own - So on...
  • 86.
    Code smell - Seethis for more details about code smell.
  • 87.
    Once you’re aclean coder, you be like 😀 Code Reviewer You
  • 88.
    What is peaceother than this? 😀
  • 89.
    That’s all BUT That’s notenough about Clean Code.
  • 90.
    Reference 📚 - “CleanCode” - Book by Robert C. Martin - Google Style Guides - Design Patterns & Refactoring Here’s everything you need
  • 91.
    ⓘ Start presentingto display the audience questions on this slide. Audience Q&A Session
  • 92.
    ⓘ Start presentingto display the poll results on this slide. What you liked in this session?
  • 93.
    See you innext session...
  • 94.
  • 95.

Editor's Notes

  • #6 Clean code is simple. Perhaps not simple in algorithmic or system-level complexity, but certainly simple in implementation. Overly clever tricks, hacks, and sleights of programmatic hand are only fun for the author and diminish the code’s long-term value. The same goes for long-winded code that takes forever to get to the point. Clean code is readable. If the naming conventions, spacing, structure, and flow used in a program are not designed with the reader in mind, then that reader will almost certainly fail to understand the original author’s intent. Conventions about how to write readable code may seem dogmatic or lacking in expressiveness, but they help to make code communal rather than arcane. Clean code is considerate. Code that does not do its best to inform future readers is code that does not respect their time. Clean code should be written with the assumption that future consumers are intelligent, thoughtful professionals (like you), and it should go out of its way to help them. Clean code is tested. No one writes perfect, bug-free code on the first try. Even if it were possible to do so, there is no guarantee that perfect code won’t break later. Writing clean code means writing tested code. That way, future users can be confident they’re interacting with something that works. Moreover, when making changes, they will have a ready-made test suite to confirm that nothing broke. Clean code is practiced. Writing clean code requires good muscle memory, just like playing an instrument, kicking a ball, or frying an egg. The best way to learn to write clean code — and, more importantly, retain the skill — is to do it all the time. When you’re at home working on a personal project, do it with clean code — even when no one else will ever see it. Clean code is relentlessly refactored. Clean code should be in a constant state of refactoring. With a good test suite to back up your code, you can refactor it as much as you like and never worry about breakage. Clean code is SOLID. Good code is as much about good design as it is about cleanliness. Following the SOLID principles is one way to ensure that your code is flexible, maintainable, and long-lasting.
  • #92 📣 This is Slido interaction slide, please don't delete it. ✅ Click on 'Present with Slido' and the questions from your audience will appear when you get to this slide.
  • #93 📣 This is Slido interaction slide, please don't delete it. ✅ Click on 'Present with Slido' and the poll will launch automatically when you get to this slide.