简体   繁体   中英

Encapsulation C# Best practices

just for clarification and for good code practices. I understand the concept of encapsulation, but can you tell me the difference between these two codes and in which scenario would you use them. Thanks. PS: I am not looking for links answers, I just want your honest opinion.

Code 1:

class Program
{
    static void Main(string[] args)
    {
        Car ObjCar = new Car();
        printVehicledetails(ObjCar);
    }

    private static void printVehicledetails(Vehilce vehicle) 
    {
        Console.WriteLine("Here are the Vehicles' details: {0}", vehicle.FormatMe());
    }
}

abstract class Vehilce
{
    protected string Make { get; set; } //here
    protected string Model { get; set; } //here

    public abstract string FormatMe();

}

class Car : Vehilce
{

    public override string FormatMe()
    {

        return String.Format("{0} - {1} - {2} - {3}", Make, Model);
    }
}

Code 2:

class Program
{
    static void Main(string[] args)
    {
        Car ObjCar = new Car();
        printVehicledetails(ObjCar);
    }

    private static void printVehicledetails(Vehilce vehicle) 
    {
        Console.WriteLine("Here are the Vehicles' details: {0}", vehicle.FormatMe());
    }
}

abstract class Vehilce
{
    public string Make { protected get; protected set; } //here
    public string Model { protected get; protected set; } //here

    public abstract string FormatMe();

}

class Car : Vehilce
{

    public override string FormatMe()
    {

        return String.Format("{0} - {1} - {2} - {3}", Make, Model);
    }
}

There is a common approach: separate data and logic. In that case you should make properties public (maybe with private setters) and put formatting somewhere else, for example, in extension method.

That totally depends on your context, wheather you need to access the properties from outside of any derived class or not. That´s the only difference on them, in last case you can access the properties only within Vehicle -class, wheras in the first you can access them from anywhere.

Btw.: Providing a access-modifier for both getter AND setter for a property will result in the following compile-time error.

"Cannot specify accessibility modifiers for both accessors of the property..."

The following works however:

protected string Make { get; set; } //here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM