Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boiler plate code replacement - is there anything bad about this code?

I've recently created these two (unrelated) methods to replace lots of boiler-plate code in my winforms application. As far as I can tell, they work ok, but I need some reassurance/advice on whether there are some problems I might be missing.

(from memory)

static class SafeInvoker
{
    //Utility to avoid boiler-plate InvokeRequired code
    //Usage: SafeInvoker.Invoke(myCtrl, () => myCtrl.Enabled = false);
    public static void Invoke(Control ctrl, Action cmd)
    {
        if (ctrl.InvokeRequired)
            ctrl.BeginInvoke(new MethodInvoker(cmd));
        else
            cmd();
    }

    //Replaces OnMyEventRaised boiler-plate code
    //Usage: SafeInvoker.RaiseEvent(this, MyEventRaised)
    public static void RaiseEvent(object sender, EventHandler evnt)
    {
        var handler = evnt;
        if (handler != null)
            handler(sender, EventArgs.Empty);
    }
}

EDIT: See related question here

UPDATE

Following on from deadlock problems (related in this question), I have switched from Invoke to BeginInvoke (see an explanation here).

Another Update

Regarding the second snippet, I am increasingly inclined to use the 'empty delegate' pattern, which fixes this problem 'at source' by declaring the event directly with an empty handler, like so:

event EventHandler MyEventRaised = delegate {};
like image 791
Benjol Avatar asked Oct 10 '08 20:10

Benjol


People also ask

Is boilerplate code good or bad?

Boilerplate code by definition is just duplication and it is always bad because opens you up to bugs in a specific part of the boilerplate while you can't have any bug at all in any boilerplate if you don't have any of it.

Why is boilerplate bad?

The problem with boilerplate is that it violates DRY. In essence, when you write boilerplate, you're repeating the same code (or very similar code) across a number of classes. When that code needs to get changed, it's not at all certain that the developer will remember all of the places that code was repeated.

Why is it called boilerplate code?

Because of their resemblance to the metal plates used in the making of boilers, they became known as "boiler plates", and their resulting text—"boilerplate text".


1 Answers

This is good stuff. Make them extension methods though to clean up your code a little more. For example:

//Replaces OnMyEventRaised boiler-plate code
//Usage: SafeInvoker.RaiseEvent(this, MyEventRaised)
public static void Raise(this EventHandler eventToRaise, object sender)
{
            EventHandler eventHandler = eventToRaise;

            if (eventHandler != null)
                eventHandler(sender, EventArgs.Empty);
}

Now on your events you can call: myEvent.Raise(this);

like image 173
programmer Avatar answered Oct 04 '22 18:10

programmer