Domanda

I would like to come up with more elegant code. I have this IF statement:

if (( !mainFlag and 
      form.opt1 == store.opt1 and form.opt2 == store.opt2 and 
      form.opt3 == store.opt3 and form.opt4 == store.opt4 ) or 
    ( mainFlag and 
      form.opt1 == store.opt1 and form.opt2 == store.opt2 and 
      form.opt3 == store.opt3 and form.opt4 == store.opt4 and 
      form.opt5 == store.opt5 and form.opt6 == store.opt6 )){
  dataHasBeenUpdated = False;
} else {
  dataHasBeenUpdated = True;
}

Basically I have a number of fields that always need to checked to see if they have been updated (opt1 - 4), but when mainFlag = true I need to also check two other fields.

It kind of bothers me that I have the same checks two times for the first four opt# fields. What would be a more elegant/lest code way of writing this IF statement?

È stato utile?

Soluzione

Let be:

A = mainFlag
B = form.opt1 == store.opt1 and form.opt2 == store.opt2 and 
    form.opt3 == store.opt3 and form.opt4 == store.opt4
C = form.opt5 == store.opt5 and form.opt6 == store.opt6

Where A,B,C are boolean variables. Then, your IF statement has the following boolean expression into it: !A*B + A*B*C

Once simplified, this expression leads us to:

!A*B + A*B*C = B*(!A+A*C) = B*((!A+A)*(!A+C)) = B*(!A+C)

(!,*,+ are boolean operators for NOT,AND and OR respectively)

Translating this back to your IF statement:

if (
     ( form.opt1 == store.opt1 and form.opt2 == store.opt2 and /*       */
       form.opt3 == store.opt3 and form.opt4 == store.opt4     /*   B   */
     ) 
     and 
     (     /* !A */
       !mainFlag or (
                     form.opt5 == store.opt5 and form.opt6 == store.opt6   /* C */
                    )
     )
   )
        dataHasBeenUpdated = False;
    else
        dataHasBeenUpdated = True;

Altri suggerimenti

This should simplify it enough I think...

dataHasBeenUpdated = ! (form.opt1 == store.opt1 
                    and form.opt2 == store.opt2 
                    and form.opt3 == store.opt3 
                    and form.opt4 == store.opt4
                    and ( !mainFlag
                         or (  mainFlag
                           and form.opt3 == store.opt3 
                           and form.opt4 == store.opt4 ) ));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top