Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fluent C# Builder

Tags:

c#

fluent

Wanted to write some fluent like this...

new Actor().DoSomething<Type>().WithOption(options).When(Conditions);

I understand method chaining and how to pass action to subsequent method / object.

For example, action of DoSomething will be passed to object containing WithOption method and action of withOption passed to the object containing When method.

It could be something like

interface Actor {
  ActorOption DoSomething<T>();
}

interface ActorOption {
  ActorCondition WithOption();
}

interface ActorCondition{
  void When();
}

So actual action happens in WHen method. All are fine so far.

To execute the code with default option or no condition, it could be called as new Actor.DoSomething<T>().WithDefaultOption().Always();

My worry is what if someone leaves the code in middle, which means new Actor.DoSomething<T>(). It appears the actor is supposed to do something, which is fluently right.

I am not able to think of design which can cover similar scenario. Please suggest.

PS: I am writing wrapper over some third party class, so I do not have full control on internal implementation. For example, I cannot set condition once options are set or vice versa.

like image 430
hungryMind Avatar asked Jul 04 '26 22:07

hungryMind


1 Answers

if you write

new Actor().DoSomething<Type>().WithOption(options).When(Conditions);

You could write alternative:

Actor actor = new Actor();
doResult = actor.DoSomething<Type>();
optionResult = doResult.WithOption(options);
conditionResult = optionResult.When(Conditions);

So you can see that your options and your condition added after you execute DoSomething, so it have no effect for the method DoSomething. If you execute your code finally in the When method, it is not intuitive. Better you prepare your actor and get your result with executing DoSomething() ("lamda-style").

And if someone leave some method calls.. Yeah of course then its missing... If it is necessary, you have to add it as a parameter in DoSomething. If not, you have to define default options, which are used if no options specified.

like image 61
Mitja Avatar answered Jul 07 '26 12:07

Mitja



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!