4

I'm having a bit of a brain fart on making this code more concise(preferably a single boolean expression)

This is my code:

                    if (d.Unemployed)
                    {
                        if (type.Unemployed)
                        {
                            tmp.Unemployed = true;
                        }
                        else
                        {
                            tmp.Unemployed = false;
                        }
                    }
                    else
                    {
                        if (type.Unemployed)
                        {
                            tmp.Unemployed = false;
                        }
                        else
                        {
                            tmp.Unemployed = true;
                        }
                    }

Basically the point is that if either type or d is not unemployed, then tmp should be set to not unemployed.

Earlz
  • 62,085
  • 98
  • 303
  • 499

5 Answers5

14

How about:

tmp.Unemployed = type.Unemployed == d.Unemployed;
MRAB
  • 20,356
  • 6
  • 40
  • 33
8

If we construct a truth table by following the code, we get

d  | type | tmp
---+------+----
1  |   1  |  1
---+------+----
1  |   0  |  0
----+-----+----
0  |   1  |  0
----+-----+----
0  |   0  |  1

The above is equivalent with the negation of the xor operation.

tmp = not (d xor type)

If the language doesn't have the xor operator we can use the != on boolean values.

tmp = ! (d != type);
// or
tmp = d == type;
Nick Dandoulakis
  • 42,588
  • 16
  • 104
  • 136
2

Thinking about how much "brain fart" this caused you I would consider using a well named variable to avoid having to go through this mental process again in future. Something like this:

isTmpUnemployed = (type.Unemployed == d.Unemployed);
tmp.Unemployed = isTmpUnemployed;
Paul.s
  • 38,494
  • 5
  • 70
  • 88
0
tmp.Unemployed = d.Unemployed || type.Unemployed ? !tmp.Unemployed : null;
Shaz
  • 15,637
  • 3
  • 41
  • 59
0

The above code means "both unemployed or both not unemployed". Thus, not (A xor B):

 tmp.Unemployed = ! ( D.Unemployed ^ type.Unemployed)
Peter O.
  • 32,158
  • 14
  • 82
  • 96