Question

Sorry if this was asked, but I keep wondering and weren't able to google up solution and not for luck of trying.

When implementing Command pattern inside one class, this one-method interface keeps popping up in all places.

public interface Command {
   void execute();
}

Then it gets reused plenty of times like this:

public void doAction1()
{
    perform(new Command () {
        @Override
        public void execute()
        {
            //do some crazy stuff
        }
    });
}
public void doAction2()
{
    perform(new Command () {
        @Override
        public void execute()
        {
            //do some event crazier stuff
        }
    });
}

public void doAction3()
{
    perform(new Command () {
        @Override
        public void execute()
        {
            //do a barrel roll
        }
    });
}

private void perform(Command command)
{
    command.execute();
}

Different namings, different modules, different software even --- but this one gets reimplemented over and over, cluttering source and doing essentially nothing new.

Is there any generic, OOB one-method interface that's OK to use instead of creating my own every time I need lambda-like sentence? Is it OK to use Runnable in this way? Wouldn't it create confusion in the mind of some future source code-reader?

PS: Now, I know, that there's java 1.8 with lambdas and all, but at my work we're stuck with 1.6 for the moment (enterprise customers are so enterprise), so I'd appreciate some archeological help here.

Was it helpful?

Solution

Yes, Runnable or Callable (if you need to return a result) are perfectly fine to use.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top