I can’t come up with a “better” way to handle the following situation - basically, I have a bunch of stored objects that inherit from the base type and would like to get them from the repository, find its subtype (possibly via "if (x is y)" ), and then act accordingly - some of them use a common implementation, others with dedicated logic and representations.
I think [truncated] it will look something like this:
/vehicle/details/1234
- Views
- Vehicle
- Details.aspx
abstract class Vehicle{
public int ID{ get; }
}
class Motorbike : Vehicle{
}
class Car : Vehicle{
public int NoOfDoors{ get; }
}
class VehicleController : Controller{
VehicleRepository _vehicleRepository;
public ActionResult Details(int id){
var vehicle = _vehicleRepository.Get(id);
}
}
Now, if we don’t worry about future expansion and maintenance, and all of this, we can go the dark way and implement something like the following - which will function normally, but will undoubtedly be an [absolute] nightmare.
- Views
- Vehicle
- Details.aspx
- CarDetails.aspx
public ActionResult Details(int id){
var vehicle = _vehicleRepository.Get(id);
return (vehicle is Car) ? DetailsView((Car)vehicle) : DetailsView(vehicle);
}
private ActionResult DetailsView(Car car){
var crashTestResults = GetCrashTestResults(car);
var carData = new CarDetailsViewData(car, crashTestResults);
return View("CarDetails", carData);
}
private ActionResult DetailsView(Vehicle vehicle){
var vehicleData = new VehicleDetailsViewData(car, crashTestResults);
return View("Details", vehicleData);
}
- , , ...
- Views
- Vehicle
- Car
- Details.aspx
- Motorbike
- Details.aspx
public ActionResult Details(int id){
var vehicle = _vehicleRepository.Get(id);
return View(vehicle.GetType().Name + "\Details", vehicle);
}
, , , , , , ...
, , , "VehicleController" , , .
.