Learning Java/Programming tips

From Wikiversity
Jump to navigation Jump to search

When to use methods[edit]

The ideal method only handles one function, and is named appropriately. Using methods increases readability of your code and makes it easier to expand or change your software. You can also call your methods from separate places, reducing the total number of lines of code. Methods are also used to retrieve data from an object and store data in objects. These methods are called getters and setters. Example:

public class Customer {
   private String firstName;
   private String lastName;

   public String getFirstName() {
      return firstName;
   }

   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }

   public String getLastName() {
      return lastName;
   }

   public void setLastName(String lastName) {
      this.lastName = lastName;
   }
}

Methods are allowed to call other methods, but only if they have a different functions. Try using common sense when deciding whether use methods or not. There are multiple analysis tools to see if you are using methods right and efficiently. You should avoid having methods with a lot of lines of code, it often (but not always) indicates that the method can be broken up in smaller methods.

About Arrays[edit]

Arrays should be used for variables that have something to do with each other. Basically, arrays are a sets of variables, and arrays are a variable themselves.
Here are some examples which declare arrays.

int[] var; // declares an array of ints
String[] stringArray; // declares an array of Strings
Object[] objArray; // declares an array of Objects

Simply declaring an array in this way does not allocate space for the elements of the array. Declaring the array with a list of elements will also allocate the space for the elements and assign their values.

int[] intArray = {0, 1, 2, 3}; // declare an array of ints with 4 assigned elements

To create an array one must use the new operator and specify the length of the array.

var = new var[8]; // instantiate the array with 8 elements
//Put into one statement
int[] myInts = new int[22]; // declare a new array and instantiate it with 22 elements;

Each array has an int member called length. It is simply how many items are in the array.

int myCount = myInts.length; // assign the size of an array to a variable

You need to initialize each part of the array. To "access" the members of the array:

myInts[2] = 3;
int var = myInts[2];

Note: Do NOT use arrays when the members have nothing to do with each other. This causes code errors!

Basic Tips for Improving Code[edit]

Code formatting[edit]

Code formatting is necessary to understand your code more easily. For example, the following is very hard to understand because it is not properly formatted:

public
class MessyCoding extends Coding {public
static void main(String
args[]
){System.out.println
("This is messy coding. Don't do this");System.exit(0);}}

In much better format:

public class CleanCoding extends Coding {
   public static void main(String args[])
   {
      System.out.println("This is clean coding. DO THIS!!");
      System.exit(0);
   }
}

Notice that the code is easier to understand. Every single new block that has { and } should have whitespace preceding it. Example:

public class CleanCoding extends Coding {
   public static void main(String args[])
   {
      try{
         try{
             ...;
         }
         ...;
      }
      ...;
   }
   ...;
}

To further improve the readability of your code, you should insert one empty line between methods:

public void method1()
{

}

A good alternative is:

public void method2() {

}

You should make a new line after every statement/declaration. If a statement is too long, you can break it down.

Some Integrated Development Environments like Netbeans IDE have an auto-formatting function built in.

Good Comments[edit]

Good comments can help make your code look neat. They should tell what you are doing overall, not what you are doing on each line. For example, you can comment an if statement if it is complex, but not every statement has to be commented:

// tests for parity, sign, and size
if( x%2 == 0 && x > 0 && x < 1000 ) {
System.out.println("x is a positive, even, integer less than 1000");

    if( x%3 == 0 ) // tests if divisible by 3
        x++;
}

An example of bad commenting would be:

if( i1 == i2 | i1 == i3 ) // Check if i1 is equal to i2 and i3
{
   System.out.println( "YES!" ); // Print Yes! to the command line
   i1= i1 + 1; // Add 1 to i1
}

Quick way to convert numbers to strings[edit]

There will be a lot of times you need a String and you're working with numbers. This is one of the faster ways to convert numbers to String, but it's not very neat.

int a = 5;
double b = 3;

String aAsString = "" + a;
String bAsString = "" + b;

or

String aAsString = String.valueOf(a);
String bAsString = String.valueOf(b);
 
or

String aAsString = Integer.toString(a);
String bAsString = Double.toString(b);

Getting numbers from strings[edit]

When you need to extract numbers from a string you can use the Wrapper classes to parse them into the number you need.

 String stringInt = "153";
 String stringDouble = "56.324";
 
 int myInt = Integer.parseInt(stringInt);
 double myDouble = Double.parseDouble(stringDouble);



Project: Java
Previous: Important Java Classes — Learning Java/Programming tips — Next: Fundamental Exercises