0% found this document useful (0 votes)
2 views

Clean Code

The document discusses principles and practices for writing clean code, emphasizing readability, meaningful naming, and simplicity. It highlights the importance of well-structured code that is easy to understand, maintain, and extend, while also providing guidelines on naming conventions and code organization. Key concepts include the Single Responsibility Principle, avoiding duplication, and adhering to established design guidelines.

Uploaded by

sohaso7499
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Clean Code

The document discusses principles and practices for writing clean code, emphasizing readability, meaningful naming, and simplicity. It highlights the importance of well-structured code that is easy to understand, maintain, and extend, while also providing guidelines on naming conventions and code organization. Key concepts include the Single Responsibility Principle, avoiding duplication, and adhering to established design guidelines.

Uploaded by

sohaso7499
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

Ahmed Mamdouh Mohamed 1

ITI – Assiut branch


• Clean Code, Robert C. Martin
• https://www.slideshare.net/nakov/writing-high-quality-code-in-c

• https://www.slideshare.net/dhelper/writing-clean-code-in-c-and-net

• https://www.slideshare.net/theojungeblut/2013-106-clean-code-part-i-design-patterns

• https://www.slideshare.net/BlackRabbitCoder/automating-coding-standards

• https://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-code

• http://stackoverflow.com/questions/2834439/what-are-some-alternatives-to-resharper
2
3
• Easy to read & understand
• Impossible to hide bugs
• Easy to extend
• Easy to change
• Well documented (self documenting code)
• Well formatted

4
A developer spend 60% – 80% of his time
understanding code.

So, make sure your code is readable

5
6
I like my code to be elegant and
efficient. Clean code does one
thing well.
Straightforward logic
Bjarne Stroustrup Hard for bugs to hide
Error Handling

7
Clean code is simple and direct.
Clean code reads like well-
written prose.
Readability
Grady Booch Crisp abstraction

8
Clean code can be read
Clean Code should be literate
Meaningful names
Dave Thomas Unit & Acceptance Tests
One way rather than many
ways for doing one thing
9
Clean code always looks like it
was written by someone who cares

Michael Feathers

10
You know you are working on clean
code when each routine you read
turns out to be pretty much what
you expected
Code makes it look like
Ward Cunningham the language was made for
the problem

11
Simple

Abstraction
12
The Dumb The Smart
Does everything Wrong Does everything Right

13
Variables

Source Files Functions

Names

Namespaces Parameters

Classes

14
Use Intention-Revealing Names

Take care with your names and change them when you find better ones

It should tell you why it exists, what it does, and how it is used

If a name requires a comment, then the name does not reveal its intent

Choosing good names takes time but saves more than it takes

15
Use Intention-Revealing Names

16
Use Intention-Revealing Names
•What this function Exactly does?!!

What kinds of things are in theList?

What is the significance of the value 4?

How would I use the list being returned?

Method call even better than Boolean expression

17
Avoid Disinformation

Don’t use of lower-case L or uppercase O as


variable names

18
Make Meaningful Distinctions
Number-series naming

Noise Words

Distinguish names in such a way that the reader knows what the differences offer

19
Use Pronounceable Names
If you can’t pronounce it,
you can’t discuss it

This matters because


programming is a social activity

20
Avoid Encoding
Member Prefix

The more we read the code, the less we see the prefixes.

21
Avoid Encoding

Name should not change when type changed!

22
Always use English

23
Class Names

Data Info

A class name should not be a


verb

Customer Account Address

24
Method Names
Methods should have verb or
verb phrase names

PostPayment() DeletePage() Save()

25
Don’t be Cute

HolyHandGrenade() whack() eatMyShorts()

Say what you mean. Mean what


you say.

DeleteItems() Kill() Abort()

26
Pick One Word per Concept
Can you spot the
difference?!!

Fetch() Get() Retrieve()

Controller Driver Manager

A consistent lexicon is a great gift to the programmers who must use your code.

27
Add Meaningful Context

City, Street, ZipCode, HouseNumber

Better…
addrCity, addrStreet, addrZipCode, addrHouseNumber

