MadBoy
MadBoy

Reputation: 11104

Is it better to do evaluation of bool once with more code or multiple times with less code

Is it better to evaluate bool once but have more code like this

 if (klient.Podmioty.PodmiotRodzaj == "Osoba") {
     textImie.Enabled = true;
     textNazwisko.Enabled = true;
     textNazwa.Enabled = false;
 } else {
     textImie.Enabled = false;
     textNazwisko.Enabled = false;
     textNazwa.Enabled = true;
 }

comparing to this

      textImie.Enabled = klient.Podmioty.PodmiotRodzaj == "Osoba";
      textNazwisko.Enabled = klient.Podmioty.PodmiotRodzaj == "Osoba";
      textNazwa.Enabled = klient.Podmioty.PodmiotRodzaj != "Osoba";

It's a generic question and maybe this little example is micro optimization but I would like to know whether reusing same bool over and over is not considered bad code.

Probably useful note is that klient.Podmioty.PodmiotRodzaj is actually variable from SQL brought by Entity Framework.

Upvotes: 1

Views: 77

Answers (3)

Mooing Duck
Mooing Duck

Reputation: 66922

The first is the common answer, and the second is hard to read. However, since you're only setting bools to the same as the condition, there's a third option:

bool t = (klient.podmioty.PodmiotRodzaj == "Osaba");
TextImed.Enabled = t;
TextNazwisko.Enabled = t;
TextNazwa.Enabled = !t;

(On phone, so I prob got the variable names wrong) This is debatibly slightly less clear than the first option, but brief (and avoids code forks).

Upvotes: 0

Oded
Oded

Reputation: 498942

Evaluate once and use the results:

var conditionValue = (klient.Podmioty.PodmiotRodzaj == "Osoba");

textImie.Enabled = conditionValue;
textNazwisko.Enabled = conditionValue;
textNazwa.Enabled = !conditionValue;

Upvotes: 8

Roee Gavirel
Roee Gavirel

Reputation: 19445

The first option, less calculation time and no replica of code...

or, option C:

bool value = klient.Podmioty.PodmiotRodzaj == "Osoba";
textImie.Enabled = value;
textNazwisko.Enabled = value;
textNazwa.Enabled = !value;

but definitely not your option B.

Upvotes: 4

Related Questions