Friday, November 3, 2017

How to Name Things


https://skillsmatter.com/skillscasts/5747-how-to-name-things-the-solution-to-the-hardest-problem-in-programming
https://www.slideshare.net/pirhilton/how-to-name-things-the-hardest-problem-in-programming

https://news.ycombinator.com/item?id=9598527
An important rule is missing here: variables should be named with their scope in mind. So if a variable is longer lived and has larger scope its name should be that much more descriptive because when you're looking at it the only thing that will tie the value of the variable to the context within which it can be used is its name.
So 'i' is fine for a loop control variable with a scope of five lines but totally inadequate for something expressing a larger and longer lived concept.
Ditto for function names and parameters to functions, if the function and the parameters are named properly understanding the function is trivial.
So if you write a chunk of code that exports one or more functions that is where your effort should go, that's the public interface. The reduced scope of the rest of the code should make any naming issues much more limited.

An expressive name for a software object must be clear, precise, and small. 
Use Intention-revealing Names
We often see comments used where better naming would be appropriate:
 int d; // elapsed time in days
Such a comment is an excuse for not using a better variable name. The name 'd' doesn't evoke a sense
of time, nor does the comment describe what time interval it represents. It requires a change:
 int elapsedTimeInDays;
 int daysSinceCreation;
 int daysSinceModifica
The problem isn't the simplicity of the code but the implicity of the code: the degree to which the
context is not explicit in the code itself

Avoid Disinformation
A software author must avoid leaving false clues which obscure the meaning of code.
Do not refer to a grouping of accounts as an AccountList unless it's actually a list. The word
list means something specific to CS people. If the container holding the accounts is not actually a
list, it may lead to false conclusions. AccountGroup or BunchOfAccounts would have been
better.
Beware of using names which vary in small ways. How long does it take to spot the subtle difference
between a XYZControllerForEfficientHandlingOfStrings in one module and,
somewhere a little more distant XYZControllerForEfficientStorageOfStrings? The
words have frightfully similar shape.

It is nice if names for very similar things sort together alphabetically, and if
the differences are very, very obvious since the developer is likely to pick an object by name without
seeing your copious comments or even the list of methods supplied by that class.

Make Meaningful Distinctions
Noise words are another meaningless distinction. Imagine that you have a Product class. If you have
another called ProductInfo or ProductData, you have made the names different without making
them mean anything different. Info and Data are indistinct noise words like "a", "an" and "the".
Noise words are redundant. The word variable should never appear in a variable name. The word
table should never appear in a table name. How is NameString better than Name? Would a Name
ever be a floating point number? If so, it breaks an earlier rule about disinformation. Imagine finding
one class named Customer and another named CustomerObject, what should you understand as the
distinction? Which one will represent the best path to a customer's payment history?

Disambiguate in such a way that the reader knows what the different versions offer her, instead of
merely that they're different.

Use Pronounceable Names
A company I know has genymdhms (generation date, year, month, day, hour, minute and second) so
they walked around saying "gen why emm dee aich emm ess". I have an annoying habit of pronouncing
everything as-written, so I started saying "gen-yah-mudda-hims". It later was being called this by a host
of designers and analysts, and we still sounded silly. But we were in on the joke, so it was fun. Fun or
not, we were tolerating poor naming. New developers had to have the variables explained to them, and
then they spoke about it in silly made-up words instead of using proper English terms.
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";
 /* ... */
};

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.

My personal preference is that single-letter names can ONLY be used as local variables inside short
methods. The length of a name should somehow 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.

Avoid Encodings
Avoid Mental Mapping
Smart is overrated. Clarity is king. The very smart must use their talent to write code that others are
less likely to misunderstand.
Use Noun and Verb Phrases
Classes and objects should have noun or noun phrase names.

Other methods (sometimes called "mutators", though not so commonly anymore) cause something to
happen. These represent a small "transaction" on the object (and generally should be a complete
action). Mutators should have verb or verb-phrase names. This way, changing a name would read:
 fred.changeNameTo("mike");
You will notice that the above line reads more like a sentence than a lot of code. It leaves a dangling
"to", which is completed by the parameter. The intention is to make the parameter list more obvious so
that it is harder to make foolish errors.
Another trend is to use a named creation function, rather than yet another overloaded constructor. It can
be more obvious to read the creation of a complex number using
 Complex.FromRealNumber(23.0);
than using the constructor version
 new Complex(23.0);

As a class designer, does this sound boringly unimportant? If so, then go write code that uses your
classes. The best way to test an interface is to use it and look for ugly, contrived, or confusing text. The
most popular way to do this in the 21st century is to write Unit Tests for the module. If you have
trouble reading the tests (or your partners do) then rework is in order.
Over time we've found that this rule extends even to constructors. Rather than having a lot of
overloaded constructors and having to chose among them by their parameter lists, we frequently create
named creation functions as class (static) methods.
Don't Be Cute

