Good Java Style: Part 1
2008-01-05 09:02:59 来源:WEB开发网核心提示:Good java Style: Part 1By Thornton Rose IntrodUCtionHaving worked as a software developer and consultant for many years, I have seen a large amount of code in a
Good java Style: Part 1
By Thornton Rose
IntrodUCtion
Having worked as a software developer and consultant for many years, I have seen a large amount of code in a variety of PRogramming languages. It has run the gamut from elegant to ugly, and unfortunately much of it has been ugly. I hope to persuade you, and my fellow developers, that we should give as much attention to the style of our code as we give to the user interface and other visible parts of an application. In this the first part of a two part series, I eXPlain why we should care about how our code looks and illustrate some general elements of good Java style.
Why Style Matters
Even though Java is used to write programs rather than prose, it is still used to express thoughts and ideas. And, in addition to conveying information, those thoughts and ideas must actually do something. Worrying about good style may seem like a waste of time, but it behooves us to write our code such that the thoughts and ideas it expresses are exceptionally clear.
Here are several reasons for using good style [from "Java Code Conventions," Sun Microsystems]:
80% of the lifetime cost of a software product goes to maintenance.
Hardly any software is maintained for its whole life by the original author(s).
Using good style improves the maintainability of software code.
If the source code is shipped with the software, it should be as well-packaged, clean, and professional as the rest of the product.
Writing code with good style also provides the following benefits:
It improves the readability, consistency, and homogeneity of the code, which makes it easier to understand and maintain.
It makes the code easier to trace and debug, because it's clear and consistent.
It allows you to continue more easily where you or another programmer stopped, particularly after a long period of time.
It increases the benefit of code walkthroughs, because the participants can focus more on what the code is doing.
General Guidelines
Writing Java with good style is not hard, but it does require attention to detail. Here are some general guidelines to follow:
Make the code clear and easy to read.
Make the code consistent.
Use obvious identifier names.
Logically organize your files and classes.
Have only one class per file (not including inner classes).
Use a maximum line width of 80-90 characters.
Use whitespace and/or other separators judiciously.
Use spaces instead of tabs for indentation.
[]
更多精彩
赞助商链接