Building a structure/object in a place other than the constructor
Posted
by
Vishal Naidu
on Stack Overflow
See other posts from Stack Overflow
or by Vishal Naidu
Published on 2012-11-17T04:21:46Z
Indexed on
2012/11/17
5:00 UTC
Read the original article
Hit count: 177
I have different types of objects representing the same business entity.
UIObject
, PowershellObject
, DevCodeModelObject
, WMIObject
all are different representation to the same entity.
So say if the entity is Animal
then I have AnimalUIObject
, AnimalPSObject
, AnimalModelObject
, AnimalWMIObject
, etc.
Now the implementations of AnimalUIObject
, AnimalPSObject
, AnimalModelObject
are all in separate assemblies.
Now my scenario is I want to verify the contents of business entity Animal
irrespective of the assembly it came from. So I created a GenericAnimal
class to represent the Animal
entity.
Now in GenericAnimal
I added the following constructors:
GenericAnimal(AnimalUIObject)
GenericAnimal(AnimalPSObject)
GenericAnimal(AnimalModelObject)
Basically I made GenericAnimal
depend on all the underlying assemblies so that while verifying I deal with this abstraction.
Now the other approach to do this is have GenericAnimal
with an empty constructor
an allow these underlying assemblies to have a Transform()
method which would build the GenericAnimal
.
Both approaches have some pros and cons:
The 1st approach:
Pros: All construction logic is in one place in one class GenericAnimal
Cons: GenericAnimal
class must be touched every-time there is a new representation form.
The 2nd approach:
Pros: construction responsibility is delegated to the underlying assembly.
Cons: As construction logic is spread accross assemblies, tomorrow if I need to add a property X
in GenericAnimal
then I have to touch all the assemblies to change the Transform
method.
Which approach looks better ?
or Which would you consider a lesser evil ?
Is there any alternative way better than the above two ?
© Stack Overflow or respective owner