Pick One Word Per Concept
Pick one word for one abstract function and stick with it. 

A consistent lexicon is a great boon to programmers who must use your classes, even if it may seem
like a pain while developing the classes. If you have to, you can write it into a wiki page or a document,
but then it must be maintained. Don't create documents lightly.

you want your readers to afford some lazy reading and
assumptions. You want your code to be a quick skim, not an intense study. You want to use the popular
paperback model whereby the author is responsible for making himself clear and not the academic
model where it is the scholar's job to dig the meaning out of the paper.

Use Solution Domain Names
Solution domain names are appropriate only if you are working at a low-level where the solution
domain terms completely describe the work you are doing. For work at a higher level of abstraction,
you should Use Problem Domain Names

Make Context Meaningful
Add Meaningful Context
If you have a number of variables with the same prefix (address_firstName, address_lastname,
address_Street), it can be a pretty clear clue that you need to create a class for them to live in
Don't add Gratuitous Context

Shorter names are generally better than longer ones, if they are clear. Add no more context to a name
than is necessary.
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 I need to
differentiate between MAC addresses, port addresses, and web addresses, I might consider
PostalAddress, MAC, and URI. The resulting names are more precise, and isn't precision the point of
all naming?


Meaningful Names

This factory will be an interface and will be implemented by a concrete class. What should you name them? IShapeFactory and ShapeFactory? I prefer to leave interfaces unadorned. The preceding I, so common in today’s legacy wads, is a distraction at best and too much information at worst. I don’t want my users knowing that I’m handing them an interface. I just want them to know that it’s a ShapeFactory. So if I must encode either the interface or the implementation, I choose the implementation. Calling it ShapeFactoryImp, or even the hideous CShapeFactory, is preferable to encoding the interface.

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.

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, and is according to the javabean standard

When constructors are overloaded, use static factory methods with names that describe the arguments

PICK ONE WORD PER CONCEPT

The power of variable names

PROBLEM ORIENTATION
A good mnemonic name generally speaks to the problem rather than the solution. A good name tends to express the what more than the how. In general, if a name refers to some aspect of computing rather than to the problem, it's a how rather than a what. Avoid such a name in favor of a name that refers to the problem itself.

A record of employee data could be called inputRec or employeeData. inputRec is a computer term that refers to computing ideas—input and record. employeeData refers to the problem domain rather than the computing universe. Similarly, for a bit field indicating printer status, bitFlag is a more computerish name than printerReady. In an accounting application, calcVal is more computerish than sum.

Names that are too long are hard to type and can obscure the visual structure of a program.
numTeamMembers, teamMemberCount
numSeatsInStadium, seatCount
teamPointsMax, pointsRecord

Programs with names averaging 8 to 20 characters were almost as easy to debug.

COMPUTED-VALUE QUALIFIERS IN VARIABLE NAMES

A programmer reading such a variable should be able to assume that its value isn't used outside a few lines of code
longer names are better for rarely used variables or global variables and shorter names are better for local variables or loop variables

If you modify a name with a qualifier like Total, Sum, Average, Max, Min, Record, String, or Pointer, put the modifier at the end of the name.
An exception to the rule that computed values go at the end of the name is the customary position of the Num qualifier. Placed at the beginning of a variable name, Num refers to a total: numCustomers is the total number of customers. Placed at the end of the variable name, Num refers to an index: customerNum is the number of the current customer. The s at the end of numCustomers is another tip-off about the difference in meaning. But, because using Num so often creates confusion, it's probably best to sidestep the whole issue by using Count or Total to refer to a total number of customers and Index to refer to a specific customer. Thus, customerCount is the total number of customers and customerIndex refers to a specific customer.

COMMON OPPOSITES IN VARIABLE NAMES
If a variable is to be used outside the loop, it should be given a name more meaningful than i, j, or k.
If you have several nested loops, assign longer names to the loop variables to improve readability.
many experienced programmers avoid names like i altogether.


Use positive boolean variable names. Negative names like notFound, notdone, and notSuccessful are difficult to read when they are negated
if not notFound
When naming constants, name the abstract entity the constant represents rather than the number the constant refers to.

Creating Short Names That Are Readable
Kinds of Names to Avoid
Avoid names with similar meanings.
input and inputValue, recordNum and numRecords, and fileNumber and fileIndex are so semantically similar that if you use them in the same piece of code you'll easily confuse them and install some subtle, hard-to-find errors.

Avoid names that sound similar, such as wrap and rap

Avoid variables with different meanings but similar names.
Have at least two-letter differences between names, or put the differences at the beginning or at the end. clientRecords and clientReports are better than the original names.

Avoid numerals in names
Avoid misspelled words in names.




Labels

