سؤال

While reading about abstraction, I came across the following statement

"Abstraction captures only those details about an object that are relevant to the current perspective"

For eg. From the driver's perspective, Car class would be

  public class Car
  {
     void start();
     void applybrakes();
     void changegear();
     void stop();
   }

From the mechanic's perspective, Car class would be

  public class Car
  {
     void changeOil();
     void adjustBrakes();
   }

My question, While designing a system, do we design for one user perspective(either driver or mechanic) or can we design for multiple user perspective and further abstract out based on user type?

Hope my question is clear.

Thanks

هل كانت مفيدة؟

المحلول

Depending on your use case you might need to deign for multiple users. In your example, if your car will be used by both the mechanic and the driver, then you cannot just ignore one set of users. In that case, you can still abstract details by using Interfaces.

You could design your object like this:

interface IDrivable {
    void start();
    void applyBrakes();
    void changeGear();
    void stop();
}

interface IFixable {
    void changeOil();
    void adjustBrakes();
}

public class Car : IDrivable, IFixable {
    // implement all the methods here
}

Now, when a mechanic wants the car, you don't give him a Car object, instead give him an IFixable object. Similarly, the driver gets an IDrivable object. This keeps the relevant abstraction for both sets of users simultaneously.

class Driver {

    private IDrivable car;

    public Driver(IDrivable car) {
        this.car = car;
    }

    public driveCar() {
        this.car.start();
        this.car.accelerate();

        //this is invalid because a driver should not be able to do this
        this.car.changeOil();
    }
}

Similary, a mechanic won't have access to the methods in the interface IDrivable.

You can read more about interfaces here. Even though this is the MSDN link and uses C#, all major languages support interfaces.

نصائح أخرى

I think you may be inferring too much from "perspective." I wouldn't take perspective here to mean a person or user so much as a vantage point. The idea of a view here is maybe not even a good metaphor. What we're really talking about here is division of responsibility between the smaller objects that we use to compose the larger objects.

The whole point of this idea is decoupling and modularity. You want objects that you can pull out and replace without changing everything around them. So you want your objects to be coherent, for their methods and variables to be closely related.

You might be able to get some mileage from the user metaphor in terms of the interface-client relationship between objects.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top