Classes (does this make sense?)

Lutger lutger.blijdestin at gmail.com
Mon Jun 2 03:50:08 PDT 2008


Saaa wrote:

> Best read after 'this needs a different approach' :)
> Still trying to get some grip on those classes...
> please comment on my try.

I'll try, comments are after each piece of code.
 
> ---------------------------
> module main;
> import std.stdio;
> public import FruitClass
> 
> int main(string[] args) {
> 
> writefln("Fruits");
> foreach( f; fruits) {
> f.eat();
> }

This has nothing to do with classes, but public import is not needed here
since this is your main entry.
 
> writefln("\nNew Fruits");
> fruits[2] = PLUM;
> foreach( f; fruits) {
> f.eat();
> }
> 
> return 0;
> }

A question of style but still important. PLUM is a type, a class, and that
is usually written with only one uppercase letter: 'Plum". All caps are
usually constants. It's a useful convention.
 
> ----------------------------
> module FruitClass;
> import Apple;
> 
> static this()
> {
> Fruit[] fruits=[APPLE,APPLE];
> //with more fruits it would become something like
> //Fruit[] fruits = [APPLE, PEAR, APPLE, APPLE, PEAR, PLUM];
> }

I'd recommend against importing Apple here. The FruitClass module defines
the more general type, what kind of a thing a fruit is. Intuitively, to do
this, it should not depend on knowledge of specific kinds of fruits. The
issue here is that the module FruitClass does two things: define what
fruits are and store a bunch of specific fruits in an array. I think it's
better to move the fruits to main where they are processed. This way, when
you define a new kind of fruit, you don't have to modify the fruitclass
module. 
More generally speaking, here you have a circular dependency. FruitClass
depends on Apple, and Apple depends on FruitClass. The more such
dependencies you have, the more different pieces of code you have to modify
whenever you want to change something and the less flexible it becomes.

...
 
> ----------------------------
> module Apple;
> import FruitClass;
> 
> class APPLE : Fruit
> {
> bool eaten=false;
> 
> void trowAway()
> {
> //how do you delete yourself?
> }
> 

Indeed, usually one doesn't delete oneself ;) Think about it this way: who
is responsible for what? The fruit can very well remember when it's eaten
or not, that's how you have implemented it. It's a property of a fruit. But
it's not up to the fruit to get rid of itself, that should be the
responsibility of the one who owns the fruit. Thus, throwAway() might not
belong in this class.





More information about the Digitalmars-d-learn mailing list