What are your Java rules?

I am learning Java, and I wonder what all the rules of Java are. Rules that you know in essence, and if you see someone breaking them, you are trying to fix them. Things to keep you out of trouble or to help improve the situation. Things you should never do. Things you should always do. Rules that a beginner would not know.

+6
java
source share
22 answers

Read Effective Java from Flea.

This is exactly what you are asking for, a set of rules for writing really wonderful, idiomatic Java code.

+20
source share

OK, brainstorming:

  • Think in classes and objects, not in functions.
  • Avoid empty catch clauses (especially catch (Throwable t) {} )
    • Handle the error, do not ignore it.
    • Only handle the type of exception. You want to process where you can process it.
  • Use Javadoc.
    • Makes you think about what you are doing.
    • Generates documentation during development.
    • Allows an IDE, such as Eclipse, to display hints when using your classes and methods.
  • Try using generics and annotations to get used to it.

There are many more, but those where the first thing that occurred to me.

By the way, if you are moving from a beginner to an expert, you will know when to make exceptions to these rules;)

+8
source share

One of mine is to stick to the Sun Coding Agreement .

+7
source share

If you repeat yourself, for example, by copying and pasting, you are doing it wrong. Java is an OO language, use it that way.

If you do not use design patterns, you reinvent the wheel. It's amazing how many problems are best solved by the original GOF design templates. Only after reviewing them should you do something else.

Keep method names long, your parameter names are described, but your methods are short. This is a bit subjective, but the more you separate things, the easier it is to fix and reuse the code. If you cannot explain what your method does in the sentence, you either have a usually difficult problem, or most likely your methods are trying to do too much.

Avoid every object doing too much. Look at the names on your objects. If there are methods in the object that are not related to the name of the object, move them somewhere where they may belong.

Method overloading is good, and it can save you from typing all over the place.

Try to avoid being smart in a way that makes it hard to understand the code you wrote. Use as many built-in language features as possible (for example, iterators). Do the simplest thing that could work. You will thank yourself later.

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

After the initial debugging, nothing should be hardcoded. For items used in the application, such as the environment and related messages, store as many items as possible in the database. If you think that these elements will never change, use property files, and the Java globals file for things that you are sure will never change, because they will.

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

If there is a well-known and reliable foundation for something, use it. JSF or Struts will be better than anything you could develop yourself, even if you think your own MVC environment is really cool. The same thing with perseverance, use something basic. If possible, use as little as possible or one structure. You could impress your friends to have a Spring, Shale, JSF, Struts project using Hibernate along with some other structures you developed yourself, but it's really just complexity for the sake of complexity.

+6
source share

You must specify the code!

  • You must document all the code you write. When you come back and read it after 3 months, it is important that you leave some clues about what the code is doing.
  • You should not document what the code does as it is in the code.
  • You must, however, document why the code exists. You will have much more benefit from why comments, and then what comments in the end.
  • If it is difficult to document, most likely you have not thought enough about the problem.
+5
source share

Equality Comparison

When matching equality, consider whether you want to compare for equality of values ​​(both objects have the same value) or reference equality (whether they are an exact instance of the object). For reference equality, use the == operator; for equality of values, you usually want to use the .equals() method.

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

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

+5
source share

Never perform time-consuming tasks in the AWT event dispatch thread or you will have an unresponsive GUI.

+5
source share

Things you should always do.

Read the Java language specification. It pays off very much if you have a background in at least one other OOP language.

+3
source share

Check out the Java API. A particularly useful package. There are many libraries for common tasks, and reusing them is much better than porting your own.

+3
source share

Use the checked exception (declared) if there is no way to ensure that the exception does not occur, but make sure that the exception is documented in the contract (JavaDoc). Punishing the caller with an unchecked (runtime) exception if the caller violated the contract, for example. passed in a null argument when the contract indicated that the argument may not be null.

+3
source share

