How to attach functions together in C#?

Viewed 58

I am having a hard time understanding this piece of code:

public IObservable<SomeInfo> OriginalFunction() => FirstFunction().SecondFunction(argument1).ThirdFunction(argument2);

First, I don't understand what that IObservable<CarsInfo> means. Does this function return an observable?

Then, what does the lambda => do?

And finally, how are the three functions attached to each other using dots?

1 Answers
public IObservable<SomeInfo> OriginalFunction() => FirstFunction().SecondFunction(argument1).ThirdFunction(argument2);

is equivalent to

public IObservable<SomeInfo> OriginalFunction() 
{ 
    var firstResult = FirstFunction();
    var secondResult = firstResult.SecondFunction(argument1)
    return secondResult.ThirdFunction(argument2); // mind the 'return' here!
}

which by the way expect argument1 and argument2 as class fields or properties, which some people would consider "not so clean"*.

* I should elaborate on that: While clean code advocates for having as small number of arguments as possible, using class fields or properties here does make the function harder to test. I personally would consider this a kind of side-effect which should be avoided. What do I mean by side-effect? Two calls of this function may return different results depending on the value of class fields. This could be reasonable or not. Depends on the actual semantics of the code which is not at all clear from the example.

So, TL;DR: Consider if it is reasonable to use class fields or if it is more reasonable to to use two arguments or use an "Options-Pattern" argument. Take into account: Is it clear what result to expect ("do not surprise clients")? Is the function testable? And some more...


EDIT:

=> is a feature added in C# 6.0 : Expression-bodied function members

Many members that you write are single statements that could be single expressions. Write an expression-bodied member instead. It works for methods and read-only properties. For example, an override of ToString() is often a great candidate:
public override string ToString() => $"{LastName}, {FirstName}";

Related