Recommended ways to handle final classes

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Aug 16 11:19:16 PDT 2013


On Fri, Aug 16, 2013 at 07:51:22PM +0200, Joseph Rushton Wakeling wrote:
> On Friday, 16 August 2013 at 17:08:36 UTC, Dicebot wrote:
[...]
> >From the conceptual purity point of view I still think that having
> >bunch of template mixins instead of _A and just combining them
> >into A or B is the proper way (inheritance should not be used as
> >code reusage tool) - but D may not have powerful enough tools to
> >makes this approach convenient, so resorting to old-school
> >inheritance sounds pragmatical.
> 
> I'm happy to consider alternative ideas. I find that mixins are very
> useful like this but also find that stuff tends to gain complexity
> quite rapidly with their use.

This probably doesn't relate directly to your problem at hand, but armed
with alias this, D structs can be made to behave as if they had
inheritance (though not fully):

	struct Base {
		int x;
		void baseMethod() {}
	}

	struct Derived {
		Base __base;
		alias __base this;

		int y;
		void derivedMethod() {}
	}

	Derived d;
	d.x = 1; // Can access "base struct" members directly
	d.baseMethod();
	d.y = 2; // Obviously can also access "derived" members
	d.derivedMethod();

You can actually implement your own version of OO by careful use of this
trick (though it would require manual maintenance and wouldn't have
language-level support).

Of course, this isn't necessarily restricted to structs alone. You can
also do this with structs that you 'alias this' into classes, to make it
appear as though the struct methods are among the class methods.
(Unfortunately multiple alias this isn't implemented yet, so this is
somewhat limited. But you should be able to pull off some pretty clever
tricks with it.)


> >You need to be aware though that I am personally an OOP hater and
> >my advices should be reconsidered in with that in mind ;)
[...]

I'm not an OOP *hater* per se, but I *am* a skeptic about applying OOP
anywhere and everywhere, even when it doesn't really belong
(*cough*Java*cough*). Different problems need different solutions;
insisting on turning a screw with a hammer only leads to poor hacks,
boilerplate, and other code smells.

*ahem* http://www.ioccc.org/2005/chia/chia.c *cough* ;-)


T

-- 
"I speak better English than this villain Bush" -- Mohammed Saeed al-Sahaf, Iraqi Minister of Information


More information about the Digitalmars-d-learn mailing list