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

Clean code Naming

Uploaded by

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

Clean code Naming

Uploaded by

alashkar.ayman95
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Clean Code

characteristic
Characteristics of Clean Code
• Clear: does not use any ambiguous statements

• Readable: Clean code should read like well-written prose.

• Simple:
• Anybody can understand it anytime in the future
• Do one thing with the Single Responsibility Principle (SRP).
• Focused: Each function, each class, each module exposes a
single-minded attitude that remains entirely undistracted, and
unpolluted, by the surrounding details.
• Contains no duplication
Characteristics of Clean Code
• Elegant: Clean code is pleasing to read, should make you
smile.

• Testable: Run all the tests.

• Performant: the code should be pretty fast and use only


the resources it really needs

• Short: as short as possible but not shorter than that

• Smart

• Easy to change
Anti - Pattern
• A fragile system is a system that starts to malfunction in different
ways as soon as some part of the code changes.

• A rigid system is a system that resists changes, in a way that makes


changes very difficult to accomplish and makes estimates not
accurate.

• An Immobile system which refers to the inability to reuse software


from other parts of the system.

• An Unpredictable system
Anti - Pattern
• The messier the code, the more time it will take to add features later
in the project’s codebase.

• An inseparable system is a system for which reading the code is not


going to help in understanding the original author’s ideas and
purposes.

• A Cognitive burden system


You can survive without
them, but life would not be that fun.
Meaningful Names
What does your name
mean?
Why is a name important?
• If the code is read by somebody else or even by you after
a while, the knowledge you have now will not be
available. All that will be available will be the
variable name and the context.

• A piece of code spends far more time under


maintenance phase than development phase.
Names are Nouns
• Variable names are nouns
• The name must answer to the question: “Who are you?”

“I am [variable name]”

Examples:
“I am homeViewController” sounds good.
“I am storesViewController” sounds not.
var “carName, distance, timeInMinutes” sounds good.
var “compute, decide “sounds not.
Use Intention-Revealing
Names
Every time you name something, the name should reveal
your intentions.
• If you need to write a comment after the name, the name is not good
enough.
• If you have to go look in the code to understand a name, the name
has failed its purpose.

Example:
Expired: int ? Boolean? Date?
Expired -> is_expired : boolean
-> expiry_date : date
-> left_time_to_expire_in_days : int
SO Be specific
Use Intention-Revealing
Names
var time: Int # in seconds var timeInSeconds: Int
Replace magic numbers with named
constants
Making repeated changes to duplicate code in this way is one of the
leading causes of bugs, since it's easy to miss out one of the usages.
Replacing them with a constant means that the literal is stored in one
place and only needs to change in that place.
Another problem is that a bare number like the one in this example
doesn't tell you why it has the value or what it is for. Replacing it with a
constant let's you give it a descriptive name, which makes the code
easier to read and understand.
Use Pronounceable Names

Speake English : Use English words and make the


names readable.

If somebody calls you on the phone and asks you about the
name of the variable, you should have no issue saying it
without the need to spell it.
Use Pronounceable Names
Examples
Use Searchable Names
• Single-letter names and numeric constants have a
particular problem in that they are not easy to locate
across a body of text.

• When using long names, try not to make them too


similar, as they can be confused one to another.
For example “userNameBeforeEnteringLoginScreen” and
“userNameBeforeEnteringLogoutScreen” are not good
choices.
How long does it take to spot the subtle difference between
them? The words have frightfully similar shapes

• Don't append prefixes


Never use negations in Boolean
values
• Boolean values can be past participle:
is_found, is_crashed: Bool
• Don’t use Double negative
Use Unit of measure
Adding the unit of measure it is sometime useful for
clarifying the purpose of a variable.

• Length -> length_in_seconds?


duration_in_xx
length_in_hour?

• Length -> length_in_meter?


Add the types at the end of variable
name
In the case of certain types it is useful to include part of the object type
at the end of the variable.

This will allow the following code to need no explanation:

NOTE:
Do not refer to a grouping of accounts as an accountList unless it's actually
a List. The word List means something specific to programmers. If the container
holding the accounts is not actually a List, it may lead to false conclusions.
So accountGroup or bunchOfAccounts or just plain accounts would be better.
Use Domain Names
• Use Solution Domain Names: Remember that the people
who read your code will be programmers. So go ahead
and use computer science (CS) terms, algorithm names,
pattern names, math terms, and so forth.

• Use Problem Domain Names: When there is no


