3 ms·
Why is calling SomeObject.SomeFunc() arguably better than calling SomeFunc(SomeObject)?
by DeathArrow 3y ago
Why is calling SomeObject.SomeFunc() arguably better than calling SomeFunc(SomeObject)?
- mattmanser 3y agoI've used these a lot in C# and it is actually a lot better, and common, to write some extension methods for common operations (e.g. standardized formatting). It's very common to see an "Extensions" folder in a C# project, where these will live. So what you didn't notice is that you if you need to share SomeFunc across classes, you'd have to put it in a static class, so it's actually SomeStatic.SomeFunc(SomeObject) vs SomeObject.SomeFunc(). So you end up with a load of Utility classes with tons of static methods on them, or you do extensions. But mostly the advantage is that it's actually clearer when you're reading the code. It can also add quite a lot to discoverability in the right circumstances, not sure abut Java, but in C# you can include Extensions in global namespaces and so it just turns up in intellisense, without needing to know there's a special utility class. Visual Studio has actually shipped new functionality recently where it will suggest extension methods (and classes) not included in your usings anyway, and then automatically add the using statements if you choose to use them. I thought this new functionality would annoy me but it's pretty clear from the prompt which objects are already in scope, and I only find myself occasionally having to clean up the using statements. TL;DR; Looks a trivial change, but it surpisingly improves the readability of code, and the discoverability of home-grown utility functions.
- sacnoradhq 3y agoYou're oversimplifying the use of continuation / builder pattern / "fluent" / monadic interfaces. SetReadTimeout(SetWriteTimeout(SetConnectTimeout(FactoryClass.factory(), 100), 2000), 4000); vs. FactoryClass.factory().SetConnectTimeout(100).SetWriteTimeout(2000).SetReadTimeout(4000); https://java-design-patterns.com/patterns/fluentinterface/ https://java-design-patterns.com/patterns/fluentinterface/
- rogerkeays 3y agoNice example. The extra parameters really drive the point home. Hope you don't mind if I steal it for the README.
- jdmichal 3y agoOr, in my opinion, even worse... When you get mix-and-match because you want to extend a fluent API. Using your example, what if `SetWriteTimeout` was a static method you wrote, but all the others were provided by library as a fluent API? Then you end up with this kind of unholy mess: SetWriteTimeout(FactoryClass.factory().SetConnectTimeout(100), 2000).SetReadTimeout(4000); Good luck correctly guessing the order of operations on that in a quick read...
- erik_seaberg 3y agoThis, having to remember which methods are implemented inside the class and which ones should have been is almost like the colored function problem.