A tip for cleaner Java code

Our latest Java tip shows you how to make your code a little less confusing.

It's time for another Builder member-submitted Java tip of the week. This week's winning tip, on keeping source code clean and easily readable, comes from member Jon Hermiz.

Keep your objects separated
A good way to keep objects distinguishable in an application is to make sure you keep the actual class implementation of your objects separate from your main program—the class with a main() method. Creating one class for one purpose and then tacking on a main() method to that class can make finding the entry point of your application very confusing.

The main() method should instead be encapsulated into one class by itself, and any objects that main will use should be in their own classes. For example, an application that uses a Queue should look like Listing A.

I'm not saying that it would be incorrect to create a single class with a main() method along with the Queue's implementation. I'm merely saying that it's easier for other developers to understand that class Queue is just that, a Queue, and nothing else, if you keep your code separate.


Editor's Picks