tags:

views:

694

answers:

20

I'm learning Java and I'm wondering what everyone's Java rules are. The rules that you know intrinsically and if you see someone breaking them you try to correct them. Things to keep you out of trouble or help improve things. Things you should never do. Things you should always do. The rules that a beginner would not know.

+2  A: 

Things you should always do.

Read the Java language specification. It pays off hugely if you have some background at least in one other OOP language.

Anonymous
+18  A: 

Read Effective Java by Bloch.

It's exactly what you're asking for, a set of rules for writing really great, idiomatic java code.

Mike Deck
Yes, read that book! Second Edition is out now.
Sébastien RoccaSerra
Yes, that book answers exactly that: 78 rules from one of the designers of the standard java class library.
sk
I make all of our new graduates read this book as their first task when they start working for me. One of the best books on Java I have ever read.
Aidos
+2  A: 

Review the Java API. Especially the util package. There are many libraries in there to do common tasks, and reusing them is a lot better than rolling your own.

Rontologist
+6  A: 

One of mine is to stick with the Sun coding conventions.

Jonas Klemming
+1  A: 

If you find yourself using inheritance instead of composition, you're probably doing it wrong.

Niniki
what exactly is your basis for this statement. seems a bit hand wavy of a declaration for me
shsteimer
Agreed. Some explanation is really necessary for comments like that.
Herms
google "Extends is evil" for a great article describing it.
Bill K
it's a bit more complicated than that...
It's not black-and-white like that. The advice is usually *favour* composition over inheritance. Inheritance is still very useful in many situations.
Dan Dyer
Hence my use of the word "probably." Here's a nice blog entry. http://www.berniecode.com/writing/inheritance/
Niniki
A: 
  1. Use recursion as little as possible. There are uses for recursion, but most of the time a simple loop will do the same job without the overhead created with recursion.

  2. use Generics where possible. Many times a class can be used for an application that you never thought of when it was developed. Generics eases the process of reuse without refactoring.

WolfmanDragon
+4  A: 

Thou shalt document ye code!

  • You must document all code that you write. When you come back and read it 3 months later it is crucial you have left some hints on what the code does.
  • You should not document what the code is doing, as it is right there, in the code.
  • You should, however, document why the code is there. You will have much more benefit of the 'why' comments then the 'what' comments in the long run.
  • If it is hard to document, chances are you have not thought enough about the problem.
jlouis
+7  A: 

OK, brainstorming:

  • Think in classes and objects, not in functions.
  • Avoid empty catch clauses (esp. catch(Throwable t) {})
    • Handle an error, do not ignore it.
    • Handle only the type of exception You want to handle at the place You can handle it.
  • Use Javadoc.
    • Makes You think about what You are doing.
    • Generates documentation while developing.
    • Enables IDEs like Eclipse to show hints while using Your classes and methods.
  • Try using generics and annotations to get used to it.

There are many more, but those where the first that came into my mind.

By the way, if You advance from beginner to expert, You will know when to make exceptions to those rules ;)

Black
+4  A: 

Equality comparisons

When doing an equality comparison, think about whether you want to compare for value equality (do the two objects have the same value) or reference equality (are they the exact same object instance). For reference equality, use the == operator; for value equality, you will generally want to use the .equals() method.

(Note that non-core Java classes may or may not have a meaningful .equals() implementation; most core classes do have a good .equals() implementation.)

For example, a common mistake would be to do (string1 == string2) to try and determine whether the string variables string1 and string2 represent the same string value.

Jon Schneider
+1  A: 

Use and understand the Java Collection Framework.

Use the class ArrayList instead of Vector. Use HashMap instead of Hashtable.

For synchronized access, use the Collections utility class.

Only use Hashtable and Vector if you really must code against some legacy API.

Sypholux
+1  A: 

Use a checked (declared) exception if there is no way to guarantee the exception will not happen, but ensure the exception is documented in the contract (the JavaDoc). Punish the caller with an unchecked (runtime) exception if the caller violated the contract, e.g. passed in a null argument when the contract specified that the argument may not be null.

Gareth
Or avoid checked exceptions for the most part and always use unchecked. Checked exceptions are kind of a failed experiment, if they were recreating Java from scratch, I'm pretty sure they wouldn't have included them. There are libraries to help you convert too.
Bill K
I think checked exceptions are a good thing. The main problem is that they're overused. It would probably have been better to have the default be unchecked instead of checked, but there are situations where checked exceptions are useful.
Herms
+1  A: 

Be liberal in what you accept and specific in what you return.

For example, take a general-purpose method with the following signature:

public void doXY(LinkedList widgets)

With this signature, clients cannot use your general-purpose method with other Lists or even a Set type. An input parameter type can often be broadened to make the method more flexible to use, e. g.:

public void doXY(Collection widgets)

Sypholux
+3  A: 

Never execute time-consuming tasks in the AWT event dispatch thread or you will have a non-responsive GUI.

cgull
+5  A: 

