First of all, I wouldnt say this is an architectural question. It is merely
a design decision based on forces. In both situations your memory impact is
completely dependant on whether the instance of B is associated to many
other instances of A at the same time. If your situation is simply that you
need an A, and it needs a B and one is created and passed in, you will
clearly get a memory impact - but if that is the true domain, then that is
the true domain.
Option 2 is a design choice one would make early on while the system is
taking shape. However this violates a few fundamental principles of object
orientation, in that you will clearly need to recompile the whole system if
you need A to now use a C instead of a B, but C decends from B. Option 2
violates a principle pioneered by Bertrand Meyer many moons ago, known as
the Open Closed Principle: "A module should be open to extension, but
closed for modification". In laymen terms, you should be able to extend A's
use with other neighbouring objects without requiring the need to change
your code in class A (the modification aspect). Depending on abstract types
is the key.
The most advanced technique for decoupling is using interfaces, and
inverting the dependancy. A then has a dependancy on an interface that is
contextually part of A's micro-problem domain. For example a Swtich could
depend on ISwitchable. Then, any bunch of objects could implement
ISwitchable, and Switch can now be extended to talk to a whole suite of
classes withouth making a single change to Switch.
Based on this, the whole reason for creating objects with the right types is
because a policy layer makes the decisions at application start up or
runtime (using factories). As an example, you might have a business object
that depends on a dal object. For arguments sake A might need persisting by
IADataService. At some point a decision is made whether to use the RDBMS
IADataService, the XML IADataService or some other data service
implementation. This decision is then applied as a policy, to the
instantiation of the association between A and its IADataService. If you
didnt create the objects passing in its types in this manner, the system
wouldnt be extendable.
HTH
Nick.
andrewcw said:
Can someone share some insight on this:
I have a class A. It needs functions from class B.
Option 1: instantiate A by passing in an instance of B [ I think this is less memory than option 2 ]
Option 2: Have A create an instance of B.
other ideas - some form of interface, but then some place I still have an
instance of B. What are some good ways to decouple or reduce the dependency
?
I went to a seminar and heard of how when a class gets created it gets
created with the right object types... say like a Tax object tailored for
the US vice Canada. Thanks for the advice. Andrew