wierd OOP problem (a bit complicated)

  • Thread starter Thread starter cody
  • Start date Start date
C

cody

I have a OOP problem with the well known pattern where objects containing an
object which represents a list of subobjects. Now my problem is that the
ctor of a subobject indirectly calls the property in Foo which returns the
BarList, since to this time the ctor of BarList did not returned yet, the
reference "list" is still null and so the next call
to the property tries to initialize BarList again!

I know there are several ways to solve this problem but what is the
recommended way to avoid this wierd problem?

class Foo
{
public Bar FirstBar(){return BarList[0];}
BarList list;
public BarList BarList
{
get {if(list==null)list=new BarList();return list;}
}
}

class BarList
{
Bar[] bar;
public BarList(Foo foo)
{
// initialize bars
}
}

class Bar
{
Bar(Foo foo)
{
if (this==foo.FirstBar) // here recursive call initializing BarList
again and again.
{
// do someting
}
}
}
 
cody said:
I have a OOP problem with the well known pattern where objects containing an
object which represents a list of subobjects. Now my problem is that the
ctor of a subobject indirectly calls the property in Foo which returns the
BarList, since to this time the ctor of BarList did not returned yet, the
reference "list" is still null and so the next call
to the property tries to initialize BarList again!

I know there are several ways to solve this problem but what is the
recommended way to avoid this wierd problem?

class Foo
{
public Bar FirstBar(){return BarList[0];}
BarList list;
public BarList BarList
{
get {if(list==null)list=new BarList();return list;}
}
}

class BarList
{
Bar[] bar;
public BarList(Foo foo)
{
// initialize bars
}
}

class Bar
{
Bar(Foo foo)
{
if (this==foo.FirstBar) // here recursive call initializing BarList
again and again.
{
// do someting
}
}
}

All I can make of it is that you're trying to define a list of type T and
you want to pass the instance of T which contains an object O to that same
object O when O is constructed. So far this will not be a problem, however in
O's constructor you're trying to check if O is the first instance in the list
O is in. This dives into recursion in your solution because you're doing test
actions in the constructor, while the constructor should just be a routine to
setup the object with default values and initialize it a bit (not much).

However if you change Foo.FirstBar into:
public Bar FirstBar
{
get
{
if(list==null)
{
return null;
}
else
{
return list[0];
}
}
}

it should work, however perhaps I don't understand what you're trying to
achieve. I think your code can be restructured for what you want to achieve.

FB
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top