[MonoDevelop] Public Widgets using Stetic?

Michael Hutchinson m.j.hutchinson at gmail.com
Tue Dec 9 14:07:37 EST 2008


On Mon, Dec 8, 2008 at 10:13 PM, Iggy <iggy.ma at gmail.com> wrote:
> I am trying to figure out how to make the widgets that I add using
> stetic public instead of private and I can't seem to figure it out. I
> dont see any public/private modifiers in the GUI properties. Does
> anybody know how to do this without writing properties to expose each
> private widget?

In general in .NET/Mono it is recommended to use properties instead of
public/protected fields, as this allows you to change internal
implementation without breaking ABI.  Trivial properties are inlined
by the JIT so there is no real cost. The commonness of trivial
properties with backing fields is why we have automatic properties in
C# 3.

Properties also allow you to control access - do you really want
public writable fields? Someone could accidentally overwrite a widget
reference - and simply writing to the field won't replace the actual
widget in the UI. The solution is simple - a public property without a
setter, making it impossible for users of your widget to do these
'wrong' things. In addition, you can validate values in the setters.
This will help to prevent making mistakes.

The last but most important point is encapsulation. Why do you want to
expose the internal structure (widgets) of your widget? Instead, think
of your composite widget/window as one coherent structure and expose
only the things that are necessary, and as if they're aspects of that
structure. For example, is there a label in your widget that could be
thought of as its title? Then expose the label's text as your widget's
title:

public string Title {
    get { return titleLabel.Text; }
    set { titleLabel.Text = value; }
}

Then users of your widget will do
myWidget.Title = "Hello";
instead of
myWidget.TitleLabel.Text = "Hello";
which is much more easily understandable, since you are not exposing
unnecessary complexity.

Good encapsulation makes your code more maintainable, because users of
your widget will not be dependent on its internal structure.

-- 
Michael Hutchinson
http://mjhutchinson.com


More information about the Monodevelop-list mailing list