Coding

xiaoxiao2021-03-06  84

SIMPLICITY

Just getting code to work is not good enough, because the first solution you come up with is hardly ever the simplest possible solution. Your methods may be too long, which makes them harder to test. You may have duplicated functionality, or you may have tightly coupled classes. Complex code is hard to understand and hard to modify, because every little change may break something else in the system. As a system grows, complexity can become overwhelming to the point where your only remaining option is to start over.

.

Simple code is self-documenting because you pick meaningful names, your methods are concise, and your classes have clearly defined responsibilities. Simple code is hard to achieve, and relies on knowledge in the areas of object-oriented programming, design patterns, and other Facets of software engineering.

Comments

If code is self-documenting, do you need source code comments? In short, there will always be cases where you need comments, but you should never write comments simply for the sake of commenting. If the meaning of a method is completely obvious, you do not need a comment. An abundance of comments in code is often an indication that the code is unclear and in need of refactoring. Let's look at a method that needs a comment, and see how to eliminate this need.

/ **

* Sets the value of x.

* @Param x the horizontal position in pixels.

* /

Public void setx (int x) {

THIS.X = x;

}

This method needs a comment because the meaning of "x" is not entirely clear. Over time, the comment might not be kept in sync if someone changes the method's implementation or signature. But what if we rename things to make the code more clear? How About this: public void setxpixelposition (int xpixelposition) {

THIS.XPIXELPSITION = XpixelPosition;

}

This code no longer needs a comment because it is self-documenting. As a result, we end up typing a little bit more for the method declaration, but save a few lines of comments. This helps us out in the long run because we don 'T Have to Spend Time and Effort Keeping The Comment in Sync with the code.

References: Java Extreme Programming Cookbook. O'Reilly

转载请注明原文地址:https://www.9cbs.com/read-124042.html

New Post(0)