Thursday, May 22, 2008

In Depth Software Development Strategies Tip 3 Conditional Statements

Writen by Graham McCarthy

The third tip in the series is about 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 computer code today.

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 might not be catched, the suggestion put forward was to declare the constant first, and then the variable after.
for example:
if(0 == num) {} , this way if you forget one of the equals, the compiler will catch it.

You can take this step further, by declaring the 0 as a constant:
public final int ZERO = 0;
if(ZERO == num);
This just gives your code that 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 havn't left 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 < SIZE; i++)
_____{
_______System.out.println("number: " + i);
_____}
____doJob();
___} //End Main

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

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.

Graham McCarthy, has 6 years experiance developing software for both educational and business oriented purposes.
Website:
http://concisecoding.blogspot.com/
Certification:
- A College Diploma in Computer Programming Analysis from Fanshawe College in London, Ontario Canada.
- A University Degree in Information Technology /w Honours from York University in Toronto, Ontario Canada.

No comments: