Variable naming is a philosophy. This sentence is not merely a feeling, not merely an indescribable complex thing to philosophy.

It is philosophy in the true sense, with philosophical skills to follow and practical guidance.

Programs do not need variable names for execution on machines, but for execution in the human brain.

The human brain executes the program, following the cognitive law of psychology, and therefore is not exactly the same as the machine execution characteristics of the program.

The same task can be solved by different programming languages, and can be solved in different ways within the same programming language. This is a one-to-many relationship.

However, very few code implementations follow the rules of human cognition and thus behave as more readable.

Of course, the cognitive law here is a diorama, not one-sided:

  • Code that can be read without learning or thinking is good code;

  • The code I find easy to read, and through empathy, the code I imagine easier to read for someone less capable than me, is the code that conforms to the laws of cognition.

Humans are learning animals, and learning itself can be a fun process. It is possible to pursue learning in code design, and to encourage others to learn, and to try to make the most of cognitive strategies.

So, a code that is not easy to understand at first glance is not necessarily a code that is not easy to understand, but after learning it, it may become very intuitive code, very elegant code. This kind of learning experience is common in mathematical formulas, where code is essentially more trivial mathematical formulas.

So, what are some of our cognitive rules that can help us make code more expressive? How is this reflected in the variable naming technique?

Human love focus, and is the key to specific focus

Lonely sail far shadow blue sky, but see the Yangtze river flow in the sky.

Lei jun said that writing code should be like writing poetry, this is not an empty expression. Variable names in code, like poetry, cut out unnecessary details and keep the most important words, and the more specific the words, the better than vague and inaccurate ones.

Write more poetry, or training classical Chinese, increase the language foundation, help to improve variable naming skills.

2. Humans like to categorize, especially visually

The choreography of the code also has visual effects, the same processing of the same resource can be put together, the same processing can be put together, the same processing can be put together.

Sometimes, there are conflicts between different categories that cannot be satisfied at the same time. At this point, you need to find the key classification, and focus on it. If you can’t find it, try more, adjust more, and feel the change.

In terms of variable naming, try to aggregate the same class together. Visually and conceptually, they can be processed as a visual block, reducing the space in working memory.

In this case, a well-classified pure function has a great advantage. The code pattern of a pure function is very same. The function body starts with a pair of get assignment statements and then returns an expression.

Get -> return mode allows the developer to jump to the function definition with the expectation already in mind (preload the mental framework of relevant code identification, add code reading efficiency and maintain flow).

Humans like stratification, especially layers of progressive stratification

When things are complex, we like to see the layers of things, each layer is simple and becomes complicated to organize, but the simplicity behind the complexity is not so complicated.

  • The hierarchical dimension of space is mainly divided into blocks. A large task is divided into several components, and each component is refined and processed.

  • The hierarchical time dimension is mainly divided into stages. A large task is divided into multiple stages, and each stage is refined and processed.

  • The layering of conceptual dimensions is mainly from special to general, a bunch of specific tasks are generalized to more general scenarios, and then refined back through parameterization.

Three hierarchies provide a framework for naming variables.

  • XPartOfThing refers to the x part after the hierarchical dimension of space, and can also have yPartOfThing and so on, that is, we can give a placeholder before we name it. We only know the Thing level, but we don’t know enough about its detailed components to call it xPartOfThing, so we can temporarily call it xPartOfThing, and then we can assign more specific variable names as the code progresses, and we know more about the components. Okay

  • XPhaseOfThing refers to the X stage after the hierarchical time dimension. It is the same as the hierarchical space dimension

  • XLayerOfThing refers to the X layer after the hierarchical concept dimension. After a clearer understanding of the problem, a new name is assigned.

You may be wondering if you have to name a variable once, but have to constantly refactor the code and change the variable name.

True, elegant code is not, and should not be, done in one go. The advantage of being software, rather than hardware, is that it is more editable and can be adjusted, updated and iterated over and over again.

It’s not just new requirements that force us to change the code, but also a new understanding of the problem.

Don’t skimp on changing variable names.

Human beings like to justify themselves

As we rationalize, our minds seem to be activated, creative, trying to build more complete structures, and happy.

How does the code justify itself? Organize our code by domain and produce interfaces.

This way of organizing code leads developers to do the above (spatial, temporal, and conceptual) layering around a particular domain.

At this point, inspiration for variable naming springs forth, free of charge.

For example, when writing the Web Framework and dealing with server-specific domains, HttpRequest, HttpResponse, HttpHeaders, HttpMethod, Url, JsonResponse, HtmlResponse, FileResponse……

Many domain-related elements will inspire developers to name variables. However, this only works if we organize code by domain. Simply follow the linear execution process of programming tasks, to implement and solve one by one, will encounter multiple fields of blocks, stages and concepts intertwined.

