Search code examples
ooptddprivate

Examples in Test Driven Development By Example by Kent Beck


I'm reading through Test Driven Development: By Example and one of the examples is bugging me. In chapter 3 (Equality for all), the author creates an equals function in the Dollar class to compare two Dollar objects:

public boolean equals(Object object)
{
    Dollar dollar= (Dollar) object;
    return amount == dollar.amount;
}

Then, in the following chapter (4: Privacy), he makes amount a private member of the dollar class.

private int amount;

and the tests pass. Shouldn't this cause a compiler error in the equals method because while the object can access its own amount member as it is restricted from accessing the other Dollar object's amount member?

//shouldn't dollar.amount be no longer accessable?
return amount == dollar.amount

Am I fundamentally misunderstanding private?

UPDATE I decided to go back and code along with the book manually and when I got to the next part (chapter 6 - Equality For All, Redux) where they push amount into a parent class and make it protected, I'm getting access problems:

public class Money
{
    protected int amount;
}

public class Dollar : Money
{
    public Dollar(int amount)
    {
        this.amount = amount;
    }
    // override object.Equals
    public override bool Equals(object obj)
    {
        Money dollar = (Money)obj;
        //"error CS1540: Cannot access protected member 'Money.amount'
        // via a qualifier of type 'Money'; the qualifier must be of 
        // type 'Dollar' (or derived from it)" on the next line:
        return amount == dollar.amount;
    }
}

Does this mean that protected IS instance-based in C#?


Solution

  • Yep, you're fundamentally misunderstanding private. Privacy is class-specific, not instance-specific.