clean code: meaningful name

16

Upload: nahid035

Post on 06-May-2015

140 views

Category:

Software


3 download

TRANSCRIPT

Page 1: Clean code: meaningful Name
Page 2: Clean code: meaningful Name

Clean Code : Meaningful Name

Presented by Md. Nahidul Hasan

Page 3: Clean code: meaningful Name

Meaningful Name

■ Names are everywhere in software.

■ We name our variables, our functions, our arguments, classes, and packages.

■ We name our source files and the directories that contain them.We name our jar files and war files and ear files.

■ We name and name and name. Because we do so much of it, we’d better do it well

“The hardest thing about choosing good names is that it requires good descriptive skills and a shared cultural background.

This is a teaching issue rather than a technical, business, or management issue. As a result, many people in this field do not do it

very well.”

Page 4: Clean code: meaningful Name

Use Intention-Revealing Names

■ Choosing good names takes time but saves more than it takes.

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

■ The name of a variable, function or class should answer the big questions such as why it exists, what it does, how it

is used.

■ If a name requires a comment, then the name does not reveal its intent. For example, these names specify what is

being measured and the unit of that measurement:

int d // elapsed time in days

int elapsedTimeInDays; int daysSinceCreation; int daysSinceModification;

Page 5: Clean code: meaningful Name

Make Meaningful Distinctions

■ Distinguish names in such a way that the reader knows what the differences offer. For example, the two classes

ProductInfo and ProductData have different names but the names don’t mean anything different, because here

Info and Data are indistinct noise words.

■ More Example :

getActiveAccount(); getActiveAccounts();

getActiveAccount(); getAllActiveAccounts();

Page 6: Clean code: meaningful Name

Use Pronounceable Names

■ Our minds have evolved to deal with spoken language, so take advantage of that when creating names.

■ Also, if you can’t pronounce it, you can’t discuss it without sounding like an idiot.

■ As an example, note the benefits of using the second version of this variable instead of the first version

class DtaRcrd102 {

private Date genymdhms;private Date modymdhms;private final String pszqint = "102"; /* ... */};

class Customer {private Date generationTimestamp; private Date modificationTimestamp;private final String recordId = "102"; /* ... */};

Page 7: Clean code: meaningful Name

Use Searchable Names

■ Names should be easy to locate across a body of text.

■ The length of a name should correspond to the size of its scope.

■ If a variable or constant might be seen or used in multiple places in a body of code, it is imperative to give it a

search-friendly name.

for (int j=0; j<34; j++) { s += (t[j]*4)/5;}

int realDaysPerIdealDay = 4;const int WORK_DAYS_PER_WEEK = 5;int sum = 0;for (int j=0; j < NUMBER_OF_TASKS; j++) {

int realTaskDays = taskEstimate[j] * realDaysPerIdealDay;

int realTaskWeeks = (realdays / WORK_DAYS_PER_WEEK);

sum += realTaskWeeks; }

Page 8: Clean code: meaningful Name

Avoid Encodings

■ Encoding type or scope information into names simply adds to the burden of deciphering. They are a mental

burden, seldom pronounceable and easy to mistype.

■ Hungarian Notation (HN) adds nothing to Java, as the objects are strongly typed and IDEs detect type errors

long before compilation. A variable that has its type changed, but accidentally not had its HN name changed can

be misleading.

Page 9: Clean code: meaningful Name

Avoid Mental Mapping

■ Readers should not need to mentally translate your names into other names they already know/are familiar

with. This problem generally arises from a choice to use NEITHER problem-domain terms nor solution-domain

terms (see more, below, on problem-domain and solution-domain).

■ Single-letter variable names are really only okay for use as loop counters if their scope is very small and no other

names can conflict with them; plus they are traditional.

■ In general programmers are pretty smart people. Smart people sometimes like to show off their smarts by

demonstrating their mental juggling abilities. However:

“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.”

Page 10: Clean code: meaningful Name

Class Names

■ Classes and objects should have noun or noun-phrase names, like Customer,WikiPage, Account and

AddressParser.

■ But avoid names like Manager, Processor, Data or Info in the name of a class.

■ A class name should not be a verb.

Method Names

■ Methods should have verb or verb-phrase names, like deletePage or save.

■ Accessors and mutators, and their predicates, should be named according to JavaBeanstandards

Page 11: Clean code: meaningful Name

Don’t Pun

■ Don’t deliberately or inadvertently re-use the same term where its semantic meaning in the code is different; for

example using the term add in several classes, for “consistency”, when you are in fact not using it in the same

sense.

Use Solution Domain Names

■ The people who read you code are programmers, so go ahead and use solution domain terms, such as

AccountVisitor, where Visitor means the VISITOR pattern, or JobQueue.

Use Problem Domain Names

■ When there is no programmer-eese for what you are doing, use the name from the problem domain. However:

The code that has more to do problem domain concepts should have names drawn from the problem domain.

Page 12: Clean code: meaningful Name

Add Meaningful Context

■ Most names are not meaningful in and of themselves. So:

You need to place names in a context for your reader by enclosing them in well-named classes, functions or namespaces.

Naming within an Unclear Context:private void printGuessStatistics(char candidate, int count) { String number; String verb; String pluralModifier; if (count == 0) { number = "no"; verb = "are"; pluralModifier = "s"; } else if (count == 1) { number = "1"; verb = "is"; pluralModifier = ""; } else { number = Integer.toString(count); verb = "are"; pluralModifier = "s"; } String guessMessage = String.format("There %s %s %s%s", verb, number, candidate, pluralModifier); print(guessMessage);}

Page 13: Clean code: meaningful Name

Add Meaningful Context Naming within a Clear Context:

public class GuessStatisticsMessage { private String number; private String verb; private String pluralModifier; public String make(char candidate, int count) { createPluralDependentMessageParts(count); return String.format("There %s %s %s%s", verb,number, candidate, pluralModifier); } private void createPluralDependentMessageParts(int count) { if (count == 0) { thereAreNoLetters(); } else if (count == 1) { thereIsOneLetter(); } else { thereAreManyLetters(count); } }

private void thereAreManyLetters(int count) { number = Integer.toString(count); verb = "are"; pluralModifier = "s"; } private void thereIsOneLetter() { number = "1"; verb = "is"; pluralModifier = ""; } private void thereAreNoLetters() { number = "no"; verb = "are"; pluralModifier = "s"; }}

Page 14: Clean code: meaningful Name

Pick One Word per Concept

■ Pick and use one word for abstract concept and stick with it.

■ A consistent lexicon is a great boon to the programmers who use your code.

■ Example: What’s the difference between fetch, retrieve and get?

Don’t Be Cute

■ Don’t be too clever or humourous with your names. Don’t use a function name likeholyHandGrenade, when you

mean deleItems.

■ For example, don’t use the name whack() to mean kill()

Page 15: Clean code: meaningful Name

Don’t Add Gratuitous Context

■ Shorter names are generally better than longer ones, so long as they are clear.

■ Add no more context to a name than is necessary.

■ Examples: The names accountAddress and customerAddress are fine names for instances of the class Address

but could be poor names for classes. Address is a fine name for a class. If you need to differentiate between MAC

Addresses, port addresses, and Web addresses, you might consider PostalAddress, MAC, and URI.

■ In an imaginary application called “Gas Station Deluxe,” it is a bad idea to prefix every class with GSD.

A mailingadress classs for in GSD’s accounting Module - GSDAccountAdress A mailing address for cutomer contact - GSDAccountAdress

Page 16: Clean code: meaningful Name

END

Thanks to All