The final example has signature List<Product> but tries to return IOrderedEnumerable<Product>.
I recognise that this is very much a taster rather than even a full introduction, so the author didn't want to explain IOrderedEnumerable<T>, but please when writing blogs, run through your code examples and make sure they compile.
This means that your audience can follow along.
( It just needs a .ToList() on the end. )
The author stating that the lambda is "better" because it's less lines is also silly. It's been a while since I've written C#, but pretty sure the SQL-like version can be formatted to a single line as well:
List<Product> GetExclusiveProducts(List<Product> source) => (from p in source where p.ProductTitle == "iPhone" orderby p.TypeOfPhone select p).ToList();
What's important to me is that I can understand the intent of the code, that I can reason about how that code will be executed at runtime, and that I can easily debug the code if needed.
Of course, there's no need to go full enterprise Java. Never go full enterprise Java.
But having ten lines of clear code that's easily debuggable and which runtime characteristics is predictable is much better than one dense line that's difficult to untangle, or a few that's hard to predict what will do etc.
I have a couple of samples that I think might surprise you if you think C# must look like Java...
* A game of pontoon [2] - I create a Game monad which is an alias for a monad-transformer stack of StateT > OptionT > IO. This shows how terse you can get, where the code almost turns into a narrative.
* Newsletter sender [3] (which I use for my blog) [4] - This generalises over any monad as long as the trait requirements are met. This is about as declarative as you can get in C#. It's certainly pushing the language, but is still elegant (in my eyes anyway).
[1] https://github.com/louthy/language-ext
[2] https://github.com/louthy/language-ext/blob/main/Samples/Car...
[3] https://github.com/louthy/language-ext/blob/main/Samples/New...
IEnumerable<Product> GetExclusiveProducts(List<Product> source) =>
source
.Where(p => p.ProductTitle == "iPhone")
.OrderBy(p => p.TypeOfPhone);
That way the user can decide if they want a List or Array or Set or whatever, and you can also add additional queries to thisAlso better to pass IEnumerable to the function instead of List, for the same reasons
Also I forget the syntax but you can use an extension method to add it to linq I think
Cases where it isn't:
- risk of multiple execution (there is a CA warning for this)
- when returning data protected by a mutex, you should always materialize a copy of the returned list/array rather than return an enumerable
So from an API perspective, I think returning IEnumerables can end up being too cute. The caller has to deal with this unknown thing.
In general you should be clear about what you return and loose about what you accept. If your whole API is returning IEnumerables and some are expensive to iterate and others are not its actually less clear what I'm getting. And this isn't to say List is always the answer either.
In performance-critical code at the time it had to be avoided due to allocations and poor performance compared to loop-based implementations.
However, the new versions of .NET have been reducing this penalty [1], to the point where it might make sense to try LINQ first if it's more concise/clear then only rewrite after profiling!
[1] https://devblogs.microsoft.com/dotnet/performance-improvemen...
... and then the author proceeds to presenting clunky, unreadable fluent syntax
That was a good joke for the afternoon.
Or are you suggesting that the majority of programmers struggle to read and understand fluent method chaining?
I don’t have a dog in this fight because this blog post is very novice oriented. I’m just genuinely confused why you think it’s unreadable or “clunky”. What is it about the fluent example that you find clunky?
Writing your own LINQ provider is a very niche activity done by people who want to translate or “transpile” C# expression trees into something else.
It is fundamentally a difficult endeavor because you’re trying to construct a mapping between two languages AND you’re trying to do it in a way that produces efficient target code/query AND you’re trying to do that in a way that has reasonable runtime efficiency.
Granted, on top of that, I’m sure LINQ provider SDKs probably add their own complexity, but this isn’t an activity that C# developers typically encourage.
List<Product> GetExclusiveProducts(List<Product> source)
=> source
.Where(p => p.ProductTitle == "iPhone")
.OrderBy(p => p.TypeOfPhone)
.ToList();
(You could join the first two lines, but I think that’s ugly for multi-line expressions.)Also, less lines is not a good argument for SQL-style syntax vs method-call syntax. The good argument is that the SQL-style syntax is limited to only a few basic operations, when there are many more useful methods available.
Another reason is that this does not compile:
List<Product> GetExclusiveProducts(List<Product> source)
{
return from p in source
where p.ProductTitle == "iPhone"
orderby p.TypeOfPhone
select p;
}
This method returns IOrderedEnumerable<Product>, not a list. To fix it, you would need to either change the return type, or go outside of the SQL-style syntax and call the ToList method: return (from ... select p).ToList();
This is a very unfortunate joke: Python has list (and generator) comprehension expression for a long time (2.3?) which are similar to LINQ. At some point in the history many languages stole useful expressions from other paradigms.
Let’s joke on BASIC, it always works.
Looking at that 'one-liner' I get strong perl vibes, or is it chills?..
bob1029•1w ago
I think C# is the best functional programming language because you always have access to a procedural code safety valve if the situation calls for it.
100% purity down the entire vertical is a very strong anti-pattern. You want to focus on putting the functional code where it is most likely to be wrong or cause trouble (your business logic). Worrying about making the underlying infrastructure functional is where I start to zone out.
Does F# care if a DLL it references was coded in a functional style?
louthy•1h ago
It really isn't. The benefit of pure all the way down is that later you can replace bits with something more performant if necessary. But starting out with the idea that some bits should never be pure just means none of it is. The beauty of pure functional programming is that its very compositional nature means that you can replace a component without having a detrimental effect to everything its composed with: as long as you maintain referential transparency for that component.
What we gain from imposing the pure functional constraints on ourselves is genuine composition. If we compose two pure functions into a new function, that resulting function will also be pure. This is the pure functional programming super power that leads to fewer bugs, easier refactoring, easier optimisation, faster feature addition, improved code clarity, parallelisation for free, and reduced cognitive load. Opting out for arbitrary reasons at certain stages of the vertical threatens all of that.
mrkeen•37m ago
"Pure functional" isn't a style choice. The judges won't hold up big placards with 10 on them because you executed your business logic in style.
It's a contract that your code will give the same output given the same input. The contract goes both ways: your ability to supply a caller with functional code is made easier by your callees supplying you with functional code.
Someone decides that that's draconian and says "what's the worse that can happen?" and starts mutating in a library dependency. Well now your backtracking parser may or may not be able to backtrack. Your transactional code may or may not be able to be rolled back. Your multi-threaded code may or may not be free of races. `true || f()` no longer means the same thing as `true`. You might need to start scaffolding all your unit tests with @Before and @After to setup and teardown state, and give up running them in parallel.
Maybe you really, really, really need to fire the missiles at the bottom of the call chain. Fine, just mark that method as 'red' so I get a compiler error when I try to serve up 'blue' code to my callers.
As long as you're showing off the syntax (matter of taste) on blog posts you might as well get some mileage out of the semantics (guarantees).
pjc50•28m ago
"Functional core, imperative shell" is a great tradeoff position though.
>> Does F# care if a DLL it references was coded in a functional style
Deeper problem: it can't know. It can only assume. I'd have to check how the loader works but it may be the case that "first call to a function in an external DLL" is not stateless (and can error!) because it triggers the linker.
jayd16•20m ago
I really love C# but I will also say that 100% purity is a super power that C# will never have (can't have 'em all).