Assignment in conditional expressions - what are the potential code quality consequences of this?

134 views Asked by At

While doing the code inspection of one of the project, I have come across that Resharper is giving "Assignment in conditional expression" warning for a code block similar to below:

if (this.pnlSummary.Visible = isValid)
{
    //do something
}
else
{
    // do something
}

While I agree that this compromises readability to some extent.. but apart from that I dont think there are any disadvantages of using this as far as code execution is concerned.

Could anyone please suggest what could be the potential consequences of writing assignments in conditional expressions?

Based on that, I will instruct developers to avoid writing such code.

Any advice on this will be much appreciated.

2

There are 2 answers

3
Hamid Pourjam On BEST ANSWER

A good programmer is a programmer who writes code that his coworkers understand not the one who writes code that computers understand.

While I agree that this compromises readability to some extent.

There you are. This is absolutely a good reason to prevent programmers from writing code like this. Also when you can write better code with just few keystrokes then what is the reason behind doing something harmful?

this.pnlSummary.Visible = isValid;
if (this.pnlSummary.Visible)
{
    //do something
}
else
{ 
   // do something
}

you see? just some keys and few dots. Auto-complete is awesome!

0
cyberj0g On

I think it compromises readability but not in a way "I wonder what that code does?", but rather "It's most likely assignment-instead-of-comparison bug, I will spend some time to check it". Static code analysis tools like R# also will always give false-positives on that.