Jump to content

Beginner code written better

- - - - -

  • Please log in to reply
12 replies to this topic

#1
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
In 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:

    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:
 if(playerTurn){
Because that does the same thing.

But the betterMethod is:

    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:

    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:

    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:

    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:

    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:

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
sb.reverse();
insert "very" between "a" and "long"
sb.insert(7, "very ");
remove a letter
sb.deleteCharAt(7);
replace a letter
sb.setCharAt(7, 'k');

For 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. :c-smile:

Edited by wim DC, 16 December 2010 - 12:13 AM.


#2
sam_coder

sam_coder

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 372 posts
Great tips!

I'm a .NET guy, but I assume it's the same in Java. Another great reason to use StringBuilders is because they are Mutable.
replacing concatenation operations with Appends to a string builder can significantly improve your operations' performance.

#3
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
Yes, true. But I must say I don't often use it to append Strings, unless it happens in a loop which I know will loop at least 50 times or so.

#4
sam_coder

sam_coder

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 372 posts
This is one of those things that really takes practice. I get what your saying, nobody would do this:

String Concat(String a, String b) {
    StringBuilder sb = new StringBuilder();
    sb.Append(a); sb.Append(b);
    return sb.toString();
} 

But, the point of my point was more a "best practice" than anything else. As we know, "best practices" don't always fit the bill..

in a more realistic sense, if I had a method that say.. generated a complicated SQL query, I'd likely use a string builder. This might be because I call the method often, or that I have several methods that generate queries.
But either way, I'd do it because I know it's less expensive.

Anywho, this was a great article, people should do more best practice typed articles.

#5
syafiq90

syafiq90

    Newbie

  • Members
  • Pip
  • 2 posts
err....sry.can ask u all smthng.actly in java whre can i write all of this code.mean wht kinda of software we use.is it j creator?

#6
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
You need to have a JDK installed (java development kit).Java SE ?? ? Sun ????? (SDN)
You can write Java in any text-editor like notepad. You save your files as .java instead of .txt and then follow this tutorial -->http://forum.codecal...e-jar-file.html

You can make it yourself easier by downloading and installing a decent IDE (integrated development environment) which does a lot of work for you.
Most of them out there are free: netbeans, eclipse, blueJ, IntelliJ community edition.
There you just create a project and you can choose to create java classes which are automatically saved in .java files,
and if you installed the JDK correctly it will propably find it itself and you'll be able to compile and run it basicly by pressing a "play"-button

#7
syafiq90

syafiq90

    Newbie

  • Members
  • Pip
  • 2 posts
can u suggest me which one is better software for beginner like me coz.i just take this java as my new subject in this semester at my college.i realy2 dn't knw about java...

#8
NomNom

NomNom

    Newbie

  • Members
  • Pip
  • 8 posts
I started out with Eclipse and I love it. And I am giving you this information even if you don't really know English grammar/spelling very well.
-NomNom

#9
sam_coder

sam_coder

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 372 posts
I'd second a few of these guys and say Eclipse as well, it's a great product!

download JDK here: Java SE Downloads

and download eclipse here: Eclipse Downloads

#10
NomNom

NomNom

    Newbie

  • Members
  • Pip
  • 8 posts

sam_coder said:

I'd second a few of these guys and say Eclipse as well, it's a great product!

download JDK here: Java SE Downloads

and download eclipse here: Eclipse Downloads

Yeah, uhh, with Eclipse you don't have to download the JDK. Just download the Eclipse standard IDE and you're good to go.
-NomNom

#11
sam_coder

sam_coder

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 372 posts

NomNom said:

Yeah, uhh, with Eclipse you don't have to download the JDK. Just download the Eclipse standard IDE and you're good to go.

thank's, I wasn't aware of that

#12
lethalwire

lethalwire

    while(false){ ... }

  • Members
  • PipPipPipPipPipPipPip
  • 748 posts
  • Programming Language:Java, PHP
  • Learning:Java, PHP
Good tutorial.
I would only change 1 part though.
I would remove Arrays.fill( scores, 0 );
At instantiation, all positions of an int[] array are set to 0.

    private int[] scores;

    private int[] players;


    public void betterMethod(){

        scores = new int[50];

        players = new Player[10];


        [COLOR="Red"]Arrays.fill(scores, 0);[/COLOR] [COLOR="SeaGreen"]// remove this line[/COLOR]

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

    }





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users