Code Readability...
The issue of code readability is one of those that I normally try to avoid. Why? Because if you asked every developer on Earth “Do you write code that is easily 'readable'” You'd probably get a response rate over 95% “Yes”. However if you asked every developer on Earth “Have you worked with/Do you know, someone that doesn't write readable code” it'd be a resounding 100% Yes. So where's the discrepancy? My point is that any time I've ever got into a discussion about what's 'readable' it usually ends up looking like a recursive loop without an exit condition. However, just as a general subject - I'd be interested in opinions on this one:
First, which way do you think is 'better' - with better defined as more benefits overall than costs:
First method:
int a = 5;
int b = 10;
int temp = a;
a = b;
b = temp;
Second method:
int x = 5;
int y = 10;
x ^= y;
y ^= x;
x ^= y;
--------------------------
Debug.WriteLine(String.Format("Value of x:{0}, value of y{1}", x.ToString(), y.ToString()));
//OR
Debug.WriteLine("Value of x:" + x.ToString() + " value of y: " + y.ToString());
Now for a few more:
private System.Int32 ReturnLargest()
{
System.Int32 x = 10;
System.Int32 y = 20;
return(x > y)? x : y;
}
private System.Int32 returnLargest()
{
System.Int32 x = 10;
System.Int32 y = 20;
if(x > y)
return x;
else
return y;
}
Clearly I prefer the first one here.
What about braces - compared to the one directly above using the if and else:
private System.Int32 returnLargest()
{
System.Int32 x = 10;
System.Int32 y = 20;
if(x > y){
return x;
}
else {
return y;
}
}
Do braces really 'enhance' readability? [On a side note - if you don't use braces you can't get one of those awful MismatchedBraceExceptions “Thank you. That's what I tried but I'm still getting mismatched brace
exceptions on the first brace of the Application_Start code block when the
converted code is used in the global.asax as follows...
“ (this was in response to the code I posted yesterday that needed translated from VB.NET TO C# - the guy nested a function declaration inside of another function declaration and the evil MismatchedBraceException sprung up).
I'm definitely in favor of the second method in the first example and the first method in the second example. Much more readable in both cases IMHO.
Thoughts?
Here's my thinking almost across the board - with very rare exceptions - readability is determined by the number of lines of code - Brevity is the mother of wit - and the less lines of code I have to dig through - the quicker I can figure out what's going on. I don't care how 'clear' you make it, if I have to scroll all over the place to see what the hell is going on - it's not readable. Rather, it may be readable but it's painful to dig through. Same thing for code that goes off of the screen to the right - that always sucks.
Any pet peeves you care to mention? that's always a fun discussion.