SlideShare a Scribd company logo
Clean Code C# - Summary by Esperansa Ohad
1. Common Code Smells:
Poor Names:
• Names that are mysterious: SqlDataReader dr1; // What does dr1 mean?
int od;
void Button1_Click();
class Page1 {}
// The problem is that I need to search on another place to
understand the meaning of Button_Click() method & Page1
class.
• Possible names: SqlDataReader dataReader // or just - reader;
overdueDays
checkAvailability_Click()
ViewCustomerPage {}
Meaningless Names:
• void BeginCheckFunctionality_StoreClientSideCheckboxIDsArray();
// What does this method do? I need to see implementation to understand.
// Generally, when my function is more than 10 lines of code, it does more than one
thing.
Names with Encodings:
• Hungarian notation: int iMaxRequests; // No need to use the “i” because by hovering the
// mouse on the variable in Visual Studio, we can
// get the data type.
var m_objCollection = new StringCollection(); // What does
// objCollection mean? I need to go and see
// what is stored in that collection.
// This collection is actual a string collection
// and not objects collection.
// I can’t tell what inside that string collection.
Ambiguous Names:
• bool MultiSelect() {} // Is this method tells me that multiple items are selected or to select
// multiple items? I have again to look at the implementation.
Noisy Names:
• Customer theCustomer; // Fix to customer;
• List<Customer> listOfApprovedCustomers; // Fix to approvedCustomers;
Fix Code Smells:
On this topic will see how to use the “Resharper” tool to fix code smells.
• Change method names using Rename-Refactoring dialog box of resharper (Ctrl+R+R / F2).
• Change parameter names using same keys.
• Change local names using same keys – Resharper will suggest us optional names.
Names – Summary:
• Not too short, not too long.
• Meaningful.
• Reveal intention.
• Chosen from problem domain.
2. Inconsistent Naming Conventions:
Examples:
• Customer GetCustomer(int _id);
• Customer saveCustomer(Customer Customer);
• private int customerId;
In .NET Framework we have two naming conventions:
PascalCase – Class names, properties names, method names.
camelCase – Class members (variables: _id) names, method parameters names, local variables names.
We can use the Resharper Rename-Refactoring dialog to change the names as we should.
3. Poor Method Signatures:
Orange GetCustomer(int airplane); // Not an airplane object → it’s integer.
// This method returns an Orange instead of a Customer.
void Parse (int command); // Parse meaning to get a string and converting that to a different
// object.
➔ int Parse (string command);
• Typically, not always, Boolean flags in method are code smells, because this mean that the
method do two different things.
Ctrl+W on Visual Studio will extend the selection.
Ctrl+Shift+R on Visual Studio will give us the Refactor This item.
Shift+F12 on Visual Studio to find usages.
Ctrl+Shift+R on parameter name to perform safe delete.
Summary:
• Check the return type.
• Check the method name.
• Check the parameters.
4. Long Parameters List
This is kind of a code smell.
• CheckNotifications(null, 1, true, false, DateTime.Now);
// What each parameter represents? We need to check the implementation to know.
// On each call we need to pass a lot of arguments. Hard to understand and to use.
How to handle long parameters list?
• Identify the parameters that repeat themselves on some methods and encapsulate them inside
another class. Pass an instance of that class instead of the previous identified parameters.
• We can use the “Extract Class From Parameters” of the Resharper-Refactoring (hover the
method name and click Ctrl+Shift+R).
Summary:
• Less than 3 parameters.
5. Output Parameters:
• We shall avoid this.
• The problem is that in order to use a method with output parameter, I need to declare and
initialize the variables, and then pass it to the method.
• Use resharper refactoring to help → hover the output parameter → Ctrl+Shift+R → Transform
Out Parameters → Resharper will suggest a returned value instead (Tuple).
• Tuples are also a code smell – because item1 & item2 are not revealing the intention.
• To get rid of the Tuple we need to create a class with variables item1 & item2.
• Now to replace the usage of the Tuple on the method above with the class that we’ve created:
we put the cursor on the method name, and press Ctrl+Shift+R → Change the signature /
Ctrl+F6.
• Afterwards we can Refactor-Rename the names of item1 & item2 on the new class, and
manually change returned values if necessary.
• If we have an argument that is a magic value – we can use Resharper’s Ctrl+Shift+R → Introduce
Variable to assign it into a variable. Instead we can use the named parameters of C# in order to
be more intention revealing.
6. Variable Declarations on the Top:
• In old days it was common to declare variables on top of the methods.
• Now days we should declare the variables where we need them.
• The reason – to keep the context reasonable.
• If an initialization to a variable is grayed out it’s mean that the initialization is unnecessary.
• Resharper’s Ctrl+Shif+R → Inline the variable → Will not work because of the initialization.
• Alt+Enter to display the menu of the yellow bulb → remove redundant initializer.
• If the declaration is green underlined so we click Alt+Enter again and select join declaration and
assignment.
• If we have an initialization that must to stay, we need to move the declaration close to the
usage manually.
Variables - Summary:
• Declare them close to their usage.
7. Magic Numbers:
• Avoid magic numbers.
• Mark the magic number → Resharper-Refactoring by Ctrl+Shift+R and select one of the
following options:
o Introduce Field
o Introduce Parameter
o Introduce Variables
• When we use proper name – we don’t need to use comments. The code is readable.
• We can introduce constant instead – when we need to use the value in some places along the
code: Ctrl+Shift+R → Introduce Field → Give a proper name and select “Introduce constant”.
• We can convert multiple constants to an enumeration by: Mark all constants declarations →
Ctrl+Shift+R → Extract Class → On Extract class field we give the name of the class
(remember that for naming enumerable in .NET we use a singular form) → Keep to make
the fields public so they can be accessible outside the class → Resharper will put the
declaration on another file → manually convert class to enum.
• Maybe we need to change afterwards the signature of the method (for example if we compare
now the new enum with an int parameter): safe way is to use change-signature-refactoring →
we put the cursor on the method name → Ctrl+F6 or Ctrl+Shift+R and select Change signature.
Avoid Magic Numbers – Summary:
• Use constants or enums.
8. Nested Conditionals:
If…if…else….
• Code smell.
• Programs are hard to read, hard to change, hard to understand and hard to test.
• The more nested conditions we have, the more execution pass that we have.
• if… else… → if a ? 1 : 2;
Ternary Operator Abuse:
c = a ? b : d ? e : f;
• Such expression unmaintainable.
• Do not apply more than one in expression.
Simplify true/false:
if (a)
b = true;
else
b = true;
➔ b = a;
Combine:
if (a)
{
if (b)
{
Statement
}
}
➔ Combine:
if (a && b)
{
statement
}
➔ Early Exit – we can use the Guard statements:
if (!a)
return;
if (!b)
return;
statement
➔ Early Exit + Combine:
if (!a || !b)
return;
statement
Everything in moderation!
if (a && (b || c) && !d || e && (f && !g || h)
STINKS!!!
• Can’t read or understand an expression like that.
• Recommended to ask someone else for their opinion about our code.
• Rule – write clean code for others, not for ourselves!!!
In Visual Studio we need to do the hard work – there are no shortcuts for refactoring the nested if.
9. Switch Case statements:
• If possible – convert switch statements to more polymorphic classes.
• One parent class and sub-classes which replace the cases on the switch statements.
• The more an object is used in our method → the more the method is needed to be placed in this
object.
• Encapsulation principle say: we want to have data and methods where operations works on the
data on the same class.
• Ctrl+shift+R (hammer) on the method name → move instance method.
• Alt+Enter (yellow/red bulb) on unrecognized variable to declare it somewhere (locally/globally).
• Recommended to use TDD = Test Driven Development in order to refactor our project.
• To push down functionality from parent to its sons, we need to put the mouse cursor on the
method name → Ctrl+Shift+Alt + up/down → Push Members Down.
Switch Statements – Summary
• Replace them with polymorphic dispatch.
• Use Push Member Down refactoring.
10. Duplicated Code:
• DRY – Don’t Repeat Yourself.
• A change is needed to be made in several places.
11. Comments:
• Comments are code smells in most cases.
• The code should be readable enough without comments.
• Don’t write comments. Re-write your code!
• Don’t explain “whats” (the obvious).
• Explain “whys” and “hows”.
12. Long Methods:
• Long method is one that is more than 10 lines of code.
Problems with Long Methods:
• Hard to understand.
• Hard to change.
• Hard to re-use.
• We want methods that specialize in one thing.
Cohesion Principle:
• Things that are related, should be together.
• Things that are not related, should not be together.
Single Responsibility Principle:
• A class / method should do only one thing and do it very well.
Methods Best Practices:
• Should be short (less than 10 lines).
• Should do only one thing.
Order in class:
• Fields & Properties.
• Public methods.
• Protected methods.
• Private methods.

More Related Content

What's hot

Python unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabusPython unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabus
DhivyaSubramaniyam
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 4 c++
Chap 4 c++Chap 4 c++
Chap 6 c++
Chap 6 c++Chap 6 c++
Ch3 Formatted Input/Output
Ch3 Formatted Input/OutputCh3 Formatted Input/Output
Ch3 Formatted Input/Output
SzeChingChen
 
Chap 4 c++
Chap 4 c++Chap 4 c++
Chap 5 c++
Chap 5 c++Chap 5 c++
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5th
Connex
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
Rasan Samarasinghe
 
Coding Best Practices
Coding Best PracticesCoding Best Practices
Coding Best Practices
mh_azad
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
sanya6900
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
Rasan Samarasinghe
 
Cpprm
CpprmCpprm
Cpprm
Shawne Lee
 
C tutorial
C tutorialC tutorial
C tutorial
Anurag Sukhija
 
C++ theory
C++ theoryC++ theory
C++ theory
Shyam Khant
 
Getting started in c++
Getting started in c++Getting started in c++
Getting started in c++
Neeru Mittal
 
Cheat Sheet java
Cheat Sheet javaCheat Sheet java
Cheat Sheet java
arkslideshareacc
 

What's hot (17)

Python unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabusPython unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabus
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Chap 4 c++
Chap 4 c++Chap 4 c++
Chap 4 c++
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Ch3 Formatted Input/Output
Ch3 Formatted Input/OutputCh3 Formatted Input/Output
Ch3 Formatted Input/Output
 
Chap 4 c++
Chap 4 c++Chap 4 c++
Chap 4 c++
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5th
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
 
Coding Best Practices
Coding Best PracticesCoding Best Practices
Coding Best Practices
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
 
Cpprm
CpprmCpprm
Cpprm
 
C tutorial
C tutorialC tutorial
C tutorial
 
C++ theory
C++ theoryC++ theory
C++ theory
 
Getting started in c++
Getting started in c++Getting started in c++
Getting started in c++
 
Cheat Sheet java
Cheat Sheet javaCheat Sheet java
Cheat Sheet java
 

Similar to Learn the Art of Writing Clean Code

Prog1-L2.pptx
Prog1-L2.pptxProg1-L2.pptx
Prog1-L2.pptx
valerie5142000
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
Aiman Hud
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
Connex
 
C –FAQ:
C –FAQ:C –FAQ:
C_BASICS FOR C PROGRAMMER WITH SRIVATHS P
C_BASICS FOR C PROGRAMMER WITH  SRIVATHS PC_BASICS FOR C PROGRAMMER WITH  SRIVATHS P
C_BASICS FOR C PROGRAMMER WITH SRIVATHS P
amankr1234am
 
Basic c# cheat sheet
Basic c# cheat sheetBasic c# cheat sheet
Basic c# cheat sheet
Ahmed Elshal
 
Legacy is Good
Legacy is GoodLegacy is Good
Legacy is Good
Uberto Barbini
 
Lập trình C
Lập trình CLập trình C
Lập trình C
Viet NguyenHoang
 
java basics - keywords, statements data types and arrays
java basics - keywords, statements data types and arraysjava basics - keywords, statements data types and arrays
java basics - keywords, statements data types and arrays
mellosuji
 
C++ Homework Help
C++ Homework HelpC++ Homework Help
C++ Homework Help
C++ Homework Help
 
Introduction to c first week slides
Introduction to c first week slidesIntroduction to c first week slides
Introduction to c first week slides
luqman bawany
 
C++.pptx
C++.pptxC++.pptx
C++.pptx
Sabi995708
 
Get Fast C++ Homework Help
Get Fast C++ Homework HelpGet Fast C++ Homework Help
Get Fast C++ Homework Help
C++ Homework Help
 
C_plus_plus
C_plus_plusC_plus_plus
C_plus_plus
Ralph Weber
 
programming week 2.ppt
programming week 2.pptprogramming week 2.ppt
programming week 2.ppt
FatimaZafar68
 
C Language Part 1
C Language Part 1C Language Part 1
C Language Part 1
Thapar Institute
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
VAIBHAVKADAGANCHI
 
Lecture 2 variables
Lecture 2 variablesLecture 2 variables
Lecture 2 variables
Tony Apreku
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
WondimuBantihun1
 
Clean code and code smells
Clean code and code smellsClean code and code smells
Clean code and code smells
Md. Aftab Uddin Kajal
 

Similar to Learn the Art of Writing Clean Code (20)

Prog1-L2.pptx
Prog1-L2.pptxProg1-L2.pptx
Prog1-L2.pptx
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
 
C –FAQ:
C –FAQ:C –FAQ:
C –FAQ:
 
C_BASICS FOR C PROGRAMMER WITH SRIVATHS P
C_BASICS FOR C PROGRAMMER WITH  SRIVATHS PC_BASICS FOR C PROGRAMMER WITH  SRIVATHS P
C_BASICS FOR C PROGRAMMER WITH SRIVATHS P
 
Basic c# cheat sheet
Basic c# cheat sheetBasic c# cheat sheet
Basic c# cheat sheet
 
Legacy is Good
Legacy is GoodLegacy is Good
Legacy is Good
 
Lập trình C
Lập trình CLập trình C
Lập trình C
 
java basics - keywords, statements data types and arrays
java basics - keywords, statements data types and arraysjava basics - keywords, statements data types and arrays
java basics - keywords, statements data types and arrays
 
C++ Homework Help
C++ Homework HelpC++ Homework Help
C++ Homework Help
 
Introduction to c first week slides
Introduction to c first week slidesIntroduction to c first week slides
Introduction to c first week slides
 
C++.pptx
C++.pptxC++.pptx
C++.pptx
 
Get Fast C++ Homework Help
Get Fast C++ Homework HelpGet Fast C++ Homework Help
Get Fast C++ Homework Help
 
C_plus_plus
C_plus_plusC_plus_plus
C_plus_plus
 
programming week 2.ppt
programming week 2.pptprogramming week 2.ppt
programming week 2.ppt
 
C Language Part 1
C Language Part 1C Language Part 1
C Language Part 1
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
Lecture 2 variables
Lecture 2 variablesLecture 2 variables
Lecture 2 variables
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
 
Clean code and code smells
Clean code and code smellsClean code and code smells
Clean code and code smells
 

Recently uploaded

Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
TaghreedAltamimi
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
gapen1
 
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
kalichargn70th171
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
Hornet Dynamics
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
rodomar2
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
VALiNTRY360
 
Liberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptxLiberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptx
Massimo Artizzu
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
sjcobrien
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
Peter Muessig
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
Marcin Chrost
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
mz5nrf0n
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
XfilesPro
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
Quickdice ERP
 
Preparing Non - Technical Founders for Engaging a Tech Agency
Preparing Non - Technical Founders for Engaging  a  Tech AgencyPreparing Non - Technical Founders for Engaging  a  Tech Agency
Preparing Non - Technical Founders for Engaging a Tech Agency
ISH Technologies
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
Peter Muessig
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
dakas1
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
dakas1
 

Recently uploaded (20)

Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
 
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
 
Liberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptxLiberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptx
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
 
Preparing Non - Technical Founders for Engaging a Tech Agency
Preparing Non - Technical Founders for Engaging  a  Tech AgencyPreparing Non - Technical Founders for Engaging  a  Tech Agency
Preparing Non - Technical Founders for Engaging a Tech Agency
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
 

Learn the Art of Writing Clean Code

  • 1. Clean Code C# - Summary by Esperansa Ohad 1. Common Code Smells: Poor Names: • Names that are mysterious: SqlDataReader dr1; // What does dr1 mean? int od; void Button1_Click(); class Page1 {} // The problem is that I need to search on another place to understand the meaning of Button_Click() method & Page1 class. • Possible names: SqlDataReader dataReader // or just - reader; overdueDays checkAvailability_Click() ViewCustomerPage {} Meaningless Names: • void BeginCheckFunctionality_StoreClientSideCheckboxIDsArray(); // What does this method do? I need to see implementation to understand. // Generally, when my function is more than 10 lines of code, it does more than one thing. Names with Encodings: • Hungarian notation: int iMaxRequests; // No need to use the “i” because by hovering the // mouse on the variable in Visual Studio, we can // get the data type. var m_objCollection = new StringCollection(); // What does // objCollection mean? I need to go and see // what is stored in that collection. // This collection is actual a string collection // and not objects collection. // I can’t tell what inside that string collection. Ambiguous Names: • bool MultiSelect() {} // Is this method tells me that multiple items are selected or to select // multiple items? I have again to look at the implementation. Noisy Names: • Customer theCustomer; // Fix to customer; • List<Customer> listOfApprovedCustomers; // Fix to approvedCustomers;
  • 2. Fix Code Smells: On this topic will see how to use the “Resharper” tool to fix code smells. • Change method names using Rename-Refactoring dialog box of resharper (Ctrl+R+R / F2). • Change parameter names using same keys. • Change local names using same keys – Resharper will suggest us optional names. Names – Summary: • Not too short, not too long. • Meaningful. • Reveal intention. • Chosen from problem domain. 2. Inconsistent Naming Conventions: Examples: • Customer GetCustomer(int _id); • Customer saveCustomer(Customer Customer); • private int customerId; In .NET Framework we have two naming conventions: PascalCase – Class names, properties names, method names. camelCase – Class members (variables: _id) names, method parameters names, local variables names. We can use the Resharper Rename-Refactoring dialog to change the names as we should. 3. Poor Method Signatures: Orange GetCustomer(int airplane); // Not an airplane object → it’s integer. // This method returns an Orange instead of a Customer. void Parse (int command); // Parse meaning to get a string and converting that to a different // object. ➔ int Parse (string command); • Typically, not always, Boolean flags in method are code smells, because this mean that the method do two different things. Ctrl+W on Visual Studio will extend the selection. Ctrl+Shift+R on Visual Studio will give us the Refactor This item. Shift+F12 on Visual Studio to find usages. Ctrl+Shift+R on parameter name to perform safe delete.
  • 3. Summary: • Check the return type. • Check the method name. • Check the parameters. 4. Long Parameters List This is kind of a code smell. • CheckNotifications(null, 1, true, false, DateTime.Now); // What each parameter represents? We need to check the implementation to know. // On each call we need to pass a lot of arguments. Hard to understand and to use. How to handle long parameters list? • Identify the parameters that repeat themselves on some methods and encapsulate them inside another class. Pass an instance of that class instead of the previous identified parameters. • We can use the “Extract Class From Parameters” of the Resharper-Refactoring (hover the method name and click Ctrl+Shift+R). Summary: • Less than 3 parameters. 5. Output Parameters: • We shall avoid this. • The problem is that in order to use a method with output parameter, I need to declare and initialize the variables, and then pass it to the method. • Use resharper refactoring to help → hover the output parameter → Ctrl+Shift+R → Transform Out Parameters → Resharper will suggest a returned value instead (Tuple). • Tuples are also a code smell – because item1 & item2 are not revealing the intention. • To get rid of the Tuple we need to create a class with variables item1 & item2. • Now to replace the usage of the Tuple on the method above with the class that we’ve created: we put the cursor on the method name, and press Ctrl+Shift+R → Change the signature / Ctrl+F6. • Afterwards we can Refactor-Rename the names of item1 & item2 on the new class, and manually change returned values if necessary. • If we have an argument that is a magic value – we can use Resharper’s Ctrl+Shift+R → Introduce Variable to assign it into a variable. Instead we can use the named parameters of C# in order to be more intention revealing.
  • 4. 6. Variable Declarations on the Top: • In old days it was common to declare variables on top of the methods. • Now days we should declare the variables where we need them. • The reason – to keep the context reasonable. • If an initialization to a variable is grayed out it’s mean that the initialization is unnecessary. • Resharper’s Ctrl+Shif+R → Inline the variable → Will not work because of the initialization. • Alt+Enter to display the menu of the yellow bulb → remove redundant initializer. • If the declaration is green underlined so we click Alt+Enter again and select join declaration and assignment. • If we have an initialization that must to stay, we need to move the declaration close to the usage manually. Variables - Summary: • Declare them close to their usage. 7. Magic Numbers: • Avoid magic numbers. • Mark the magic number → Resharper-Refactoring by Ctrl+Shift+R and select one of the following options: o Introduce Field o Introduce Parameter o Introduce Variables • When we use proper name – we don’t need to use comments. The code is readable. • We can introduce constant instead – when we need to use the value in some places along the code: Ctrl+Shift+R → Introduce Field → Give a proper name and select “Introduce constant”. • We can convert multiple constants to an enumeration by: Mark all constants declarations → Ctrl+Shift+R → Extract Class → On Extract class field we give the name of the class (remember that for naming enumerable in .NET we use a singular form) → Keep to make the fields public so they can be accessible outside the class → Resharper will put the declaration on another file → manually convert class to enum. • Maybe we need to change afterwards the signature of the method (for example if we compare now the new enum with an int parameter): safe way is to use change-signature-refactoring → we put the cursor on the method name → Ctrl+F6 or Ctrl+Shift+R and select Change signature. Avoid Magic Numbers – Summary: • Use constants or enums. 8. Nested Conditionals: If…if…else…. • Code smell. • Programs are hard to read, hard to change, hard to understand and hard to test. • The more nested conditions we have, the more execution pass that we have. • if… else… → if a ? 1 : 2;
  • 5. Ternary Operator Abuse: c = a ? b : d ? e : f; • Such expression unmaintainable. • Do not apply more than one in expression. Simplify true/false: if (a) b = true; else b = true; ➔ b = a; Combine: if (a) { if (b) { Statement } } ➔ Combine: if (a && b) { statement } ➔ Early Exit – we can use the Guard statements: if (!a) return; if (!b) return; statement
  • 6. ➔ Early Exit + Combine: if (!a || !b) return; statement Everything in moderation! if (a && (b || c) && !d || e && (f && !g || h) STINKS!!! • Can’t read or understand an expression like that. • Recommended to ask someone else for their opinion about our code. • Rule – write clean code for others, not for ourselves!!! In Visual Studio we need to do the hard work – there are no shortcuts for refactoring the nested if. 9. Switch Case statements: • If possible – convert switch statements to more polymorphic classes. • One parent class and sub-classes which replace the cases on the switch statements. • The more an object is used in our method → the more the method is needed to be placed in this object. • Encapsulation principle say: we want to have data and methods where operations works on the data on the same class. • Ctrl+shift+R (hammer) on the method name → move instance method. • Alt+Enter (yellow/red bulb) on unrecognized variable to declare it somewhere (locally/globally). • Recommended to use TDD = Test Driven Development in order to refactor our project. • To push down functionality from parent to its sons, we need to put the mouse cursor on the method name → Ctrl+Shift+Alt + up/down → Push Members Down. Switch Statements – Summary • Replace them with polymorphic dispatch. • Use Push Member Down refactoring. 10. Duplicated Code: • DRY – Don’t Repeat Yourself. • A change is needed to be made in several places. 11. Comments: • Comments are code smells in most cases. • The code should be readable enough without comments. • Don’t write comments. Re-write your code! • Don’t explain “whats” (the obvious). • Explain “whys” and “hows”.
  • 7. 12. Long Methods: • Long method is one that is more than 10 lines of code. Problems with Long Methods: • Hard to understand. • Hard to change. • Hard to re-use. • We want methods that specialize in one thing. Cohesion Principle: • Things that are related, should be together. • Things that are not related, should not be together. Single Responsibility Principle: • A class / method should do only one thing and do it very well. Methods Best Practices: • Should be short (less than 10 lines). • Should do only one thing. Order in class: • Fields & Properties. • Public methods. • Protected methods. • Private methods.