Read "Code neat way"

The principle is named

1, a veritable

In fact, very simple, is the code name you can tell the reader why it exists, it do something, how should use. The book also added that, if the name needs to be supplemented comment, it is not worthy of the name. But I think this is definitely a bit. But energy on behalf of its raison d'etre named after is very important.

E.g

int d; //消逝的时间
int daysSinceCreation;]]></ac:plain-text-body>

The above two, there is obviously the first question, because without a defined place, behind who can not read this "d" is used to do

2, to avoid misleading

To avoid the use of the name you would or could hide clues error codes intended meaning.

E.g

1) Do not use abbreviations to represent proper nouns own variables (I feel good unless the project agreement, otherwise do not use any abbreviations. Of course, with the exception of some widely used, for example, URL)

2) Do not type in the variable name with them, even if it is this type. For example accountList to represent a group account list is bad, directly or accountGroup accounts are good (think of themselves often use similar XXXArray ... .. the future will be correct)

3) Do not name appears little difference, naming and long situations, such as XYZControllerForEfficientHandlingOfStrings with XYZControllerForEfficientStorageOfStrings so .... Who can see it at first glance these are two different variables? ! (I think the name is so long and boring ... very good. Although there is code completion and do not waste time, but read this code is like watching the same sentence tired ah ... named or to dapper good)

4) Do not uppercase or lowercase l O like named, and it is easy to confuse the numbers 1 and 0

3, do meaningful distinction

Because the two things the same name can not appear in the same scope, so we do distinguish in a series of code time to have a certain sense, otherwise people of undetermined significance

1) with a numerical suffix to distinguish between acts very immature ... ..a1, a2, a3 ... Who knows what that distinction is doing?

public static void copyChars(char a1[], char a2[]){
    for (int i = 0; i < a1.length(); i++) {
        a2[i] = a1[i];
    }
}

For example, the above first glance this is a bit of undetermined significance, such as the a1, a2 and destinationChars like a lot into sourceChars

2) distinguish when not to use what ... what synonyms such as ProductInfo and ProductData ...

What is similar

getActiveAccount();
getActiveAccounts();
getActiveAccountInfo();

These three very strange, okay?

4, read out the name

Named the time to use can easily read out the name, cite an extreme example of the book

genymdhms (but I think this is simply a variable named frenzied, more than a violation of this right)

Its practical significance is to generate date as the date when the minutes and seconds

generate year month day hour minute seconds

Change

generateTimestamp to clear out

5, using the name searchable

Named not too short too often, or do not have a long unified prefix, or on a global search for a name when you will find too many results to be meaningful search.

6, to avoid using encoding

Before seen students doing windows programming, naming is the Hungarian notation, meaning completely unknown okay? Anyway, remember named by law hump like ...

7, to avoid thinking maps

Named in many cases do not run counter to the general public with it, for example, most people are accustomed to using a single letter i, j, k as the index cycle, do not use any other single letter of the strange (I think the use of index, idx like it is also harmless ...), but note that, in addition to this case, most of the other cases generally do not have to name the single letter, as to why, see Article!

Summed up in five words: clear is king

8, class names, method names

Object class name is usually named after a noun or noun phrase: Customer, WikiPage, Account, AddressParser, PageDao like

Method names should be a verb or verb phrase: postPayment, deletePage, insertAccount, saveChange and the like, as well as the Java standard, in front of the setter and getter a variable with the set and get, or is identified

9, other

Several feeling more or less behind the front and repeat, anyway, to be named dapper, meaning clear, take the word norms, standards consistent with the public

Second, the function

Function is a very important part of the program is full of function, so named specification and implementation of a function is crucial drops

1, short

The first rule function is short, because the second rule because the function, the function logic should be simple and clear, if you write too long, then, readability on the poor, and very prone to error, the error is not easy to locate misplaced where they are. If a function has to write very long, we try to split into different functions. The authors suggest a function twenty lines capped at best.

2, only one thing

To determine whether the function to do more than one thing, there is a method to determine whether they can be split out a function.

3, each function a level of abstraction

To ensure that the function of only one thing, it should be a function of the statement on the same level of abstraction. Code should be allowed to have a top-down reading order: We want to follow behind each function is located in function to the next level of abstraction. As a result, when viewing a list of functions, you can read in accordance with the level of abstraction down.

Level of abstraction where my understanding is that such a function is used to organize than a series of small features to achieve a large function, then the previous code called a subroutine located behind the code logically, to ensure that a process of feeling it.

4, switch statements

The switch statement because of their unique, write a short switch statement is very difficult, because it is inherently tied to do a lot of things.

For example, this piece of code