class Address

28
Naming (Verbs & Keywords)

Good

Better

Good
Better

29
Small

Should be small

Should be smaller than that

< 150 characters per line

< 20 lines

30
Do one thing

Do it well

Do it ONLY

31
Arguments
The ideal number of arguments
 Zero (Niladic) for a function is zero
 One (Monadic)

 Two (Dyadic)
Easier to understand
 Three (Triadic)

 More… (Polyadic) Easier to Test

Output arguments are


harder to understand

The more arguments are, the harder to understand functions


32
Monadic functions
Output argument

33
Flag arguments

34
Dyadic functions

Reasonable

Problematic

35
Triadic functions

36
Output arguments

37
Structured Programming

One entry, One exit. Only one return statement in a function, no


break or continue statements in a loop, and never, ever, any goto
statements.

If functions are small, then the occasional multiple return, break, or


continue statement does no harm and can sometimes even be more
expressive than the single-entry, single-exit rule.

38
Conditional statements & Loops

Always use { } block after if / for..

Never put the block after if / for.. On the same line

39
Have No side effects

Side Effect

40
Have No side effects

Side Effect

41
Returning result

• Returned value has self documenting name


• Simplified debugging

42
Using variables

Variables should have single purpose

Don’t use variables with hidden purpose

Use enum instead

43
Using Expressions

Never use complex expressions in the code

44
“Don’t comment bad code,
rewrite it”
45
Explain yourself in Code

46
Informative comments

47
Explanation of Intent

48
TODO comments

49
Amplification

50
Mumbling

51
Redundant Comments

52
Commented-Out Code

53
Noise Comments

54
Dependency magnet

Exceptions or Error codes?

55
Exceptions or Error codes?

Open/Closed
principle

56
Extract try/catch blocks

Error handling is ONE thing


If the keyword try exists in a function, it
should be the very first word in the
function and that there should be
nothing after the catch/finally blocks

57
Naming a class

The name of a class should describe what responsibilities it fulfills

Naming is the first way of helping determine class size

The more ambiguous the class name, the more likely it has too
many responsibilities

Class names including words like Processor or Manager often hint


at unfortunate aggregation of responsibilities

We should be able to write a brief description of the class in


about 25 words, without using the words “if,” “and,” “or,” “but.”
58
Should be Small

With functions we measured size by counting physical


lines. With classes we use a different measure. We
count responsibilities.

59
Class organization

Class should begin with:


• List of variables
 Public static constants
 Private static variables
 Public instance properties
 Private instance variables
• List of functions
 Public functions
 Private functions
 Events handlers

60
Single Responsibility Principle

Class should have only one reason to change

61
Abstraction
Concrete

Abstract

62
Encapsulation

Minimize visibility of class members

Anything which is not part of class interface should be private

Never declare fields public (except constants). Use methods / Properties.

63
Inheritance

Don’t hide methods in a subclass

Move common interfaces & behavior as high as possible in inheritance tree

Be suspicious of base classes of which there is only one derived class

Be suspicious of classes that override a function and do nothing inside

Avoid using a base class’s protected fields in a derived class (provide


protected methods / properties)

64
The law of Demeter

Method f of a class C should only call the methods


of these:
• C
• An object created by f
• An object passed as an argument to f
• An object held in an instance variable of C
• Talk to friends, Not to strangers

65
Don’t Repeat Yourself (No Duplication)

66
Don’t Repeat Yourself (No Duplication)

67
Don’t Repeat Yourself (No Duplication)

68
Principles of Object Oriented Design

Single Responsibility Principle

Open / Closed Principle

Liskov substitution

Dependency Inversion

69
Liskov substitution

Objects in a program should be replaced with instances of their subtypes


without altering the correctness of that program

70
Avoid Negative conditionals

71
Encapsulate Boundary Conditions

72
Name at the appropriate level of Abstraction

73
Design Guidelines

Microsoft has official code conventions, follow the link and pay some time
reading..

https://msdn.microsoft.com/en-us/library/ms229042.aspx

74
75

You might also like