开源日报 每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,坚持阅读《开源日报》,保持每日学习的好习惯。
今日推荐开源项目:《取其精华 pattern-dreamer》
今日推荐英文原文:《How To Create Meaningful Names In Code》

今日推荐开源项目:《取其精华 pattern-dreamer》传送门:GitHub链接
推荐理由:这个项目能够提取一个字符串中的重要元素——比如邮件地址和 URL 以及它们的各种参数等。为了避免这些繁杂的工作,用户的输入通常应该遵守规定的格式以便于处理;但是在有些比如处理文本等无法预先给定格式的场合,要想把 URL 和参数等一个个分拣出来并非易事,要把正则表达式和字符串处理等各种神通都用上兴许才能做到准确拆分,而这个项目就做到了。
今日推荐英文原文:《How To Create Meaningful Names In Code》作者:Daan Daan
原文链接:https://medium.com/better-programming/how-to-create-meaningful-names-in-code-20d7476537d4
推荐理由:哦我亲爱的老伙计,放下那本见鬼的婴儿起名指南吧

How To Create Meaningful Names In Code

Simple rules you can follow to create good names


As a developer, you spend a lot of your coding time making variables and thinking about proper names. Names are everywhere. You name files, classes, methods, and variables.

As we spend so much time naming things it’s really important to do it well. In this article, I will show you some simple rules you can follow for creating good names. Naming things in your code is an art in itself!

Use Names Which Reveal Intention

Having names which reveal their intent is easier said than done. How often do you come across variable names that don’t tell you anything about their intent?

A good rule of thumb is: If a name requires a comment, then it doesn’t reveal the intent.

The following piece of code is a variable which does not reveal intent:
<?php
private $s; // Time in seconds
The variable $s reveals nothing. It does not evoke a sense of lapsed time. It would be better to choose a name that specifies what is being measured, and the unit of that measurement.

One of the variable names in the example below would be much better.
<?php
private $days_since_creation;
private $elapsed_time_in_seconds;
private $seconds_since_last_modified;
Choosing names that reveal intent can make it much easier to understand a piece of code, and therefor easier to maintain.

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

Let’s take a look at the following example:
<?php
function getList() {
    $list1 = [];

    foreach ($this->the_list as $x) {
        if ($x % 2 != 0) {
            $list1[] = $x;
        }
    }

    return $list1;
}
function getOddNumbers() {
    $odd_numbers = [];

    foreach ($this->numbers as $number) {
        if (isOdd($number)) {
            $odd_numbers[] = $number;
        }
    }

    return $odd_numbers;
}
Why is it so hard to tell what the getList function does? There are no complex expressions. The code is indented and formatted properly. Only three variables are used and there’s no fancy stuff.

Now take a look at the getOddNumbers function. Did you see that the function does exactly the same as the getList function?

Notice that the simplicity of the code has not changed. It still has exactly the same number of operators and variables, with exactly the same number of nesting levels. The only thing that has changed, is that the code has become much more explicit.

With some simple name changes, it is suddenly much easier to tell what this piece of code does.

Avoid Disinformation

You should avoid leaving false clues that obscure the meaning of code.

Avoid misleading words where their meaning varies from the intended meaning. For example, do not refer to a grouping of products as a productList, unless it actually is an object of the type List. This can lead to false conclusions. A better name would be products.

Probably the worst variable names that you can pick are uppercase O and lowercase L. This is because they look a lot like 0 and 1.

Beware of using names that vary in small ways. How long does it take to spot the subtle difference between SomeMethodForEfficientHandlingOfFiles in one file, and SomeMethodForEfficientStorageOfFiles in another file? At first sight, these names look the same.

Make Meaningful Distinctions

Number-series naming is not a good way of intentional naming. Such names are non-informative, as they provide no clue of the intention for the author of the code.

Let’s see the following example:
<?php
public function duplicateArray($arr1, &$arr2) {
  foreach ($arr1 as $key => $value) {
    $arr2[$key] = $value;
  }
}
This code would be much better to read when $arr1 and $arr2, would be renamed to$source and $destination.

Use Names You Can Pronounce

If you can’t pronounce a name, you can’t discuss it without sounding like an idiot. This actually matters, because a part of programming is social activity. There’s a good chance everybody knows a variable name off the top of their head that they can’t pronounce.

Let’s pretend we have a variable name called $xsq, which is a very important abbreviation for your company. Imagine a conversation with a colleague:

“Hey, what about that variable eks ess kjew?”

“You mean the access queue?”

Some developers will try to pronounce the variable as one word. Others will spell out the word.

Use Searchable Names

Names that consist of one letter have the problem that they can’t be located easily.

The same applies to numeric constants. Numeric constants could be replaced with a constant variable. The number 8 could give you a lot of trouble when you’re searching your code.

Replacing it with a constant MAX_BLOCKS_DISPLAYED makes it a lot easier, however.

The only use case for single-letter names is for local variables inside short methods.

Member Prefixes

Don’t use member prefixes.

Some developers have the habit of prefixing all private members with an underscore, for example. Don’t. Your classes and methods should be small enough that you don’t need any of these prefixes.

As an alternative, you could use an IDE (or install a plugin) which colorizes variables based on their scope.

Think of your code like it is a campground — leave it cleaner than you found it.

Conclusion

This is how you can create more meaningful names in your code.

Feel free to leave a comment if you have any feedback, questions or want me to write about another programming related topic.

This article was inspired by the book Clean Code written by Robert C. Martin, which I highly recommend you read.
下载开源日报APP:https://openingsource.org/2579/
加入我们:https://openingsource.org/about/join/
关注我们:https://openingsource.org/about/love/