Does this break encapsulation?

  • Thread starter Thread starter .pd.
  • Start date Start date
P

.pd.

If I have a control that adds itself to its container, does that break
encapsulation? Is it a bad thing?

Here's what I mean:

public class fred
{
public barny b;
public fred()
{
b = new barny(this);
}
....
}

public class barny
{
public barny(fred f)
{
...
f.Controls.Add(this);
}
}

Cheers,
..pd.
 
You have public members in Fred and barney....you could fix this by making
barney private and declaring a property that assigns a value to barny.
Remember that encapsulation doesn't deal with what a class does internally
per se, it deals with how other classes can access things inside your class.
And if outside classes can manipulate your members directly, without being
marshalled through a property, then you broke encapsulation.

Is it a bad thing? Generally speaking, yes and I would recommend avoiding
it. Once again, it mainly depends on how its being used----I know many use
Public variables and think properties are a waste of code - I'm not one of
them. I'd use properties and go from there...

HTH,

Bill
 
William Ryan wrote on Tue 04 Nov 2003 05:38:33p:

Thanks for replying.
You have public members in Fred and barney...

Well, that's just an example. IRL, "b" is a protected member of the
instantiating form, so that only inheritors can manipulate it.
it deals with how other classes can access
things inside your class.

So having b's constructor manipulating f's controls is perfectly
valid/safe/acceptable?

The way I figure, and I'm open to correction, a control - say a Panel -
is always going to have a parent. If part of the Panel's setup is to
make decisions based on its parent's fields/properties then why make the
instantiator have to:

(a) call a separate method in the barny object that would have to check
that a parent has been assigned before it could do any processing
(b) remember not to call said setup routine until after it has added the
control to itself.

Compared to my original example, this looks very convoluted.

public class fred
{
public fred()
{
barny b = new barny();
this.Controls.Add(b);
b.Setup();
}
}

public class barny
{
public barny()
{
// can't do any initialisation stuff based on parent
// here cuz we don't know who we belong to yet
}
public void Setup()
{
// but we still have to check even here
if (Parent == null)
throw new Exception("You haven't added the control *to*
anything yet!");
else
{
// finally we get to do the initialisation
}
}
}
And if outside classes can manipulate your
members directly, without being marshalled through a property, then
you broke encapsulation.

Okay - but Controls being a public member of the Control class isn't
something I can change. So can I assume M$'s decision to make it public
is an indication that anyone with a reference to the object may add
controls to it with impunity?
I'm not one of them.

Me either :-)

Thanks again for your response,

..pd.
 
Back
Top