Note: Java Coding Guidelines

This book has nothing to do with coding style guide. It offers advices of writing secure, reliable, high quality Java by looking at both coding and design aspects of building Java project.

Chapter 1: Security
I’d say most content on Security and Privilege management is not familiar to ordinary Java coders. Although we are not going to use those classes and configuration directly for the majority of Java projects on the planet, it is beneficial to know how Java manages security context in the face of many daily operations: file I/O, LDAP look up, loading classes, etc. A few practical lessons are learned:

  • Literally limit the lifetime of sensitive data – “around” validate code only and erase completely afterwards with no buffering and trace what so ever.
  • Use cookie without sensitive data and perform validate with secret on server side.
  • Wrap sensitive mutable class with immutable wrapper – embrace immutability.
  • Validate anything from inside and outside, and format generated content before output.
  • Do not trust equals, clone and all the overridable methods from untrusted code. Make your class final to avoid this.
  • Use hash with salt to store password

Chapter 2: Defensive Programming

  • Limit the scope of variable and @SuppressWarnings and accessibility of classes/methods
  • Always let methods provide feed back from return values and exceptions
  • Identify file using multiple attributes instead of just path, e.g. time
  • Beware of numeric promotion!
  • Public final fields are cached in compiled file, change in later version may not be seen by library users

Chapter 3: Reliability

Reliability – the capacity to maintain a level of performance when used under specified conditions. The faults in requirement, design and implementation introduce failures. A few lessons learned:

Encode relationship between constant definitions

Use try-with-resources

Handle runtime error gracefully instead of using assertions

Do not serialise handles to system resource – use transient

Direct buffer creation is expensive. Use direct buffer for long lived, frequently used objects.

Remove short-lived objects from long-lived containers – null them or reference to a special singleton NULL object


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s