Writing good Java code

You've got enough Java syntax under your belt to write basic Java programs, which means that the first half of this tutorial is about to conclude. This final section lays out a few best practices that can help you write cleaner, more maintainable Java code.

Keep classes small

You created a few classes in this tutorial. After generating getter/setter pairs for even the small number (by the standards of a real-world Java class) of attributes, the Person class has 150 lines of code. This is a small class. It's not uncommon to see classes with 50 or 100 methods and a thousand lines of source (or more). The key point for methods is to keep just the ones you need. If you need several helper methods that do essentially the same thing but take different parameters (such as the printAudit() method), that's a fine choice. Just be sure to limit the list of methods to what you need, and no more.
In general, classes represent some conceptual entity in your application, and their size should reflect only the functionality to do whatever that entity needs to do. They should stay tightly focused to do a small number of things and do them well.

Name methods carefully

A good coding pattern when it comes to method names is the intention-revealing method-names pattern. This pattern is easiest to understand with a simple example. Which of the following method names is easier to decipher at a glance?
  • a()
  • computeInterest()
The answer should be obvious, yet for some reason, programmers have a tendency to give methods (and variables, for that matter) small, abbreviated names. Certainly, a ridiculously long name can be inconvenient, but a name that conveys what a method does needn't be ridiculously long. Six months after you write a bunch of code, you might not remember what you meant to do with a method called compInt(), but it's obvious that a method called computeInterest(), well, probably computes interest.

Keep methods small

Small methods are just as preferable as small classes, and for similar reasons. One idiom I try to follow is to keep the size of a method to one page as I look at it on my screen. This makes my application classes more maintainable.
If a method grows beyond one page, I refactor it. Refactoring is changing the design of existing code without changing its results. Eclipse has a wonderful set of refactoring tools. Usually a long method contains subgroups of functionality bunched together. Take this functionality and move it to another method (naming it accordingly) and pass in parameters as needed.
Limit each method to a single job. I've found that a method doing only one thing well doesn't usually take more than about 30 lines of code.

Use comments

Please, use comments. The people who follow along behind you (or even you, yourself, six months down the road) will thank you. You might have heard the old adage Well-written code is self-documenting, so who needs comments? I'll give you two reasons why this adage is false:
  • Most code is not well written.
  • Your code probably isn't as well written as you'd like to think.
So, comment your code. Period.

Use a consistent style

Coding style is a matter of personal preference, but I advise you to use standard Java syntax for braces:
1
2
public static void main(String[] args) {
}
Don't use this style:
1
2
3
public static void main(String[] args)
{
}
Or this one:
1
2
3
public static void main(String[] args)
  {
  }
Why? Well, it's standard, so most code you run across (as in, code you didn't write, but might be paid to maintain) will most likely be written that way. Having said that, Eclipse does allow you to define code styles and format your code any way you like. The main thing is that you pick a style and stick with it.

Use built-in logging

Before Java 1.4 introduced built-in logging, the canonical way to find out what your program was doing was to make a system call like this one:
1
2
3
4
5
6
public void someMethod() {
  // Do some stuff...
  // Now tell all about it
  System.out.println("Telling you all about it:");
  // Etc...
}
The Java language's built-in logging facility (refer back to "Your first Java object") is a better alternative. I never use System.out.println() in my code, and I suggest you don't use it either. Another alternative is the commonly used log4j replacement library, part of the Apache umbrella project.

In the footsteps of Fowler

The best book in the industry (in my opinion, and I'm not alone) is Refactoring: Improving the Design of Existing Code by Martin Fowler et al. This book is even fun to read. The authors talk about "code smells" that beg for refactoring, and they go into great detail about the various techniques for fixing them.
Refactoring and the ability to write test-first code are the most important skills for new programmers to learn. If everybody were good at both, it would revolutionize the industry. If you become good at both, you will ultimately produce cleaner code and more-functional applications than many of your peers.
Share on Google Plus

About M

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.

0 comments:

Post a Comment