Encapsulation C# Best practices

851 views Asked by At

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);
    }
}
2

There are 2 answers

0
Dmitriy Dokshin On

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.

2
MakePeaceGreatAgain On

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