[Mono-list] code stuff

Michael Poole poole@troilus.org
20 Jul 2001 10:10:00 -0400


Andrew Sutton <ansutton@sep.com> writes:

> there was some talk yesterday about coding standards for c#... i'd like to 
> add one. if a class has attributes, make sure they're protected - not private 
> (you never know whose going to subclass you), and not public (thats what 
> accessors are for).
> 
> for example, i was throwing together a SocketException class and found that 
> the Exception class defined the source as a private attribute. can't use it 
> without the accessor.

There are some advantages to having attributes private.

For example, a sufficiently smart JIT can open-code the accessor as a
direct reference to the (normally private) attribute; the JIT can also
make additional optimizations if it knows all of the places that
assume things about the layout of the class's attributes -- for
example, improved handling of things like invariants and dead data.

It also makes the interfaces clearer; if several attributes of a class
have data dependencies, any subclass of it needs to maintain the
proper relations (whatever invariants must hold).  For example, take
an IMAP connection class.  It has attributes like the underlying
network stream, connection state, etc.  Subclasses need to update the
connection state as they read or write data to the network stream.
This can lead to hard-to-find bugs.

In fact, some OOP purists think that there should be no protected
attributes ever (just as some say there should be no public
attributes).  I disagree with that extreme, but there are enough
complications from having attributes mutable outside the defining
class that you should be careful with hard-and-fast rules.

-- Michael