views:

95

answers:

4

Hello all, I'd like to know whether this approach is correct or if their are better ways of doing this.

I have what is basically a Person class which has a number of other classes as variables, each of the custom classes is instantiated by passing the Person ID and then that class retrieves the data it needs using that ID. I expose the variable classes via Properties.

Currently I am instancing the variable classes when I create an instance of the Person class, and the large number of these mean that the time it takes to instantiate the Person class is growing. My idea was to move the instancing of the variable classes to the Propertie declaration and then using an If statement here to instantiate it if it hasn't yet been done.

As I said above is this approach correct or is their a better way of doing this?

Thanks

A: 

Go with it. If there's a better way, I'd like to hear it too :)

Vincent Van Den Berghe
+3  A: 

There is a term for the technique you're describing; it's called "lazy-loaded properties". It should definitely help spread out your load on this object away from a "front-loaded" constructor.

On a different note, it sounds like what you're describing is going to result in a terribly tightly-coupled object model (if you don't have one already) which is likely to have a negative impact on this code's maintainability. However, I don't think that a serious dissertation on that topic and how to work otherwise is really within the scope of this question.

Matt Campbell
Hi Matt, yeah I know that the classes I'm creating are poor but I'm the 5th dev for this project in 4 years and it's in a very poor state! I want to create a business layer first before I work on the database structure, then I'll go back and improve them. Finishing is the first concern at the mo.
David A Gibson
I don't want to give the impression that your classes are inherently "poor," it's just that having that many different dependencies in a single class is what is referred to as a "code smell." The app is very likely to be hard to maintain, and would probably be hard to unit-test.
Matt Campbell
A: 

Seems there are always better (at least arguably) ways of doing things, but your solution is a good one. Instantiate your person class and in the in for instance the children property you would have something like

If Children Is Nothing Then
   Set Children = New Children
   ...
Beaner
+1  A: 

Just to clarify: If you mean instantiating the classes on the getter of their accessor then yes this is a fine approach - referred to as Lazy Loading.

Eg

public Property ChildClass as PersonChildClass

   Get

      if _childClass is Nothing          
          _childClass = new PersonChildClass(_personId)
      End If
      return _childClass
  End Get
End Property
KiwiBastard
Hi, yeah that's what I meant but Matt named it first so I'll accept his answer, thanks though I'll vote up your answer as well!
David A Gibson