David DeMar
David DeMar

Reputation: 2670

Would this sort of method chaining be frowned upon in C#?

Say I have this code:

Foo foo = new Foo();
foo.Bar();

Would it be considered bad practice to do this instead?

new Foo().Bar();

Upvotes: 0

Views: 119

Answers (4)

Arvin Yorro
Arvin Yorro

Reputation: 12175

I find that a good practice.

One of the refactoring techniques is to remove the intermediate variable when used only once as long as the intention is obvious.

Introduce a variable only when the expression becomes complicated. The variable helps the code become self documenting.

IPizza hawaiianPizza = new PizzaBuilder()
    .AddCheese()
    .AddMushroom()
    .AddPineapples();

Upvotes: 2

Alexei Levenkov
Alexei Levenkov

Reputation: 100620

This is pretty common.

Fluid interfaces. You sample new up object from nowhere - functions used strictly for side effects are generally not welcome as they are harder to reason about. Usually it used to either start with existing object and modify its properties:

getMyItem(itemId).Width(42).Height(33).Open();

or build some item:

var result = new Builder().Width(42).Height(44).Create();

Another example is LINQ - you chain many queries to get result - again you usually use result but may just use for side effect.

Start with something and use result

var filteredSquares = myArray.Select(x => x * x).Where(r => r < 1000); 

Strictly side effects (ignore results):

Enumerable.Range(1,10).Select(x => x * x).Aggregate(0, (c,x)=> 
    {
       Console.Write(x); // side effect
       return 0; // to make Aggregate happy
    });

Upvotes: 3

Brian Rasmussen
Brian Rasmussen

Reputation: 116481

If you're not passing any state to the constructor, then the method could most likely be made static and then the call would probably not raise any eyebrows.

Upvotes: 1

Simon Whitehead
Simon Whitehead

Reputation: 65087

I do/see that all the time. Its comes from my habit of refactoring large methods into classes. I end up just calling:

new ClassThatWasAMethod(initialization, variables, here).PerformAction();

There is something called the Law of Demeter, that says any more than what you've done there is too "chatty". i.e.:

new Foo().Bar().Baz(); // potentially more

But, a badly named "Law" doesn't make it so. That is to say - you won't go to jail for not following that guideline.

Upvotes: 4

Related Questions