Conditional Assignments

Many programs require implementing some code which assigns values to variables based on certain conditions. Here is an example:

if( a < 5 )
   b = 3;
   b = 8;

The same in abbreviated form (Java):

b = ( a < 5 ) ? 3 : 8;

In most cases there is nothing wrong about such code. However, let’s have a look at this:

if( a == true )
   b = false;
   b = true;

It is easy to see that the code above can be replaced by the following simple statement.

b = !a;

Whenever there is a simple mathematical dependency between the variable used in the condition and the value to be assigned, you should express this dependency mathematically. So never do something like this:

switch( n ) {
   case 0: m = 2; break;
   case 1: m = 3; break;
   case 2: m = 4; break;
   case 3: m = 5; break;
   // ... and so on

If there is no simple mathematical dependency to be found, you also should consider the following question before coding the conditional assignment:

Is “assignment” really the only task to be performed if a certain condition occurs, and is it unlikely that further conditional code needs to be added in future?

If the answer is yes, it might be helpful to consider using a lookup-table for conditional assignments. Let me show you an example:

Imagine that you have an integer variable which indicates the day of week (1=Monday, 2=Tuesday, and so on). Let’s further assume that you want to convert this number into text.

A straightforward solution could be this:

switch( dayOfWeek ) {
   case 0: text = "Monday";
   case 1: text = "Tuesday";
   case 2: text = "Wednesday";
   case 3: text = "Thursday";
   case 4: text = "Friday";
   case 5: text = "Saturday";
   case 6: text = "Sunday";

However, in various programming languages, compilers, and platforms the following code may be way faster in execution.

String[] day = { "Monday", "Tuesday", "Wednesday", "Thursday",
                 "Friday", "Saturday", "Sunday" }; 

text = day[ dayOfWeek - 1 ];

Lookup-tables will only provide appropriate solutions in situations where the selector is an integer value, of course. In some cases they might be worth a thought, though. (Wow, a tongue-twister …)

In C you can do fancy stuff by using such tables: Just create an array that contains pointers to functions and invoke them based on the value of an integer variable. (This technique is called “function pointer array”.)

That’s all for now. Have fun!

— Andre M. Maier


About bitjunkie

Teacher, Lecturer, and BITJUNKIE ...
This entry was posted in Programming Essentials, Uncategorized and tagged , , , , . Bookmark the permalink.