Clearest Code Challenge: My answer
Here’s my solution.
const int spacing = 12;
_buttonCancel.Location = new Point(this.ClientSize - _buttonCancel.Size - new Size(spacing, spacing));
_buttonOK.Location = _buttonCancel.Location - new Size(spacing + _buttonCancel.Width, 0);
It’s pretty short.
I didn’t create any new types to solve the problem, but there is still an important OO lesson to be learned here. As much as possible, I tried to deal with higher order types. See that I used arithmetic on Point and Size types, instead of on X and Y coordinates, for the most part. The only exception is the “spacing + _buttonCancel.Width” expression in the last line. I could have created a pair of Size objects, I suppose:
const int spacing = 12;
_buttonCancel.Location = new Point(this.ClientSize - _buttonCancel.Size - new Size(spacing, spacing));
_buttonOK.Location = _buttonCancel.Location - new Size(spacing, 0) - new Size(_buttonCancel.Width, 0);
I’m not sure whether that’s an improvement or not. Your thoughts?
My real solution (the one I checked in to our source control) has 2 differences from the above code:
1. I extracted 2 methods
2. I included some comments
Here is what I actually checked in:
void HACK_ResetButtonLocations()
{
const int spacing = 12;
HACK_PlaceCancelButton(spacing);
HACK_PlaceOKButton(spacing);
this.PerformLayout();
}
void HACK_PlaceCancelButton(int spacing)
{
// place the Cancel button from the bottom-right corner of the form
ButtonCancel.Location = new Point(this.ClientSize - ButtonCancel.Size - new Size(spacing, spacing));
}
void HACK_PlaceOKButton(int spacing)
{
// place the OK button from the Cancel button
ButtonOK.Location = ButtonCancel.Location - new Size(spacing + ButtonCancel.Width, 0);
}
I have an unpleasant taste in my mouth, still. None of the solutions I’ve seen, including my own, seem clean & elegant. Maybe one of you will read this and think of something better?
Hopefully in a few days the bug that I’m working around will be fixed in the internal build, and I can go back to using anchoring.