“programmer-eese” for what you’re doing, use the name
from the problem domain. At least the programmer who
maintains your code can ask a domain expert what it
means
Don’t s
• Avoid Mental Mapping: Readers shouldn't have to
mentally translate your names into other names they
already know.

• Don't be creative: Do not invent your own convention.


For example, do not consider adding str for each string or
nbr for each number when nobody does that.

• Don't Be Cute: While a name might look funny to you, it


might not for others. You might confuse the next
developer. eatMyShorts for abort ain’t a good name
Don’t s
• Pick one word per concept: Pick one word for one
abstract concept and stick with it. For instance, it’s
confusing to have fetch, retrieve, and get as equivalent
methods of different classes.

• Don't Pun: Avoid using the same word for two purposes.
Using the same term for two different ideas is essentially
a pun. Example: in a class use add for create a new value
by adding or concatenating two existing values and in
another class use add for put a simple parameter in a
collection, it's a better options use a name
like insert or append instead.
Don’t s
• Avoid ambiguous names:
For example the following names can be confusing:
User.getName -> User.getFirstName
User.getFullName

Location.getDistance ->
Location.getDistanceFromCurrentPositionInMiles

City.getTime -> City.getTimeInUT


Don’t s
• Remove useless words :
class User {
func getUserName(){}
}

class Database {
func initLocalDatabase(){}
}

class Game {
func restartGame() {}

func inviteAnotherUser() {}
}
Don’t s
• Don’t use one variable for multiple purpose is the
same chunk of code

let unit_price
unit_price = vals['unit_price'] * qty_done
unit_price += work_center_cost + extra_cost + additional_cost
unit_price = ….

total_quantity_price = vals['unit_price'] * qty_done


added_cost = work_center_cost + extra_cost + additional_cost
unit_price = ….
One difference between a smart
programmer and a professional
programmer is that
the professional understands that
clarity is king. Professionals use their
powers for good
and write code that others can
understand.
Method & Class
Names
Method Name
Methods should have verb or verb phrase names
like postPayment, deletePage or save.

Accessors, mutators, and predicates should be named for


their value and prefixed with get, set
Methods are Verbs
• Method names are Verbs
• The name must answer to the question: “What are you
doing?”
“I [Function name] should
be the answer”

Examples:
"I createDatabase" - is good.
"I sortArray" - is great.
"I user" - not that much.
"I database" - nop.
Also the order of the words is important. First one should be
a verb:
"I createDatabase" is good.
Long is okay
• The same as for variables make the name of the function
as long as you need, but not longer than that. For
example createLocalDatabase might be replaced with
createDatabase if there is only one database.
• Function name should describe clearly what it does.
• The parameters should follow variables naming
standards, clearly describing their purpose.
• Do not save space when naming a function.
• If making the name longer adds clarity, so be it.
Class Name
Classes and objects should have noun or noun phrase names
like Customer, WikiPage, Account, and AddressParser.

Avoid words like Manager, Processor, Data, or Info in the name of a


class.

A class name should not be a verb.


Context
• Consider the variables and the constants as thieves that steal
memory, processor cycles and developer attention. Hide them
as much as you can in the most restrictive context possible.

• If the variable is used only in a function, make it local to the


function.

• If only a class uses it, make it private.

• If you are not sure if a variable needs to be private, make it so


and you will find out.

• It is rare when you need global variables.


Context
• If you need global constants, add them in the class where it
makes the most sense. If it doesn't, create a separate file for
constants.

• The longer the scope of a variable, the longer its name should
be (if the scope is short, the variable name is used very near to
the declaration, and hence it’s easy to look for what it stands
for).

• Methods which are called from many places should have nice
and short names; private methods which are called in very few
places and with a small scope should have long and detailed
names.
1. Choose descriptive and unambiguous names.
2. Make meaningful distinction.
3. Use pronounceable names.
4. Use searchable names.
5. Replace magic numbers with named constants.
6. Avoid encodings. Don't append prefixes or type
information.
General rules
1. Follow standard conventions.
2. Keep it simple stupid. Simpler is always better. Reduce
complexity as much as possible.
3. Boy scout rule. Leave the campground cleaner than you
found it.
4. Always find root cause. Always look for the root cause of a
problem.
Understandability tips
1. Be consistent. If you do something a certain way, do all
similar things in the same way.
2. Use explanatory variables.
3. Encapsulate boundary conditions. Boundary conditions
are hard to keep track of. Put the processing for them in
one place.
4. Prefer dedicated value objects to primitive type.
5. Avoid logical dependency. Don't write methods which
works correctly depending on something else in the same
class.
6. Avoid negative conditionals.

You might also like