This kind of interweaving is not conducive for us to focus on any single field for a more comprehensive understanding and overall planning, and it also greatly increases the cognitive burden. Things of different nature are difficult to form a cognitive memory block, and it is easy to occupy too much working memory.

Each time we focus on a single field, the layers and blocks within the field and their relationships will more naturally harmonize in cognition and be treated as a whole. Our tendency to justify ourselves is to focus on the structural or hierarchical integrity of symmetry, duality, closed loops, etc., in the domain.

For example, open means close, get means set, add means DELETE, and so on. These operations, which often go together, are all complimentary variable names.

More importantly, self-justification for multiple single domains adds quality code assets to our codebase, where many of the underlying domain issues have been addressed and code can be written to focus on high-level business logic.

Humans also like abstraction

Before, I said that humans like concrete, but here we say that humans like abstract. Is that a contradiction?

There is no contradiction.

A lot of times, people misuse the word “abstract” and call something vague and inaccurate “too abstract.”

Most of the time, people misunderstand the word “abstract” and call it “too abstract” for things they have not learned or understood.

Just because humans like concrete things doesn’t mean they don’t like abstract things. Humans are better at processing concrete things because the stimulation of concrete things is more common in everyday life, whereas the stimulation of abstract things requires extra creation.

In other words, abstract stimuli are scarce.

Here we need to introduce the concept of “professional training”, the so-called professional training, which is to increase the level of stimulation of abstract things in a particular field, so that we can also establish a better level of processing of terms in a particular field.

Most programmers have been professionally trained in basic programming knowledge. Terms such as variable, function, loop, class, inheritance, etc. are processed more efficiently than ordinary people.

But that’s not enough for writing elegant variable names, for writing elegant code.

Elegant code often contains abstract knowledge of two core areas:

  • The code field
  • The problem domain

Developers need to understand not only programming, but also the business domain problems they face, and integrate the two. This is the tactical part of domain-driven design (DDD), how to programmatically replicate concepts and organizational relationships in the business domain model.

It’s not just the code domain that has frameworks, it’s the non-code domain that has frameworks. Mathematics, for example, is the framework for all fields of knowledge.

Even mathematics has its own subdivisions, and there are even subdivisions of mathematical properties of mathematics, which can be called the framework of mathematical Theory, such as Category Theory.

Learning to use frameworks can help us understand and solve domain-specific problems more quickly.

The framework of learning framework can help us build a domain-specific framework more quickly.

There are also similarities between frameworks, which can also be integrated and organized organically.

For example, the add, delete, change, review (CRUD) model for resources is the framework for many business domain specific models. Many problems can be modeled as management processes for specific resources.

CQRS processing of resources is a further refinement of CRUD model. Its main contribution is to separate the Read /write model and emphasize the layering of the technical domain and the business domain. CRUD is a concept in the technical field with few constraints, while models in the business field often require more constraints and are not free to add, delete, change and check. Therefore, it is not easy to focus on domain issues around CRUD, while CQRS emphasizes the construction of Query model in line with the business model to query resources. Build the Command Model to update the resource.

These things are known as — architecture.

  • A framework is an abstraction of a domain-specific problem
  • The framework of a framework (architecture) is an abstraction of the organizational relationships of multiple domain problems
  • The framework of the framework of the framework is an abstraction of the organizational relationships of multiple organizational relationships…
  • The framework of the framework of the framework (paradigm) is an abstraction of the organizational relationships of multiple organizational relationships
  • The four – order framework is an abstraction of the organization relation of the three – order framework
  • The n-order framework is an abstraction of the organization relation of the n-1 order framework

Humans like abstractions, and like to see them broken up into multiple, side by side subsections like the one above, where each section is some sort of progressive abstraction of the previous section, containing a particular pattern of things (essentially induction).

Human beings like abstraction, but the ability of abstraction needs professional training. The process of professional training is the process of learning, which often contains a lot of confusion and distress. We often misunderstand that we don’t like abstractions.

When we successfully master certain levels of abstraction, we fall in love with them.

The more levels of abstraction you master, the more disciplined and easy it is to write code with names.

We can use getResource, setResource, queryRespurce, sendCommand, and other more general abstract words to write code, and then replace them with more specific operation names and resource names when the code is written.

In other words, the abstract framework allows our code to converge faster. We don’t have to block because we don’t know the specific name, but we know it must be one of some broader concept/resource/pattern. We use the abstract as a placeholder and continue to expand the code. When we’re done, we’ll come back and assign new variable names one by one, with a fuller and more comprehensive understanding of the problem and where each variable name fits in the overall code picture.

In general, human beings like abstractions, but they don’t like abstractions well mastered.

Humans are sensitive to trends and goals

