views:

175

answers:

5

I'm in the middle of refactoring some code on my current project, and I'd like some input on if any design pattern exists for the following scenario.

I have a class which executes some logic and returns an object containing the results of said logic; Let's call this the Result object. The state information contained in the Result object is constructed based on a more complex object, the Intermediary object.

Now the code which populates the Result object from the Intermediary object already exists, but since I'm refactoring I want to make this cleaner. I was thinking of creating a separate class, maybe called ResultBuilder, which has a static execute method which takes Intermediary as input and spits out Result as output.

Is there a design pattern which is equivalent to the "ResultBuilder" class? Is there a better way of going about constructing a Result object from an Intermediary object?

+2  A: 

I believe you want the Factory pattern.

McWafflestix
+1  A: 

It seems that you already have the solution, So why do you find the need to have some external source to name it for you so it will become more valid?
If it makes sense to you and indeed makes things clearer and cleaner, just do it without excessive thinking about names and labels.

shoosh
So that anyone dealing with the code in the future just needs to see the word factory and understand the intent? The whole rationale behind patterns is communicating common designs with a common vocabulary.
Ken
Because the thinking and refinement that have gone into documented patterns may help to inform and enhance Todd's design. Because it may be a solved problem, and it's easier to apply an already-existing solution than to create one from scratch. Because an existing solution may be more robust than his own. Because we learn from the community.
Carl Manaster
I agree that Design Patterns are useful as a documentation mechanism but as a way to face problems it is limited at best.
shoosh
+1  A: 

Why can't a Result have a constructor that takes an Intermediary instance?

Marco Mustapic
I was thinking about this, but then I felt like it would be cluttering up the Model object with external logic.
Todd
Yes, but sometimes it is not a bad thing. Classes should encapsulate state and logic. Putting the building process as a static method in another class is like having a top-level function, since its reason for the existence is that unique method.
Marco Mustapic
+1  A: 

The Builder pattern!

though its usually a multi part build process....if it just makes one thing, then its more of a factory....

its a standard GOF pattern

Keith Nicholas
Well, the builder pattern abstracts the steps of the building process, usually when you have a whole hierarchy of products you want to build.
Marco Mustapic
+1  A: 

I would suggest looking into the Builder and Factory patterns, both of which are Gang of Four patterns. There are examples on Wikipedia of both, and in Java no less.

Thomas Owens