CSC/ECE 517 Fall 2009/wiki2 4 dn: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
Line 26: Line 26:
== When and why are if-statements error prone? ==
== When and why are if-statements error prone? ==


<h3>When the same condition has to be checked in multiple places</h3>
<h3>Testing:</h3>


Sometimes in a program the same condition may have to be checked in multiple places.
Sometimes in a program the same condition may have to be checked in multiple places.


<pre>
<pre>
if(flag==1)
if(flag is enabled)
{
{
   read a
   read a
}
}
else if(flag==2)
else if(flag is not enabled)
{
{
   read b
   read b
}
}
.......
 
.......
.....
if(flag==1)
.....
 
if(flag is enabled)
{
{
  write a  
  write a  
}
}
else if(flag==2)
else if(flag is not enabled)
{
{
  write b
  write b
}
}
</pre>
</pre>
In the above example, flag is checked multiple times. This scenario can be particularly difficult for testing because the progaram needs to read a and write a or read b and write b. The program should not read a and write b or read b and write a. If the condition needs to be checked more than twice then the testing becomes more comlicated.





Revision as of 20:13, 8 October 2009

A large fraction of the if-statements in o-o programs could be replaced by uses of polymorphism, which would lead to more modular and maintainable programs. Explain why if-statements are error prone if there is any chance that future development may require them to change. Give examples of if-statements that can be replaced by elegant uses of polymorphism, trying to find some useful replacements that are not obvious. Concentrate on polymorphism, not other reasons for avoiding use of ifs.


The If Statement

The if-then statement is the most basic of all the control flow statements. It tells a program to execute a certain section of code only if a particular test evaluates to true.

if (operator = "+")
{
  result = a+b
}
else if(operator = "-")
{
  result = a-b
}
else if(operator = "*")
{
  result = a*b
}
.....


When and why are if-statements error prone?

Testing:

Sometimes in a program the same condition may have to be checked in multiple places.

if(flag is enabled)
{
  read a
}
else if(flag is not enabled)
{
  read b
}

.....
.....

if(flag is enabled)
{
 write a 
}
else if(flag is not enabled)
{
 write b
}

In the above example, flag is checked multiple times. This scenario can be particularly difficult for testing because the progaram needs to read a and write a or read b and write b. The program should not read a and write b or read b and write a. If the condition needs to be checked more than twice then the testing becomes more comlicated.




Polymorphism

In object-oriented programming, polymorphism refers to a programming language's ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes.