forbid field name conflict in class hierarchy

Jonathan M Davis jmdavisProg at gmx.com
Tue Nov 16 17:09:19 PST 2010


On Tuesday, November 16, 2010 03:40:24 spir wrote:
> On Tue, 16 Nov 2010 05:37:52 -0500
> 
> bearophile <bearophileHUGS at lycos.com> wrote:
> > spir:
> > > (and bug-prone, because sometimes the absence of a fields seems not
> > > caught, for any reason), so I add fields to the top type.
> > 
> > What do you mean? Do you have an example?
> > (Adding fields to the top type doesn't look like a good idea, generally).
> > 
> > Bye,
> > bearophile
> 
> For instance, I have 2 sub-classes of nodes: one leaf kind with element
> (here called slice), one branch kind with an array of (child) nodes. They
> are exclusive, and none of the data fields should appear on the top Node
> type. But everywhere the Node class must be used, since a branch (as the
> top tree) can indifferently hold leaves or sub-branches, right? Each time
> I need to post-process results, since I apparently get Nodes (even if I
> know they are actually of one or the other type), I would first have to
> down-cast each node to the proper kind before doing anything. Else, I
> would get compiler errors, or plain bugs, for not having the proper field.
> So, I ended up setting fake fields on Node (and remove them from the
> sub-classes). And yes, I agree it's A Bad Thing to do. Just tell me of an
> elegant solution, and I apply it at once.

Well, I think that I'd have to study your code to get quite what you're doing. 
However, I would consider _any_ case in code where you specifically cast to a 
derived class from a base class to be a code smell. My general reaction is that 
there _has_ to be a better, cleaner way to do it, and that it stinks of bad 
design. However, I'd have to really understand what you're doing to give a 
better suggestion, and just because it's _almost_ always a bad idea doesn't mean 
that it's _always_ a  bad idea.

- Jonathan M Davis


More information about the Digitalmars-d mailing list