Is it possible to write good and understandable co

2019-02-02 15:22发布

Can any one suggest what is the best way to write good code that is understandable without a single line of comments?

标签: comments
20条回答
Animai°情兽
2楼-- · 2019-02-02 15:46

If you really want to then you would need to be very detailed in your variable names and methods names.

But in my opinion, there is no good way to do this. Comments serve a serious purpose in coding, even if you are the only one coding you still sometimes need to be reminded what part of the code you're looking at.

查看更多
甜甜的少女心
3楼-- · 2019-02-02 15:46

If you want to code entirely without comments and still have your code be followable, then you'll have to write a larger number of shorter methods. Methods will have to have descriptive names. Variables will also have to have descriptive names. One common method of doing this is to give variables the name of nouns and to give methods the names of verbal phrases. For example:

account.updateBalance();
child.givePacifier();
int count = question.getAnswerCount();

Use enums liberally. With an enum, you can replace most booleans and integral constants. For example:

public void dumpStackPretty(boolean allThreads) {
    ....
}

public void someMethod() {
    dumpStackPretty(true);
}

vs

public enum WhichThreads { All, NonDaemon, None; }
public void dumpStackPretty(WhichThreads whichThreads) {
    ....
}

public void someMethod() {
    dumpStackPretty(WhichThreads.All);
}
查看更多
▲ chillily
4楼-- · 2019-02-02 15:47

I like to 'humanise' code, so instead of:

if (starColour.red > 200 && starColour.blue > 200 && starColour.green > 200){
   doSomething();
}

I'll do this:

bool starIsBright;
starIsBright = (starColour.red > 200 && starColour.blue > 200 && starColour.green > 200);

if(starIsBright){
   doSomething();
}
查看更多
太酷不给撩
5楼-- · 2019-02-02 15:50

I once had a professor when I was in college tell me that any good code should never need any comments.

Her approach was a combination of very precise logic split out into small functions with very descriptive method/property/variable names. The majority of what she presented was, in fact, extremely readable with no comments. I try to do the same with everything I write...

查看更多
老娘就宠你
6楼-- · 2019-02-02 15:52

I think that the concept of Fluent Interfaces is really a good example of this.

var bob = DB.GetCustomers().FromCountry("USA").WithName("Bob")

查看更多
Deceive 欺骗
7楼-- · 2019-02-02 15:53

Clean Code by Robert C. Martin contains everything you need to write clean, understandable code.

查看更多
登录 后发表回答