Wednesday, November 23, 2005

Tips #3 : Conditional Statements

Today's tip will be really quick, lets talk conditional statements.

A neat suggestion was posted as a comment on my last article, suggesting a really good way to prevent logic errors from creeping into your code. Logic errors being the hardest type of errors to find in your code.

If presented with an if statement:
if(num == 0)
{
//do something.
}

Now, if you forgot to put the double equals in the condition like:
if(num = 0)
{
//Do something
}

An error like that might not be catched, the suggestion put forward was to declare the constant first, and then the variable after like :
if(0 == num) {} , this way if you forget one of the equals, the compiler will be sure to catch it.

You can take this step one further, by declaring the 0 as a constant, like this:
public final int ZERO = 0;
if(ZERO == num);
This just takes your code that 1 extra step to insure good coding practices.

Thank you Jeff, for that great tip!

Lets continue,
Since white space is never compiled into your program, you should never worry about making your code extra readible with space. A lot of the code that I have tested, has been really hard to traverse through because the authors don't leave enough white space between actions, let me demonstrate:

public class MyTestClass{
public final int SIZE = 5;
public static void main(String [] args){
for (int i = 0; i<>
public doJob() {
for (int i=0; i
if (i%2 == 0)
System.out.println("number: " i);}}}

Confused? Frustrated? Good!
Make your code clear to read; the clearer the code, the easier it is to find errors later.
And also dont forget to add comments!

//MyTestClass.java Author: Graham.
//Desc: Prints out numbers, then the even numbers
public class MyTestClass
{
___//Variables
___public final int SIZE = 5;

___//Main Method, prints numbers o - 4, then runs doJob() method
___public static void main(String [] args)
___{
_____for (int i = 0; i (LESS THAN) SIZE; i++)

_____{
_______System.out.println("number: " + i);
_____}
____doJob();
___} //End Main

___public doJob()
___{
_____for (int i=0; i (LESSTHAN) SIZE ; i++

_____{
_______if (i%2 == 0)
_______System.out.println("number: " i);
_____}
___}//End doJob
} //END Class

NOTE: Instead of LESSTHAN you'd obviously put in the symbol, which for some reason Blogger won't let me write.

Now, if I was going to critique my own code here, I would say that the method doJob() is pretty ambiguous, I should have called it countEvenNumbers().

Hope you have found this article useful! Thanks you.

2 Comments:

At 7:03 p.m., November 29, 2005, Anonymous Anonymous said...

Blogger won't let you use the less than symbol because you're allowed to use HTML tags. Use &_l_t (minus the underscores) for less than and &_g_t for greater than.

Friendly hint from the Yellow Dart!

 
At 1:34 a.m., November 30, 2005, Blogger Graham said...

ahhh.. the Yellow Dart Strikes again!!

thanks bud. Appreciated!

 

Post a Comment

<< Home