Review (554) System Design (293) System Design - Review (189) Java (178) Coding (75) Interview-System Design (65) Interview (60) Book Notes (59) Coding - Review (59) to-do (45) Knowledge (39) Linux (39) Interview-Java (35) Knowledge - Review (32) Database (30) Design Patterns (29) Product Architecture (28) Big Data (27) Soft Skills (27) Miscs (25) MultiThread (25) Concurrency (24) Cracking Code Interview (24) Career (22) Interview - Review (21) Java - Code (21) Operating System (21) Distributed (20) Interview Q&A (20) OOD Design (20) System Design - Practice (19) Security (17) Algorithm (15) How to Ace Interview (15) Brain Teaser (14) Google (13) Linux - Shell (13) Spark (13) Spring (13) Code Quality (12) How to (12) Interview-Database (12) Interview-Operating System (12) Redis (12) Tools (12) Architecture Principles (11) Company - LinkedIn (11) Testing (11) Resource (10) Solr (10) Amazon (9) Cache (9) Search (9) Web Dev (9) Architecture Model (8) Better Programmer (8) Company - Uber (8) Interview - MultiThread (8) Java67 (8) Math (8) OO Design principles (8) SOLID (8) Scalability (8) Cassandra (7) Git (7) Interview Corner (7) JVM (7) Java Basics (7) Machine Learning (7) NoSQL (7) C++ (6) Design (6) File System (6) Highscalability (6) How to Better (6) Kafka (6) Network (6) Restful (6) Trouble Shooting (6) CareerCup (5) Code Review (5) Company - Facebook (5) Hash (5) How to Interview (5) JDK Source Code (5) JavaScript (5) Leetcode (5) Must Known (5) Be Architect (4) Big Fata (4) C (4) Company Product Architecture (4) Data structures (4) Design Principles (4) Facebook (4) GeeksforGeeks (4) Generics (4) Google Interview (4) Hardware (4) JDK8 (4) Optimization (4) Product + Framework (4) Shopping System (4) Source Code (4) Web Service (4) node.js (4) Back-of-Envelope (3) Company - Pinterest (3) Company - Twiiter (3) Company - Twitter (3) Consistent Hash (3) GOF (3) Game Design (3) GeoHash (3) Growth (3) Guava (3) Interview-Big Data (3) Interview-Linux (3) Interview-Network (3) Java EE Patterns (3) Javarevisited (3) Map Reduce (3) Math - Probabilities (3) Performance (3) Puzzles (3) Python (3) Resource-System Desgin (3) Scala (3) UML (3) geeksquiz (3) AI (2) API Design (2) AngularJS (2) Behavior Question (2) Bugs (2) Coding Interview (2) Company - Netflix (2) Crawler (2) Cross Data Center (2) Data Structure Design (2) Database-Shard (2) Debugging (2) Docker (2) Elasticsearch (2) Garbage Collection (2) Go (2) Hadoop (2) Html (2) Interview - Soft Skills (2) Interview-Miscs (2) Interview-Web (2) JDK (2) Logging (2) POI (2) Papers (2) Programming (2) Project Practice (2) Random (2) Software Desgin (2) System Design - Feed (2) Thread Synchronization (2) Video (2) ZooKeeper (2) reddit (2) Ads (1) Advanced data structures (1) Algorithm - Review (1) Android (1) Approximate Algorithms (1) Base X (1) Bash (1) Books (1) C# (1) CSS (1) Chrome (1) Client-Side (1) Cloud (1) CodingHorror (1) Company - Yelp (1) Counter (1) DSL (1) Dead Lock (1) Difficult Puzzles (1) Distributed ALgorithm (1) Eclipse (1) Facebook Interview (1) Function Design (1) Functional (1) GoLang (1) How to Solve Problems (1) ID Generation (1) IO (1) Important (1) Internals (1) Interview - Dropbox (1) Interview - Project Experience (1) Interview Tips (1) Interview-Brain Teaser (1) Interview-How (1) Interview-Mics (1) Interview-Process (1) Jeff Dean (1) Joda (1) LeetCode - Review (1) Library (1) LinkedIn (1) LintCode (1) Mac (1) Micro-Services (1) Mini System (1) MySQL (1) Nigix (1) NonBlock (1) Process (1) Productivity (1) Program Output (1) Programcreek (1) Quora (1) RPC (1) Raft (1) RateLimiter (1) Reactive (1) Reading (1) Reading Code (1) Refactoring (1) Resource-Java (1) Resource-System Design (1) Resume (1) SQL (1) Sampling (1) Shuffle (1) Slide Window (1) Spotify (1) Stability (1) Storm (1) Summary (1) System Design - TODO (1) Tic Tac Toe (1) Time Management (1) Web Tools (1) algolist (1) corejavainterviewquestions (1) martin fowler (1) mitbbs (1)

Popular Posts