Clearest Code Challenge: Honorable Mention


Honorable mention to Thomas Eyde.  His submission uses a new class, so he gets points for trying to be OO.  I don’t think this approach was fruitfull, though; the result is pretty complex to my eyes.


He’s also the only one who submitted legal code.  Every other submission had problems that a compiler would have a hard time with.


Here’s Thomas’s submission, pretty printed for your enjoyment:



using System.Windows.Forms;


using System.Drawing;


 


class C : Form


{


    Button _buttonOK;


    Button _buttonCancel;


 


    void F()


    {


        int margin = 12;


 


        ControlMover okMover = new ControlMover(_buttonOK, this.ClientSize, margin);


        okMover.MoveLeft();


        okMover.MoveUp();


 


        ControlMover cancelMover = new ControlMover(_buttonCancel, _buttonOK.Location, margin);


        cancelMover.MoveLeft();


    }


}


 


class ControlMover


{


    Control _control;


    int _margin;


 


    public ControlMover(Control c, Point location, int margin)


    {


        _margin = margin;


        _control = c;


        _control.Location = location;


    }


 


    public ControlMover(Control c, Size location, int margin)


: this (c, new Point(location), margin)


    {


    }


 


    public void MoveLeft(int delta)


    {


        _control.Location = Offset(-delta – _margin, 0);


    }


 


    Point Offset(int deltaX, int deltaY)


    {


        Point location = _control.Location;


        location.Offset(deltaX, deltaY);


        return location;


    }


 


    public void MoveLeft()


    {


        MoveLeft(_control.Width);


    }


 


    public void MoveUp(int delta)


    {


        _control.Location = Offset(0, -delta – _margin);


    }


 


    public void MoveUp()


    {


        MoveUp(_control.Height);


    }


}


Does it work?  I’m not really sure.  I hoped that the clearest solution would be trivial to verify by inspection. 


It looks to me like it places the OK button in the bottom-right corner of the form, with the Cancel button to its left.  That’s not what I asked for, but it’s OK because:


·        It’s easy to see by inspection.


·        It’s probably easy to fix.


Those last bullets are indications that Thomas got something right.

Comments (1)

  1. Thomas Eyde says:

    Thank you for the kudos.

    I know the buttons are misplaced. I didn’t care to fix it when I discovered the mistake.

    Yes, the code works. I have never moved controls in code, so it took some investigation and trial and error.

    I would use a little more energy to make the code clearer if it were production code.