0

A naive and hard to test implementation of a method could look like this

public void getFromDatabaseComputeAndStore(SomeType param) {
     Collection<Something> s = dao.retrieveSomethingFromDatabase(param);
     Collection<Other> o = dao.retrieveOtherFromDatabase(param);
     Result r = null;
     <do massive computation, call other methods, figure out what r should be>
     <based on s and o>
     dao.store(r);
}

Normally I'd refactor this into something like

public void getFromDatabaseComputeAndStore(SomeType param) {
     Computer computer = new Computer();
     Collection<Something> s = dao.retrieveFromDatabase(param);
     Collection<Other> o = dao.retrieveOtherFromDatabase(param);
     computer.setSomething(s);
     computer.setOther(o);
     computer.execute();
     Result r = computer.getResult();
     dao.store(r);
}

where the Computer class is the key. This class does not interact with databases or other external systems and has no side effects, eg it's purely functional. Given the same somethings and others, the result will always be the same.

So my question are:

  • Is this a known pattern with a name
  • What would be the common name of a class with the functionality of Computer

I've looked at the Strategy, Mediator, and Command patterns, but I don't feel they fit perfectly.

slipset
  • 2,960
  • 2
  • 21
  • 17
  • why cant you simply have a method which takes two arguments? Especially since you are not using multiple threads or getting any other advantage besides some neater code – Osama Javed May 09 '12 at 09:47
  • It looks like a [Master/Worker pattern](http://stackoverflow.com/a/8573733/829571). See also: http://blog.gigaspaces.com/2009/08/24/the-master-worker-pattern/. – assylias May 09 '12 at 09:49
  • Because, as I tried to show, the computations needed to calculate the results could be quite large and you might want to isolate it. – slipset May 09 '12 at 09:49
  • 1
    Errr, it is called refactoring. This is a style, not a pattern. – leppie May 09 '12 at 09:51
  • Or at the very least decoupling, since you're decoupling the `Computer` from having to know about the formatting, etc of DB results. – Brady May 09 '12 at 11:27

1 Answers1

0

Your Computer is a form of a Builder.

One use of a Builder is to allow complex construction of an object to be encapulated such that the client of the builder never has access to a partially constructed or invalid object. You configure the Builder and then fetch the completed object from it.

Note that the GoF has a builder example that includes a polymorphic result. That usage is common as well, but I don't feel it is strictly required.

.NET and Java have ample examples of both usages in their frameworks.

tcarvin
  • 10,715
  • 3
  • 31
  • 52