always record unit tests as much as possible. There are 2 main unit test frameworks - junit and TestNG. Each of them has an ecoSystem of other test extensions. with unit tests gives you confidence. After someone has added new code or changed code, you may find that the system is broken or NOT by running all the unit tests.

In addition, the java community has embraced continuous integration systems. Many of them - open source - plan to build your software on a regular basis. If you can, deploy it and run integration tests with them, but at least regularly create and run unit tests.

+3
source share

If you use inheritance instead of composition , you are probably mistaken.

+2
source share

Using and understanding the Java Collection Framework.

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

For synchronized access, use the Collections utility class.

Use only Hashtable and Vector if you really need to code some legacy APIs.

+2
source share

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

For example, take a generic method with the following signature:

public void doXY(LinkedList widgets)

With this signature, clients cannot use your general-purpose method with other types of Lists or even Set . The type of input parameter can often be expanded to make the method more flexible for use, for example. g :.

public void doXY(Collection widgets)

+2
source share

In my opinion, the most important things:

  • Formatting: I cannot understand code with a bad format.
  • Good name: A good naming convention is the first step to good code.
  • Documentation: Always write documentation about what code is and why it is done this way.
  • Do not repeat the code
  • Use the technique specified in "effective java". This book contains very helpful suggestions.
+2
source share

Great tip!

Let's see what I have not seen.

use many small classes. Each class should do well. I have never seen too many classes, almost always too few.

read the refactoring book - the section on Bad Code Smells lists many of the materials you need to look for.

The biggest pointers that you are doing OO wrong are the many setters and getters, the desire to use the switch statement and the large inheritance tree, but there are many others (your question was not OO, but close enough).

Do not initialize local variables out of habit (String s = null;), otherwise the compiler will not be able to 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" 

Explore Javadocs. Just getting used to their use, they are not so complicated.

Use Eclipse or NetBeans. Turn on error checking. Pay attention to errors. Some that you can decide are not important, but many will help.

If you work in Swing, you will learn about the flow of events - grok it or your GUIs will look like crap.

There are several AMAZING libraries in the SDK. Advanced flow control, reference classes, NIO and reflection are overlooked by many programmers - and it just scratches the surface.

However, do not abuse your thoughts - this can make your code difficult to maintain - just know it there and what it can do.

Do not free unnecessary variables in free memory - this is almost never useful and makes you look like you do not understand garbage collection. It is even more stupid to do this in the finalization method.

Hmm, while we are there, we don’t use finalization methods. Ever. If you need to clear an external resource, find the reference classes (WeakReference).

+2
source share
  • Keep your code neat (indented), with comments and clean variable names. This will help you read / change your code later. It will also help others read your code.

  • Create objects where possible.

  • Ensure code efficiency, do not repeat the code (do not copy + paste mkay ?.

+2
source share
  • Use recursion as little as possible. There is use for recursion, but most of the time a simple loop will do the same job without the overhead created with recursion.

  • Use Generics where possible. Many times, a class can be used for an application that you never thought of when it was developed. Generics makes reuse easy without refactoring.

+1
source share

I saw some pretty good advice I'm trying to apply: avoid initializing class fields by default.

I still often see:

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

etc.

It is inefficient (albeit at a secondary level), since the JVM has already set the values ​​at variable distribution times, is ugly (and distracts the reader from values ​​other than the default values), and annoys debugging time (we should take a step to create the class there).

Some people say that there are cases when such an init is necessary, but could not imagine a real case. If anyone has more info here ...

+1
source share

Steven McConnel's Code Complete provides many useful tips, not just for Java programming, but for programming in general.

+1
source share
  • Always use self-evident names for properties and methods .

  • Comment only when necessary.

+1
source share

Another good book on this issue is Robert C. Martins Clear Code .

It contains general coding rules and recommendations for java, but most of them can be applied to other languages.

I think the developer who reads this book creates much more readable and maintainable code.

+1
source share

All Articles