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.