I wrote both of these for correcting rectangles. For example, if a rectangle has these properties:
X:32, Y:32, Width:-32, Height:-32
This will make the rectangle X:0, Y:0, Width:32, Height:32
if (r.Width < 0)
{
r.X -= Math.Abs(r.Width);
r.Width = Math.Abs(r.Width);
}
if (r.Height < 0)
{
r.Y -= Math.Abs(r.Height);
r.Height = Math.Abs(r.Height);
}
Here is #2
r.X -= Math.Abs(Math.Min(0, r.Width));
r.Width = Math.Abs(r.Width);
r.Y -= Math.Abs(Math.Min(0, r.Height));
r.Height = Math.Abs(r.Height);
They both work just fine. My question is which? I feel like the first may be faster and more readable but the second has less lines of code. Also, I feel like this is something that may have been invented already. Is there a method that does this already in the .NET or XNA Framework?
Thanks!!
Edit: Someone posted a shortened version of the second way which I really like and combined it into this:
r = new Rectangle(r.X + Math.Min(0, r.Width), r.Y + Math.Min(0, r.Height), Math.Abs(r.Width), Math.Abs(r.Height));
Honestly I prefer less lines to more and I don’t think this is too complex. If anything I can place a comment or encapsulate it in to a method with a descriptive name.
If you know r.Width and r.Height are < 0 why do you need to Abs on them? Remove that and it will be even faster, and simpler.
IMHO the second way you’ve written of doing this is just plain ugly. You don’t look at it and immediately realise what it’s doing. Remember KISS.
EDIT: I understand you like your code in the fewest lines possible so I re-engineered the above:
Just as simple – and all in one line of code! It’s even less characters on the line than your alternative….
Line count is generally not a good measure of programming beauty – but of course it’s your code so you’ve got to go with what brings you the most joy.