Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code suggestions by Resharper making code less readable?

Tags:

c#

resharper

While trying to get to all green, i got the following suggestion by Resharper.

Original code:

    static public string ToNonNullString(this XmlAttribute attr)     {         if (attr != null)             return attr.Value;         else             return string.Empty;     } 

Suggestion: remove redundant 'else' resulting in following:

    static public string ToNonNullString(this XmlAttribute attr)     {         if (attr != null)             return attr.Value;         return string.Empty;     } 

To me, the suggested version seems less readable than the original. Does Resharper suggestion reflect the definition of good maintainable code?

like image 904
AngryHacker Avatar asked Jan 21 '09 22:01

AngryHacker


2 Answers

Technically Resharper is correct in that the "else" is unnecessary, I prefer the former version though as the intent is more obvious.

Having said that, I'd rather go with:

return attr != null ? attr.Value : string.Empty; 
like image 143
tddmonkey Avatar answered Oct 01 '22 05:10

tddmonkey


Ah, code aesthetics. Holy war time. (ducks)

I'd go with either a ?: expression:

return attr != null ? attr.Value : String.Empty 

or invert the if and remove the line break to produce a guard clause:

if (attr == null) return String.Empty;  return attr.Value; 
like image 35
Jeffrey Hantin Avatar answered Oct 01 '22 07:10

Jeffrey Hantin