I.T. Discussion Community!
-Collapse +Expand
Coder
Search Coder Group:

Advanced
-Collapse +Expand Coder Study Test
PRESTWOODCERTIFIED
-Collapse +Expand Coder Store
PRESTWOODSTORE

Prestwood eMagazine

July Edition
Subscribe now! It's Free!
Enter your email:

   ► KBProgramming   Print This    All Groups  
  From the October 2015 Issue of Prestwood eMag
 
Coder Programming:
Defensive Programming
 
Posted 47 months ago on 8/19/2015
Take Away:

Defensive programming practice.

KB102725

When we write code, we want to ensure quality and that the code endures possible flaws. Let's say we are writing a code that outputs the integers 5 to 1 (C#):

void SomeFunction()

{

    int i=5;

    while (i != 0){

        Console.WriteLine(i);

        i--;

    }             

}

This code will output the numbers  5,4,3,2,1.  When it decrements the 1, it makes i =0 which makes the program flow exit the while loop. What if somehow the program skips the case where i=0 and continues i=-1, i=-2....  This will result in an infinite loop and the program crashes.  As a defensive programming practice, we want to write the code as follows:

void SomeFunction()

{

    int i=5;

    while (i > 0){

        Console.WriteLine(i);

        i--;

    }             

}

This is more certain that the program flow will exit the while loop when i reaches 0 and it will not process any values less than or equal to 0.

 


Comments

0 Comments.
Share a thought or comment...
 
Write a Comment...
...
Sign in...

If you are a member, Sign In. Or, you can Create a Free account now.


Anonymous Post (text-only, no HTML):

Enter your name and security key.

Your Name:
Security key = P1233A1
Enter key:
Article Contributed By Sam.H:
Visit Profile

 KB Article #102725 Counter
3693
Since 8/19/2015
Follow PrestwoodBoards on: 


©1995-2019 PrestwoodBoards  [Security & Privacy]
Professional IT Services: Coding | Websites | Computer Tech