Clean code guidelines

From SIMSTADT
Jump to: navigation, search

One aim of SimStadt project is to deliver a software platform that will be usable, extensible and maintainable after the project has ended. One precondition to achieve this goal is a good knowledge of the tools used for development, especially the programming language. In the next section you'll find some valuable free resources about the Java programming language in general as well as Java 8 and JavaFX in particular.

Good tools are of no help if they are used badly. Therefore, the main part of this page es dedicated to the idea of writing "clean code".

Contents

[edit] Java resources

Many free courses and books about the Java programming language can be found on the web (see the list at https://github.com/vhf/free-programming-books/blob/master/free-programming-books.md#java). The following are worthwhile to look at:

Starting points for Java FX and Java 8 are:

[edit] Clean code

"Even bad code can function. But if code isn't clean, it can bring a development organization to its knees."
— from the book description of Robert C. Martin: "Clean code - A Handbook of Agile Software Craftmanship", 2008

[edit] About clean code

  • Clean code is intuitively comprehensible, that is: it is understandable correctly in short time and with ease
  • Programming not as art (obsession?) or (engineering) science, but professional craftmanship
  • Requires discipline, practice, and principles

A very good and motivating first read in my opinion is: http://blog.pluralsight.com/7-reasons-clean-code-matters

[edit] Some Principles

  • POLS, Principle of Least Surprise
  • DRY, Don’t Repeat Yourself (do not copy any code)
  • YAGNI, You Ain’t Gonna Need It (no programming for the stock)
  • KISS, Keep it small and simple
  • SRP, Single Responsibility Principle aka Separation of Concerns (one class for one purpose, e.g. separate iteration logic from calculation logic)
  • CoC, Convention over Configuration (code formatter)

[edit] Some To Dos

  • Use modifier correctly (final, visibilities)
  • Care of variable scopes, use innermost (POLS)
  • Meaningful names and uniform naming schemas (see special section below)
  • Use most general types for input parameters and most constrained types for output parameters (reusebility)
  • JavaDoc for APIs
  • Comment only code that is not self-explanatory (usually a bad thing!)
  • Use software pattern, but only if appropriate

[edit] Some Don'ts'

  • Don't use deprecated code: Hashtables, Vector, Enumeration (KISS, POLS)
  • No unused variables, parameter und statements (POLS, YAGNI)
  • No programming by copying!! (DRY)
  • Don't mix any features and functions (SRP)


General theme: Express your intentions clearly!


Many more useful tips can be found in this "Clean Code Cheat Sheet": File:Clean-Code-V2.2.pdf
(In there, the topics and rules I find most important in the context of SimStadt are highlighted)

[edit] Java Programming Style Guidelines

"Any fool can write code that a computer can understand.
Good programmers write code that humans can understand."

— Martin Fowler, Refactoring: Improving the Design of Existing Code

Java, like most programming languages, provides many ways to express a specific functionality in code. The main rationale to agree upon and follow some programming style guidelines is that the resulting software is easier to maintain (adding new features, fixing bugs). This is certainly desired for SimStadt, since platform and workflows are developed by a flock of people that also changes over time.

But there is a second rational of great importance, especially for less experienced developers: Learning and following programming guidelines allows developers to concentrate more on programming logic instead of thinking about, say, the right sequence of modifiers, naming schemas, rules for indention, the "best" line length, or when to use a do-while-loop instead of a while-do-loop (simple guideline here is: never).

Since we don't want to invent programming guidelines for SimStadt anew, we stick with this three guides, that I (Kai) find matured and helpful:

  1. http://www.javaranch.com/styleLong.jsp (quite short, makes a good first read)
  2. http://geosoft.no/development/javastyle.html (our reference for SimStadt with some exceptions)
  3. https://google-styleguide.googlecode.com/svn/trunk/javaguide.html (supplements specific topics)

Note, that the once "official" style guideline from Sun/Oracle is not considered, because it is out of date. In what follows, we refer to the guides as JavaRanch guide, Geosoft guide, and Google guide.

The following sections introduce the programming guidelines for SimStadt regarding formatting, naming conventions, coding practices and miscellaneous topics by pointing to specific sections of the above sources. Referencing the GeoSoft recommendations is especially easy, since they are numbered from 1 to 86.

[edit] Formatting

Code formatting is covered in depth in Geosoft guide, section 6, and Google guide, section 4. Luckily, most of the these recommendations are implemented as special SimStadt formatting rules, that you already should have imported into Eclipse as described here: Development_environment#Other_general_settings. Thus, your source code should automatically be reformatted according to the rules each time you save a file.

Please, double check that your Eclipse settings for automatic reformatting are correct. In "Window -> Preferences -> Java -> Editor -> Save Actions", check boxes "Perform the selected actions on save", "Format source code" (format all lines), and, "Organize imports" must all be checked. Ensure that these global settings are not overridden by project settings!

Some highlights

  1. Opposed to Geosoft guide #34, #35, and #61 we use
    • a maximal line length of 120 characters instead of 80
    • tabs for indentation instead of spaces
    • a basic indentation of 3, not 2 characters.
  2. Opposed to Geosoft guide #72, single statement if-else, for or while statements must be written with brackets.
  3. Geosoft guide #75 applies (Logical units within a block should be separated by one blank line), whereas #76 (Methods should be separated by three blank lines) does not.
  4. Except bodies of classes, interfaces and enumerations, braces are formatted according Google guide section 4.1 (no line break before the opening brace, line break after the opening brace, etc.). Thus, JavaRanch guide, section 1.1 ("Matching braces always line up vertically in the same column as their construct") does not apply in general.

Note: Some "clean code" features like point 2 above or removing unnecessary casts can be automatically detected and corrected with Eclipse command "Source -> Clean Up...". Like the formatter, this command takes a special SimStadt profile into account. It is not executed automatically, since it usually requires the programmer to inspect changes in a preview mode. I encourage anyone to try this command upon his or her code.

[edit] Naming conventions

Naming conventions are not enforced by the IDE. Consequently, our code base contains many strange identifiers that make the code hard to read. In SimStadt we follow the recommendations in GoogleGuide, section 5, and Geosoft guide, section 3. They cover many cases, please read them carefully.

Some highlights

  1. All identifiers except of constants and package names are written in "Camel case". Google guide, section 5.3, discusses how to build a correct camel case name, e.g. "new customer ID" translates to newCustomerId and "supports IPv6 in iOS" to supportsIpv6OnIos.
  2. Package name com.example.deepspace is correct, while com.example.deep_space or com.example.deepSpace is not.
  3. Opposed to Geosoft guide #8, but in line with Google guide, section 5.1, no underscores may be used to mark private instance variables.
  4. Constants (static final fields or enumeration constants) are written with capital letters and underscores, like in int MAX_ITERATIONS and enum {ROW_X, ROW_Y, ROW_Z}
  5. Underscores are only used for constants (see above) and possibly for JUnit test methods and variables (see JavaRanch guide, section 2.3.2, and Google guide, section 5.2.3)
  6. Do not use any special suffixes or prefixes to express type information (see Google guide, section 5.1), except for JavaFX variables, e.g. startButton or nameTextField (see Geosoft guide #18)
  7. Common suffixes and prefixes for variables, methods and types are listed in Geosoft guide #14, #20, #21, #26, #27, #28.
  8. Use correct english spelling

[edit] Programming practices

Good programming practices are covered in JavaRanch guide, section 3, Google guide, section 6, and Geosoft guide, parts of section 3. Please have a look.

Some highlights

  1. Declare local variables as close as possible to where they are used. (JavaRanch guide, section 3.3, Geosoft guide #44)
  2. Do not ignore caught exceptions (see Google guide, section 6.2) unless you have a good reason that must be documented in the catch-clause. Otherwise, just leaving a catch block empty or print something to standard out is a bug. Either you can handle the exception sensibly at this point — sometimes by logging it or rethrowing another (Runtime) exception — or you have to propagate the exception to the calling method. If this breaks the calling method, this method has to fixed.
  3. Class variables should never be declared public (Geosoft guide #46)
  4. The use of magic numbers or Strings should be avoided. Numbers other than 0 and 1can be considered declared as named constants instead (see Geosoft guide #57)

[edit] Miscellaneous

Imports

We let Eclipse organize imports automatically on file save, so that imports are sorted nicely and "bulk" imports like import java.util.*; or static import Math.* are replaced by explicit import statements.

Source file structure

Class and Interface declarations should be organized as follows (we use a slightly modified version of Geosoft guide #40 withSimStadt additions in bold):

  1. Class/Interface documentation
  2. class or interface statement
  3. Class (static) variables in the order public, protected, package (no access modifier), private.
  4. Class methods (no specific order)
  5. Instance variables in the order public, protected, package (no access modifier), private.
  6. Constructors
  7. Instance methods (no specific order).

Exactly one top-level type has to exist in any Java source file (Google guide, section 3.4.1)

File encoding

All Java source files are encoded with UTF-8!

Documentation

Tricky code should not be commented but rewritten (Geosoft guide #79, see JavaRanch, section 4, for an example)

Except simple accessor methods, Javadoc has to be added to every public class, and every public or protected member of such a class. (Geosoft guide #86)

Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox