Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it proper to negate an entire if statement to check for null values?

Tags:

c#

I am somewhat of a beginner programmer. What I am trying to do here is to check that if there is a time, if it is selected, and if that time is equivalent to the other. If that is all true then I want to skip the block of code under it. Here is the code example:

if (currentGVR.Round_Start_Time)
{
     if (tr.StartLunchDateTime != null && currentGVR.Round_Start_Lunch && roundedStart == roundedStartL)
           // skip
     else
     {
           key = tr.TransactionID;
           TransactionRecords[key]["Start_DateTime"] = roundedStart;
     }
}

I thought about using an OR operator, but I can see where an error would occur if there was no time to compare to. Using the AND operator avoids this dilemma here.

So the overall question is, is it proper coding to negate all of the conditions to get the correct result, e.g. if (!( cond's )), and also, would this be the best way to check if there is a value to compare with before actually comparing it in C# and otherwise? The times can be null (or do not exist) in some records. Any recommendations?

like image 283
Mark Avatar asked Dec 19 '22 04:12

Mark


2 Answers

I'd negate all those conditions and switch the && to || so it's more quickly evident under what conditions the code will (or will not) execute.

Plus (in my experience), you don't typically see an empty if block with all the code under the else.

if (tr.StartLunchDateTime == null || !currentGVR.Round_Start_Lunch || roundedStart != roundedStartL)
{
    key = tr.TransactionID;
    TransactionRecords[key]["Start_DateTime"] = roundedStart;
}
like image 191
Grant Winney Avatar answered Jan 12 '23 00:01

Grant Winney


The statement

 if (tr.StartLunchDateTime != null && currentGVR.Round_Start_Lunch && roundedStart == roundedStartL){
       // skip
 }
 else
 {
       key = tr.TransactionID;
       TransactionRecords[key]["Start_DateTime"] = roundedStart;
 }

is equivalent to

 if (!(tr.StartLunchDateTime != null && currentGVR.Round_Start_Lunch && roundedStart == roundedStartL))
 {
       key = tr.TransactionID;
       TransactionRecords[key]["Start_DateTime"] = roundedStart;
 }
 else {
       // skip
 }

This can be further simplified because

!(tr.StartLunchDateTime != null && 
  currentGVR.Round_Start_Lunch &&
  roundedStart == roundedStartL)

Is the same as

(!(tr.StartLunchDateTime != null) ||
  !(currentGVR.Round_Start_Lunch) ||
  !(roundedStart == roundedStartL))

or

(tr.StartLunchDateTime == null ||
 !currentGVR.Round_Start_Lunch ||
 roundedStart != roundedStartL)

See DeMorgan's Laws.

like image 32
John Saunders Avatar answered Jan 11 '23 22:01

John Saunders