If you repeat yourself, such as by copy and paste, you're doing it wrong. Java is an OO language, use it that way.

If you aren't using design patterns, you are reinventing the wheel. It's amazing how many problems are best solved by the original GOF design patterns. Only after reviewing these should you do something different.

Keep your method names long, your parameter names descriptive, but your methods short. This is a bit subjective, but the more you split things apart, the easier it is to fix and reuse the code. If you can't explain what your method is doing in a sentence, you either have an usually complex problem, or more likely your methods are trying to do too much.

Avoid having each object do too much. Look at the names on your objects. If there are methods in the object that don't relate to the name of the object, move them somewhere where they might belong.

Method overloading is nice, and it can save you from typecasting all over the place.

Try to avoid being "clever" in such a way that makes it more difficult to understand the code you wrote. Use as many built in features of the language (e.g. Iterators) as possible. Do the simplest thing that could possibly work. You will thank yourself later.

Source control is necessary, even if you are one developer working alone. It has saved my neck more times than I can count.

After initial debugging, nothing should be hard coded. For items used across the application, such as environment and related messages, store as many items as possible in the database. If you think these items will never change, use properties files, and a globals java file for things that you are convinced will never change, because they will.

Automatically format your code using your IDE, even if it makes it ugly you are still better off in the long run.

If there is a well known, and reliable framework for something, use it. JSF or Struts will be better than anything you could develop on your own, even if you think your own MVC framework is really cool. The same thing with persistence, use something mainstream. Try to use as few, or one framework, when possible. You might impress your friends to have a Spring, Shale, JSF, Struts project using Hibernate along with some other framework you developed yourself, but it is really just complexity for the sake of complexity.

srclontz
+2  A: 

hi Bob,

always write unit tests as much as possible. There are 2 main unit test frameworks -- junit and TestNG. Each of them has an ecoSystem of other testing extensions. having unit tests gives you confidence. After someone has added new code or modified code, you can find if the system is broken or NOT by running the unit tests all over.

Also, the java community has embraced the Continuous Integration systems. Many of them are open source -- plan on building your software on a regular basis. If you can, deploy it and run Integration tests on them BUT at the least, build and run unit tests regularly.

anjanb
+1  A: 

In my mind the most important things are:

  1. Formatting: I can't understand code with bad format.
  2. Good naming: good naming convention is the first step to good code.
  3. Documentation: always write documentation about what the code is and why it is done this way
  4. Don't repeat code
  5. Make use of the technique mentioned in "effective java". This book provides very useful guideline.
logoin
+1  A: 

A great set of advice!

Let's see, what haven't I seen mentioned..

use lots of small classes. Each class should do one thing well. I've never seen too many classes, virtually always too few.

read the Refactoring book--the section on Bad Code Smells lists a lot of stuff to look out for.

The biggest pointers that you are doing OO wrong is lots of setters and getters, the desire to use a switch statement and a large inheritance tree, but there are many others (Your question wasn't OO, but close enough).

Don't initialize local variables as a matter of habit (String s=null;), otherwise the compiler can't catch this problem:

String s;
if(x == 5)
    s="5";

if(y == 5) 
    s.append("5"); // Compiler will tell you s might not have been assigned
                   // UNLESS your first line was "String s=null"

Learn Javadocs. Just get in the habit of using them, they're not that complicated.

Use Eclipse or NetBeans. Turn up error checking. Pay attention to the errors. Some you may decide aren't important, but many will help.

If you are working in Swing, learn about the event thread--grok it or your GUIs will look like crap.

There are some AMAZING libraries in the SDK. Advanced threading control, Reference classes, NIO and reflection are all missed by many programmers--and that's just scratching the surface.

That said, don't abuse reflection--it can make your code hard to maintain--just know it's there and what it can do.

Don't "Null" out variables to free memory--it's virtually never useful and makes you look like you don't understand Garbage Collection. Even sillier to do it in a finalize method.

Hmm, while we're there--don't use finalize methods. Ever. If you need to clean up an external resource, look up reference classes (WeakReference).

Bill K
A: 
  • Keep your code neat (indentation), with comments and clear variable names. This will help you read/edit your code at a later date. It'll also help others to read your code.

  • Create objects where applicable.

  • Ensure efficiency in your code, don't repeat code (no copy+paste mkay?.

Glitch
A: 

I saw a rather good advice that I try and apply: avoid to initialize class fields to default values.

I still often see:

public class Foo
{
  boolean b = false;
  int n = 0;
  float x = 0.0;
  SomeClass sc = null;
}

and so on.

It is inefficient (although at a minor level) since the JVM have already set the values at variable allocation time, ugly (and distracting the reader from non-default values) and annoying at debugging time (we have to step there at class creation time).

Some people said there are cases where such init is needed, but wasn't unable to present a real case. If somebody has more info here...

PhiLho
A: 

Code Complete by Steven McConnel has many useful tips, not just for programming in Java, but for programming generally.

trilobite