public Money calculatePay(Employee e)
    throws InvalidEmployeeType
{
    switch(e.getType())
    {
        case COMMISSIONED:
            return calculateCommissionedPay(e);
        case HOURLY:
            return calculateHourlyPay(e);
        case SALARIED:
            return calculateSalariedPay(e);
        default:
            throw new InvalidEmployeeType(e.getType());
    }
}

The code above there are a lot of problems, first of all, it is relatively long, and secondly, if in the future a new type of employee came in after, it is necessary to change the code here, but also becomes longer, it is prone to error. In general, it is contrary to the powers and responsibilities of a single issue (Single Responsibility Principle, SRP) and open closed principle (Open Closed Principle, OCP)

The book gives a solution with the abstract factory way, the Switch statement put under the abstract factory, do not let anyone see the plant using a Switch statement to create an entity for the Employee of the derived class, and a variety of different entities similar methods may be implemented Employee uniform interface with the polymorphism.

Talk is Cheap, Show me the code

public abstract class Employee {
    public abstract boolean isPayDay();
    public abstract Money calculatePay();
    public abstract void deliverPay(Money pay);
}
//------------------以上是抽象类------------------------

public interface EmployeeFactory {
    public Employee makeEmployee(EmployeeRecord r) throws InvalidEmployeeType;
}
//------------------以上为工厂接口-----------------------

public class EmployeeFactoryImp implements EmployeeFactory {
    public Employee makeEmployee(EmployeeRecord r) throws InvalidEmployeeType
    {
        switch(r.getType())
        {
            case COMMISSIONED:
                return new CommissionedEmployee(r);
            case HOURLY:
                return new HourlyEmployee(r);
            case SALARIED:
                return new SalariedEmployee(r);
            default:
                throw new InvalidEmployeeType(r.getType());
        }
    }
}

5, descriptive name

This has been mentioned in the previous chapter named after them

6, function parameters

最理想的参数数量是0,其次为1,尽量避免3及以上的参数。参数传递中<span style="color: rgb(255,0,0);">不应该传入布尔值</span>的参数,传入布尔值的参数,说明这个函数做了不止一件事情。如果标识为true会这样做,如果标识为false会那样做。对于这种情况我们应该把函数拆成两个函数。

E.g

render(true);

Calling function will know why, do not know the true in the end is doing.

Although the stated function can be written as

public void render(Boolean isSuite)]]></ac:plain-text-body>

This looks a little better,

But encountered a Boolean value, or better written two functions

public void renderForSuite();
public void renderForSingleTest();

Secondly

If three or more of the three parameters required, preferably to a class encapsulates. E.g:

Circle makeCircle(double x, double y, double radius);
Circle makeCircle(Point center, double);

7, no side effects

What are the side effects? That function is called once an impact on the global state. For example, a change in the global variable, initialized a class not eliminated, and so when the function ends. Try to keep the situation without side effects, if you have side effects, it is reflected in the realization of the function name of the function in

8, the division instruction for asking

Function either do, or what to answer, the two can not do both, do both will lead to confusion, such as:

public boolean setValue(String key, Object value);]]></ac:plain-text-body>

The above function of the key value, given a key value successful return true, otherwise returns false. But the reason for the failure of diverse key may not exist, may be set unsuccessful. This resulted in undetermined significance


9, an alternative use of exception return error codes

If the error code is returned to the caller requires the following error processing immediately, so that the entire structure of the code can lead to confusion, a lot of space during the error code is determined:

if (deletePage(page) == E_OK) {
    if (registry.deleteReference(page.name) == E_OK) {
        if (configKeys.deleteKey(page.name.makekey()) == E_OK) {
            log.error("page deleted");
        }
        log.error("configKey not deleted");
    }
    log.error("deleteReference from registry failed");
} else {
    log.error("delete failed");
    return E_ERROR;
}
//--------------------以上为错误码方式--------------------

try{
    deletePage(page);
    registry.deleteReference(page.name);
    configKeys.deleteKey(page.name.makekey());
} catch (Exception e) {
    log.error(e.getMessage);
}
//--------------------以上为异常方式--------------------

Abnormal way it is much simpler

Moreover, should try / catch logic alone pulled out, the internal implementation using a separate function to wrap, it will look much better.

public void delete(Page page) {//只与错误处理相关
    try {
        deletePageAndAllReferences(page);
    } catch (Exception e) {
        logError(e);
    }
}

private void deletePageAndAllReferences(Page page) throws Exception {//只与完全删除一个page相关
    deletePage(page);
    registry.deleteReference(page.name);
    configKeys.deleteKey(page.name.makekey());
}

private void logError(Exception e) {
    log.error(e.getMessage());
}

Error handling should not be mixed with other things to do together.

Original: Large column  read "the code clean way."


Guess you like

Origin www.cnblogs.com/petewell/p/11607410.html