Classes (does this make sense?)

Lutger lutger.blijdestin at gmail.com
Tue Jun 3 03:00:54 PDT 2008


Saaa wrote:
///
> Why is an interface better than a abstract class?
> Where should I store the number (it should have been called color, my bad
> )? Every fruit has the color variable.

Interfaces may have these benefits:
- it is possible for a class to implement more than one interface
- implementation is completely seperate from the interface. This can lead to
more flexible code. Further, it means that the implementation is in one
place, which is easier to maintain. 

When you make color a property, it's variable must be stored in the classes
that implement IFruit: Apple, Plum, etc, and would be a private field. 

Here is an example of how that could have some advantage:

class Apple : IFruit
{

    int color()
    {
        return _color;
    }    
        
    void rot()
    {
        _color = BROWN; 
    }   

        
    private int _color = GREEN; // GREEN is defined elsewhere
}

In this implementation, only inside the Apple class can the color be
changed. This means that, when that code is correct color can be guaranteed
to always be in a valid state. Alternatively a setter can be implemented
that checks for valid input:

void color(int clr)
{
    if ( ! (clr == BROWN || clr == GREEN || clr == YELLOW) )
        throw new Exception("invalid color for Apple");
    _color = clr;
}

Yet another way to keep color always correct is to use an invariant:

class Apple : IFruit
{
    invariant()
    {
        assert(clr == BROWN || clr == GREEN || clr == YELLOW, 
               "Apple's color is invalid");
    }
}

When compiled with -unittest, the invariant is checked before and after
every function in Apple is executed.


More information about the Digitalmars-d-learn mailing list