Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single-use object: yea or nay?

I'm thinking about creating some classes along a "single-use" design pattern, defined by the following features:

  • Instances are used for performing some task.
  • An instance will execute the task only once. Trying to call the execute method twice will raise an exception.
  • Properties can be modified before the execute method is called. Calling them afterward will also raise an exception.

A minimalist implementation might look like:

public class Worker
{
    private bool _executed = false;

    private object _someProperty;
    public object SomeProperty
    {
        get { return _someProperty; }
        set
        {
            ThrowIfExecuted();
            _someProperty = value;
        }
    }

    public void Execute()
    {
        ThrowIfExecuted();
        _executed = true;
        // do work. . .
    }

    private void CheckNotExcecuted()
    {
        if(_executed) throw new InvalidOperationException();
    }
}

Questions:

  1. Is there a name for this?
  2. Pattern or anti-pattern?
like image 680
Sean U Avatar asked Oct 22 '22 09:10

Sean U


1 Answers

This looks like a form of a balking pattern.

If it appears logical for your specific object to behave in this way, I don't see a problem with it.

like image 85
Guffa Avatar answered Oct 27 '22 09:10

Guffa