LostGamerz
Java Beginner code written better 1296785282
LostGamerz
Java Beginner code written better 1296785282
LostGamerz
Would you like to react to this message? Create an account in a few clicks or log in to continue.



 
HomePinoy VendeTaLatest imagesRegisterLog in

 

 Java Beginner code written better

Go down 
AuthorMessage
Crowd™
Administrator
Administrator
Crowd™


Join date : 31/01/2011
LostPoints : 10383
Thanks & Rep : 28
Posts : 229
Age : 33
Location : 6ret
Warning Level : Java Beginner code written better WarningBar-Gloss1

Java Beginner code written better Empty
PostSubject: Java Beginner code written better   Java Beginner code written better Icon_minitimeFri Aug 03, 2012 10:18 pm

n fact this is no tutorial as I won't show you how to build a program or accomplish a predefined result.
This will just be a (short) list of code, that works, but could be written shorter and looks better.

This "tutorial" is aimed at the very new Java coders as I think that most people who do Java for a while will have figured this out by themselves.
Each part consists of 2 code-blocks. 1 with "someMethod()" containing the code a beginner might write.
Then the 2nd code-block with a "betterMethod()" containing the shorter/cleaner code.


Changing a boolean to true or false depending on its current value.
How it COULD be written:

Code:
 private boolean playerTurn;
   
    public void someMethod(){
        if(playerTurn == true){
            playerTurn = false;
        } else {
            playerTurn = false;
        }
    }

Better it would be when the if-statement was rewritten like:

Code:
 if(playerTurn){

Because that does the same thing.

But the betterMethod is:

Code:
 private boolean playerTurn;
   
    public void betterMethod(){
        playerTurn = !playerTurn
    }

So playerTurn is Not playerTurn. True becomes not true => false, and false becomes not false => true.


Strings that could be null but you need to use equal
First of all you should try to initialise your Strings with an emptry String if it shouldn't contain anything.
That way you won't encounter NullpointerExceptions there. If for whatever reason you could get nullStrings, you may write:

Code:
 private String possiblyNull;

    public void someMethod(){
        if(possiblyNull != null){
            if(possiblyNull.equals("good")){
                System.out.println("The string is ok.");
            } else {
                System.out.println("The string is not ok.");
            }
        } else {
            System.out.println("The string is not ok.");
        }
    }

You can't do possiblyNull.equals("good") Before checking for null because if the String turns out to be null, an exception will be thrown.
This method totally works fine. It's just bad that you have to write System.out.println("The string is not ok."); 2 times.
...And the method is quite large for the amount of stuff it's really doing.
This can better be written as:

Code:
 private String possiblyNull;

    public void betterMethod(){
        if("good".equals(possiblyNull)){
            System.out.println("The String is ok");
        } else {
            System.out.println("The String is not ok");
        }
    }

Unless you need to treat a null differently, the you have no choice but the first method.
By turning the statement around, possiblyNull can be null without causing the program to crash.
"good".equals(null) Will just return false.


Arrays of whatever and filling it.
Believe me you will not be the first one to fall for this..."mistake". I too did this for a very long time. Imagine if you have to keep 50 scores in your program, so you create an array of 50 integers.
And you also have to store 10 players, so you have another player array.
Both arrays should be filled at the start. the scores with 0 and the players with "new Player()".

You may write it as:

Code:
private int[] scores;
    private int[] players;

    public void someMethod(){
        scores = new int[50];
        players = new Player[10];
       
        for(int i=0 ; i<scores.length ; i++){
            scores[i]=0;
        }
        for(int i=0 ; i<players.length ; i++){
            players[i]=new Player();
        }
    }

Again nothing wrong with it, I did it for over a year like that.
But actually that can be much shorter with the use of the Arrays class:

Code:
  private int[] scores;
    private int[] players;

    public void betterMethod(){
        scores = new int[50];
        players = new Player[10];

        Arrays.fill(players, new Player());
    }

int types have a 0 in them by default so you shouldn't have to do anything for that.
And that's it, the Arrays class does the work for you. You may need to import java.util.Arrays; if the compiler is complaining. Arrays also contains methods for sorting, changing an array in a List and other useful methods.
The Collections class has pretty much the same methods but for Collections.


Know the StringBuilder
This won't be with someMethod and betterMethod. I just want to let you know the StringBuilder class.
Because when you start learning java, Strings are used A LOT. Your teacher propably wants you to make stuff with the console as your "GUI". --> String based propably.
It won't be the first teacher that gives you the assignment to do stuff with Strings like
put a character in the middle of the String. word.substring(0,i) + "inTheMiddle" + word.subString(i, word.length());
Reverse the string (teacher now thinks: "Oh that will involve some nice looping, let's make the students think hard")
Remove certain letters in the String.

Unfortunately the String class is, relatively, limited in its functionallity. Luckily there is the StringBuilder class which has a good amount of very useful methods you can use to change a String.
It's created like so:

Code:
String sentence = "What a long sentence.";
StringBuilder sb = new StringBuilder(sentence );

Then you can do all the things you want to do with the String with the StringBuilder:
reverse
Code:
sb.reverse();

insert "very" between "a" and "long"
Code:
sb.insert(7, "very ");

remove a letter
Code:
sb.deleteCharAt(7);

[color=red]replace a letter[/color]
Code:
sb.setCharAt(7, 'k');

or all this stuff, without the StringBuilder, you were looping or messing with subStrings. This is just much easier.
To get a normal String from the StringBuilder you just call the .toString() method on it, and it will return the String it currently has.


That'll be it for now, thanks for reading.
I hope you learned something new here.
Back to top Go down
https://pinoyvendetta.forumtl.com
 
Java Beginner code written better
Back to top 
Page 1 of 1
 Similar topics
-
» Beginner Java: Displaying a 2D background
» Java guides and basic tutorials

Permissions in this forum:You cannot reply to topics in this forum
LostGamerz :: Guides, eBooks, Tutorials and Tools Zone :: Tutorials and Guides-
Jump to: