Derived class and override method with derived arguments: how is it better to code it?

I have a question about derivation, polymorphism and method signature

I have a class

public abstract class PaymentMethod { public abstract float GetSalary (Employee employee,Vehicule vehicule) } 

and two others

 public class MarinePaymentMethod : PayementMethod { public override float GetSalary (Sailor sailor,Boat boat) } public class AirPaymentMethod : PayementMethod { public override float GetSalary (Pilot pilot,Plane plane) } 

Assume also that:

 public class Sailor : Employee{} public class Pilot : Employee{} public class Boat: Vehicule{} public class Plane: Vehicule{} 

So, the β€œproblem” is that this code does not compile because the signatures do not match.

I can save the basic signature of GetSalary (Employee employee, vehicleule vehicleule)

and then I have to use the derivative payment method so that I can use certain members of Pilot , Sailor , Boat , Plane in this particular payment method.

My first question is: is it really a bad smell?

My second question: how to make more elegant code design? I thought about Generics and created a class like this:

 public abstract class PaymentMethod<T, U> where T: Employee where U: Vehicule 

But then in my code I understand that I should use the generic almost everywhere I use the mehod payment class, and it makes the code heavy. Any other solutions?

thanks a lot

+5
source share
1 answer

Personally, I would do it as follows:

 public abstract class PaymentMethod { public decimal GetSalary(Employee employee, Vehicle vehicle) { return GetSalaryImpl(employee, vehicle); } protected abstract decimal GetSalaryImpl(Employee employee, Vehicle vehicle); } public class MarinePaymentMethod : PaymentMethod { public decimal GetSalary(Sailor sailor,Boat boat) { throw new NotImplementedException(); /* your code here */ } protected override decimal GetSalaryImpl(Employee employee, Vehicle vehicle) { return GetSalary((Sailor)employee, (Boat)vehicle); } } public class AirPaymentMethod : PaymentMethod { public decimal GetSalary(Pilot pilot, Plane plane) { throw new NotImplementedException(); /* your code here */ } protected override decimal GetSalaryImpl(Employee employee, Vehicle vehicle) { return GetSalary((Pilot)employee, (Plane)vehicle); } } public class Employee {} public class Vehicle{} public class Sailor : Employee{} public class Pilot : Employee{} public class Boat: Vehicle{} public class Plane: Vehicle{} 

This then works for both polymorphism approaches and overloading - although it is unusual that the method that Employee accepts requires a certain type of employee.

+1
source

Source: https://habr.com/ru/post/1209220/


All Articles