Hi, Iām trying to understand how I could create readable as well as prevent Fluent-API errors without any special restrictions for the user.
to keep it simple, let them say that we want to change the next class to be free
public class Car { public int Gallons { get; private set; } public int Tons { get; private set; } public int Bhp { get; private set; } public string Make { get; private set; } public string Model { get; private set; } public Car(string make, string model) { Make = make; Model = model; } public void WithHorsePower(int bhp) { Bhp = bhp; return this; } public void WithFuel(int gallons) { Gallons = gallons; } public void WithWeight(int tons) { Tons = tons; } public int Mpg() { return Gallons/Tons; } }
the problem in this case is the user should have access only to Mpg() if Weight() and Fuel() received the call first, and the position of HorsePower() does not matter.
Samples:
int mpg =Car.Create().HorsePower().Fuel().Weight().Mpg(); int mpg =Car.Create().Fuel().HorsePower().Weight().Mpg(); int mpg =Car.Create().HorsePower().Fuel().HorsePower().Weight().Mpg();// <- no typo int mpg =Car.Create().Fuel().Weight().HorsePower().Mpg(); int mpg =Car.Create().Weight().HorsePower().Fuel().Mpg(); int mpg =Car.Create().Weight().Fuel().Mpg();
Is there an easy way to do this without a lot of interfaces?
I also do not know how to properly implement these nested interfaces.
Below are the interfaces I created
interface Start { IFuelWeight1 HorsePower(); IHorsePowerWeight1 Fuel(); IHorsePowerFuel1 Weight(); } interface IFuelWeight1 // Start.HorsePower() { IHorsePowerWeight1 Fuel(); IHorsePowerFuel1 Weight(); } interface IHorsePowerWeight1 // Start.Fuel() { IHorsePowerWeight1 HorsePower(); IHorsePowerFuelMpg Weight(); } interface IHorsePowerFuel1 // Start.Weight() { IHorsePowerFuel1 HorsePower(); IHorsePowerWeightMpg Fuel(); }
EDIT for Adam Haldsworth :-)
- Is the interface higher than good or is there an easier way to do this , but keep the constraint for Mpg ()?
How to implement the interface above to do this?
var k = myMiracle as Start; k.Fuel().Weight(); k.Weight().Fuel(); k.HorsePower().Fuel().Weight(); k.HorsePower().Weight().Fuel(); k.Fuel().HorsePower().Weight(); k.Weight().HorsePower().Fuel();
c # fluent-interface fluent
WiiMaxx
source share