Clean Code
‫نویسنده‬:Robert C. Martin
‫سال‬:2008
‫مطالب‬ ‫سرفصل‬
1.Meaningful Names
2.Functions
3.Comments
4.Formatting
5.Error Handling
6.Boundires
7.Unit Tests
8.Class
‫ی‬‫نامگذار‬ ‫قواعد‬:
1.‫معلوم‬ ‫های‬ ‫نام‬‫از‬‫استفاده‬
4.‫بیان‬‫قابل‬
3.‫گردد‬ ‫تمایز‬‫باعث‬ ‫گه‬ ‫ای‬ ‫کلمه‬ ‫از‬‫استفاده‬
5.‫باشد‬ ‫جستجو‬ ‫قابل‬‫سریع‬
8.‫مفهوم‬ ‫یک‬‫ای‬‫ر‬‫ب‬ ‫کلمه‬ ‫یک‬
6.‫پیشوند‬
7.‫ذهنی‬ ‫کلمات‬
2.‫غلط‬ ‫اطالعات‬ ‫از‬‫اجتناب‬
Soultion Domain Names 9.
‫توابع‬ ‫قاعده‬:
1.Small
2.Do One Thing
3.One Level Of Abstractions
4.Switch Case Statement
5.Use Descriptive Names
6.Function Arguments
8.Have No Side Effect
9.Don’t Repeat Yourself
10. Prefer Exceptions to Returning Error Codes
7. Argument Objects
Comments
‫بودند‬ ‫تر‬ ‫نزدیک‬ ‫انسان‬ ‫بان‬‫ز‬ ‫به‬ ‫ی‬ ‫نویس‬ ‫برنامه‬ ‫های‬ ‫بان‬‫ز‬ ‫اگر‬
‫نبود‬‫کامنت‬ ‫نوشتن‬ ‫به‬ ‫ی‬‫نیاز‬.
‫کند‬ ‫تغییر‬ ‫باید‬ ‫هم‬ ‫کامنت‬ ‫های‬ ‫نوشته‬ ،‫کند‬ ‫تغییر‬ ‫برنامه‬ ‫کد‬ ‫اگر‬.
‫نکته‬:
‫ل‬‫او‬ ‫قاعده‬:
1Comments Do Not Make Up for Bad Code
"Ooh,
I would better comment that!"
=> No! You would be better clean it!
‫ل‬‫او‬ ‫قاعده‬:
1Comments Do Not Make Up for Bad Code
‫ل‬‫او‬ ‫قاعده‬:
1Comments Do Not Make Up for Bad Code
‫دوم‬ ‫قاعده‬:
2Explain Yourself in Code
This:
// Check to see if the employee is eligible for full benefits
if (employee.flags && HOURLY_FLAG) && (employee.age >65)) {
vs:
// Check to see if the employee is eligible for full benefits
if (employee.isEligibleForFullBenefits()){
=> Create a function that says the same thing as the comment you want to write
‫سوم‬ ‫قاعده‬:
3Don’t Use a Comment When You Can Use a Function or a Variable
Consider the following stretch of code:
// does the module from the global list <mod> depend on the
// subsystem we are part of?
if (smodule.getDependSubsystems().contains(subSysMod.getSubSystem()))
This could be rephrased without the comment as
ArrayList moduleDependees = smodule.getDependSubsystems();
String ourSubSystem = subSysMod.getSubSystem();
if (moduleDependees.contains(ourSubSystem))
Good Comments
Legal Comments
Informative Comments
(Put all the terms and conditions into an external document.)
(Useful information about the implementation and taken decisions.)
TODO Comments
Bad Comments
Redundant Comments Less information than the code.
It is not easier to read than the code.
It is less precise
Noise Comments Auto generated or very obvious comments that are
nothing but noise.
Formatting
The Purpose of Formatting
Code formatting is about communication.
Readability of code.
The style and discipline survives to changes.
‫نمونه‬:
Type Formatting
Vertical Formatting
Horizontal Formatting
The Newspaper Metaphor
We would like a source file to be like a newspaper article:
At the top you expect a headline
The first paragraph gives you a synopsis of the whole story.
As you continue down-ward the details increase
In a source file: high-level concepts and algorithms => lowest level functions and details
1‫ل‬‫او‬‫قاعده‬:
Vertical Density ‫دوم‬ ‫قاعده‬:
2
Vertical Distance
Conceptual Affinity
Group of functions performing a similar operation. They share common naming scheme and perform
variations of the same task. We want them to be close together.
Variables should be declared as close to their usage as possible Our functions are short -> local
variables at the top. Control variables for loops => declare them within the loop statement
Instance variables
Should be declared at the top of the class. Everybody should know where to go to see the declarations.
Dependent functions
If one functions calls another they should be vertically close, an the caller should be above the calle, if it is
possible.
‫سوم‬ ‫قاعده‬:
3
Team Rules
Every programmer has his own favorite formatting rules,
but if he works in a team, them the team rules
‫نمونه‬:
Error Handling
Use Exceptions Rather Than Return Codes
It is better to throw an exception.
The calling code is cleaner.
Its logic is not obscured by error handling.
Try to separate the algorithm from error handling:
public void sendShutDown() {
try {
tryToShutDown();
} catch (DeviceShutDownError e) {
logger.log(e);
}
private void tryToShutDown() throws DeviceShutDownError {
// ..
}
‫ل‬‫او‬‫قاعده‬:
1
Don’t Return Null
If you return null then you have to manage "the null" with if's...".
When we return null we are creating work for ourselves.
You can return an empty list and clean up the code:
2‫دوم‬ ‫قاعده‬:
List<Employee> employees = getEmployees();
if (employees != null) {
for(Employee e : employees) {
totalPay += e.getPay();
}
}
vs
List<Employee> employees = getEmployees();
for(Employee e : employees) {
totalPay += e.getPay();
}
//...
public List<Employee> getEmployees() {
if( .. there are no employees .. )
return Collections.emptyList();
}
Don’t Pass Null
Returning null from methods is bad, but passing null into methods is worse
3‫سوم‬ ‫قاعده‬:
‫مطالب‬‫خالصه‬:
Formatting
Error HandlingComments
Comments Do Not Make Up for Bad Code
Explain Yourself in Code
Don’t Use a Comment When You Can Use a Function or a Variable
The Newspaper Metaphor
Use Exceptions Rather Than Return Codes
Don’t Pass Null
Don’t Return Null
Vertical Density
Vertical Distance
Vertical Formatting
Horizontal Formatting

Clean code ch03

  • 2.
  • 3.
  • 4.
    ‫ی‬‫نامگذار‬ ‫قواعد‬: 1.‫معلوم‬ ‫های‬‫نام‬‫از‬‫استفاده‬ 4.‫بیان‬‫قابل‬ 3.‫گردد‬ ‫تمایز‬‫باعث‬ ‫گه‬ ‫ای‬ ‫کلمه‬ ‫از‬‫استفاده‬ 5.‫باشد‬ ‫جستجو‬ ‫قابل‬‫سریع‬ 8.‫مفهوم‬ ‫یک‬‫ای‬‫ر‬‫ب‬ ‫کلمه‬ ‫یک‬ 6.‫پیشوند‬ 7.‫ذهنی‬ ‫کلمات‬ 2.‫غلط‬ ‫اطالعات‬ ‫از‬‫اجتناب‬ Soultion Domain Names 9.
  • 5.
    ‫توابع‬ ‫قاعده‬: 1.Small 2.Do OneThing 3.One Level Of Abstractions 4.Switch Case Statement 5.Use Descriptive Names 6.Function Arguments 8.Have No Side Effect 9.Don’t Repeat Yourself 10. Prefer Exceptions to Returning Error Codes 7. Argument Objects
  • 6.
  • 7.
    ‫بودند‬ ‫تر‬ ‫نزدیک‬‫انسان‬ ‫بان‬‫ز‬ ‫به‬ ‫ی‬ ‫نویس‬ ‫برنامه‬ ‫های‬ ‫بان‬‫ز‬ ‫اگر‬ ‫نبود‬‫کامنت‬ ‫نوشتن‬ ‫به‬ ‫ی‬‫نیاز‬. ‫کند‬ ‫تغییر‬ ‫باید‬ ‫هم‬ ‫کامنت‬ ‫های‬ ‫نوشته‬ ،‫کند‬ ‫تغییر‬ ‫برنامه‬ ‫کد‬ ‫اگر‬. ‫نکته‬:
  • 8.
    ‫ل‬‫او‬ ‫قاعده‬: 1Comments DoNot Make Up for Bad Code "Ooh, I would better comment that!" => No! You would be better clean it!
  • 9.
  • 10.
  • 11.
    ‫دوم‬ ‫قاعده‬: 2Explain Yourselfin Code This: // Check to see if the employee is eligible for full benefits if (employee.flags && HOURLY_FLAG) && (employee.age >65)) { vs: // Check to see if the employee is eligible for full benefits if (employee.isEligibleForFullBenefits()){ => Create a function that says the same thing as the comment you want to write
  • 12.
    ‫سوم‬ ‫قاعده‬: 3Don’t Usea Comment When You Can Use a Function or a Variable Consider the following stretch of code: // does the module from the global list <mod> depend on the // subsystem we are part of? if (smodule.getDependSubsystems().contains(subSysMod.getSubSystem())) This could be rephrased without the comment as ArrayList moduleDependees = smodule.getDependSubsystems(); String ourSubSystem = subSysMod.getSubSystem(); if (moduleDependees.contains(ourSubSystem))
  • 13.
    Good Comments Legal Comments InformativeComments (Put all the terms and conditions into an external document.) (Useful information about the implementation and taken decisions.) TODO Comments
  • 14.
    Bad Comments Redundant CommentsLess information than the code. It is not easier to read than the code. It is less precise Noise Comments Auto generated or very obvious comments that are nothing but noise.
  • 15.
  • 16.
    The Purpose ofFormatting Code formatting is about communication. Readability of code. The style and discipline survives to changes.
  • 17.
  • 18.
  • 19.
    The Newspaper Metaphor Wewould like a source file to be like a newspaper article: At the top you expect a headline The first paragraph gives you a synopsis of the whole story. As you continue down-ward the details increase In a source file: high-level concepts and algorithms => lowest level functions and details 1‫ل‬‫او‬‫قاعده‬:
  • 20.
    Vertical Density ‫دوم‬‫قاعده‬: 2
  • 21.
    Vertical Distance Conceptual Affinity Groupof functions performing a similar operation. They share common naming scheme and perform variations of the same task. We want them to be close together. Variables should be declared as close to their usage as possible Our functions are short -> local variables at the top. Control variables for loops => declare them within the loop statement Instance variables Should be declared at the top of the class. Everybody should know where to go to see the declarations. Dependent functions If one functions calls another they should be vertically close, an the caller should be above the calle, if it is possible. ‫سوم‬ ‫قاعده‬: 3
  • 22.
    Team Rules Every programmerhas his own favorite formatting rules, but if he works in a team, them the team rules
  • 23.
  • 24.
  • 25.
    Use Exceptions RatherThan Return Codes It is better to throw an exception. The calling code is cleaner. Its logic is not obscured by error handling. Try to separate the algorithm from error handling: public void sendShutDown() { try { tryToShutDown(); } catch (DeviceShutDownError e) { logger.log(e); } private void tryToShutDown() throws DeviceShutDownError { // .. } ‫ل‬‫او‬‫قاعده‬: 1
  • 26.
    Don’t Return Null Ifyou return null then you have to manage "the null" with if's...". When we return null we are creating work for ourselves. You can return an empty list and clean up the code: 2‫دوم‬ ‫قاعده‬: List<Employee> employees = getEmployees(); if (employees != null) { for(Employee e : employees) { totalPay += e.getPay(); } } vs List<Employee> employees = getEmployees(); for(Employee e : employees) { totalPay += e.getPay(); } //... public List<Employee> getEmployees() { if( .. there are no employees .. ) return Collections.emptyList(); }
  • 27.
    Don’t Pass Null Returningnull from methods is bad, but passing null into methods is worse 3‫سوم‬ ‫قاعده‬:
  • 28.
    ‫مطالب‬‫خالصه‬: Formatting Error HandlingComments Comments DoNot Make Up for Bad Code Explain Yourself in Code Don’t Use a Comment When You Can Use a Function or a Variable The Newspaper Metaphor Use Exceptions Rather Than Return Codes Don’t Pass Null Don’t Return Null Vertical Density Vertical Distance Vertical Formatting Horizontal Formatting