Humans are predictive animals, and we’re always trying to predict what’s going to happen with limited clues, and we’re happy that things fit our predictions.

How can this feature be used to optimize variable naming?

Trends, goals, and goals are expressed in variable names (especially function names) to express the intent of resource changes.

For example, setCount(count + step), a generic data update process, is encapsulated into an increaseBy(step), which shows the intent and trend of the data change, while its domain-related operations are displayed again, such as decreaseBy(step). SetMax (maxValue), setMin (minValue), animateTo (targetCount).

Count domains can only be subject to min and Max constraints if they are removed from simple generic technical semantics. CountDomain#increaseBy(step) is an increment in a domain-specific context, and overflow values can be discarded.

The purely technical semantics of setCount(newCount) make it difficult to allow count to be anything other than newCount, unless the function returns Boolean and other information telling the outside world whether the update was successful and why the update failed.

When you add intents to variable names, you often make them verbose. This is hard to avoid, and it takes a lot of training to improve your ability to deliver the “critical concrete” element of the first paragraph, which is the ability to write poetry.

Human beings like honest things

What is sincere code, do what you say, do what you say, is for sincerity.

A lot of code has variable names that change semantically and remain unchanged, and execution and variable names can even have opposite meanings.

Many developers, in order to simplify the length of the code, excessive compression, eliminate a lot of prefixes, leaving specific code with a broader noun, the degree of abstraction does not match, looks exaggerated.

Every time a small module is developed, an overall “integrity review” is needed to check that the code does what it says it does.

This may seem like a hassle, and it is at first, but it’s well worth it. The trouble is not constant, and as we become more familiar and our naming skills mature, the review time will shorten. Also, new room for modification can often be developed during the review phase.

conclusion

We could list many more elements and techniques, but we don’t need to, because it’s all tactical in nature.

The above can be learned in practice by developers themselves if the strategic mindset is adjusted. And if the strategic mindset doesn’t change, the tactical elements above will just haunt us as another thing that’s “too abstract,” “out of touch,” “too idealistic.”

The true value and meaning of these tactics are lost.

So what is this strategic mindset?

Is it our fundamental attitude toward code, do we see coding as a tool to accomplish goals, or is it an activity like writing an essay or even a poem that is an end in itself?

Do we put as much effort into code as we do into writing good articles and poems?

We treat our writing and writing as valuable personal creations and assets. Do we look at our code from the same asset perspective?

Are we bored, or are we happy, in the process of extracting subfunctions? Is it a hassle, or do you feel like you’ve added a good code asset and added insight into the problem?

Many developers often say that code is a problem solver and don’t think narrowly in technical terms. I emphasize here that the code is an end in itself, is it too technical to emulate?

No, there is no conflict.

People do not have only one purpose, many different situations, there are different ends and means of the relationship.

Code is still a tool for solving business problems, but if you want to write good code, you should write good code as a goal. This mentality has nothing to do with the tool nature of code at the problem solving level.

Purpose at one level can be a tool at another level, compatible with each other.

Developers who always use technology and code as tools may end up blocking technical achievements, not taking code and technology seriously, not investing enough, and easily hitting technical ceilings.

Developers who always focus on technology and code for purpose will eventually suffer in non-technical areas as well.

We also need layering in our attitude to code, and that layering is at the level of human cognitive psychology, not just for writing code.

The key is to improve our cognitive level, the level of writing code is an application of cognitive level. Most of the time, it’s not a lack of programming skills that keeps us from writing elegant code, it’s a lack of awareness of the problem.

The technique of assigning abstract placeholder variables was introduced earlier, that is, around the cognitive level, to unblock programming, advance the processing of the problem, accumulate the understanding of the problem, improve the cognition and then return the variable name.

Elegant variable names come not just from programming skills, but from domain knowledge.

Cognitive attitudes and skills are strategic, while programming skills and experience are tactical.

As the strategic level increases, the amount of time we spend reading, communicating and thinking increases, and the percentage of time we spend coding decreases, but the quality and efficiency increases.

Code efficiency increases both from understanding domain issues and from mastering the higher-order abstractions mentioned earlier (framework of framework of framework…). We can build programming models without actually writing code.

Because we have mastered the relationship between technical concepts in programming, we know that x can solve X, y must have Z, and A operation and B elements can form C structure and express the intention of D, which can be used as g function of F layer after e module…

With a lot of professional training, we are as familiar with the relationships between technical abstractions as entertainment fans are with the gossipy relationships between their idols.

The problem of variable naming is not the problem of variable naming, but the problem of cognitive level and professional training degree.

Every time we hone our code and learn more abstract programming and math, we’re training for better abstraction next time. Elegant variable names are a byproduct of that.

Start by changing your attitude to code, and try writing code like poetry.

To see a thousand miles, to the next level