Question

I have a piece of code, which I am not sure how to refactor.. It is not very readable and I would like to make it readable. Here is a the problem

There are two columns in database which can be either NULL, 0 or have a value each. On the web page there is a checkbox - enable and text box - value for each of those two columns.

x = checkbox1
z = textbox1
y = checkbox2
w = textbox2

The logic is if both the checkboxes are not selected, then both the values should be 0. If either one is selected and other is not, then others value should be NULL. and for the one that is selected, if the textbox is empty its value should be NULL else should be the value in the textbox

if{x}
{
   if(z)
   {
      a = NULL;
   }
   else
   {
      a = z;
   }
   if(y)
   {
      if(w)
      {
          b=w;
      }
      else
      {
          b = NULL;
      }
   }
   else
   {
      b = null
   }
}
else
{
   if(y)
   {
      a = NULL;
      if(w)
      {
          b=w;
      }
      else
      {
          b = NULL;
      }
   }
   else
   {
      a = 0;
      b = 0;
   }
}

Trust me this is a valid scenario. Let me know if this makes sense or I should give more information

Was it helpful?

Solution

Using some logical ands and nots, we get something more readable. We can save a little by defaulting to NULL (thus not needing to set the other to NULL). We can also save by putting the code for checking if a textbox is set or using null into a little function.

In pseudo code:

a = NULL
b = NULL
if (not checkbox1) and (not checkbox2):
  a = 0
  b = 0
if (checkbox1):
  a = valueornull(textbox1)
if (checkbox2):
  b = valueornull(textbox2)


function valueornull(textbox):
  if textbox value:
    return value
  else:
    return null

OTHER TIPS

I think it would help to use more descriptive names that the single letters here, but assuming this is C code, it looks a lot neater with inline if statements:

if(x)
{
   a = z ? NULL : z;
   b = (y && w) ? w : NULL;
}
else
{
   a = y ? NULL : 0;
   b = (y && w) ? w : 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top