5 ms·
Typically, boiler plate implemented by a standalone function is not easily discoverable, eg. no clear convention where to put it, does not look idiomatic on som
by tuyiown 3y ago
Typically, boiler plate implemented by a standalone function is not easily discoverable, eg. no clear convention where to put it, does not look idiomatic on some usages syntax habits, and not suggested by auto completion in top results.
Extensions are searchable by syntax and naturally in a namespace, largely diminishing the risk of put it in in a single use function that will be quickly forgotten, and might seem obscure.
The code itself might not be much shorter, but you don't introduce code looking weird, if it's re-usable it's now discoverable, and if your boilerplate contained a lot of micro adjustments on a larger glue code, this glue code is now shorter and way clearer.
- rogerkeays 3y agoAlso, creating a subclass just to add extension methods is definitely boiler plate. Util classes too, though they are useful for packaging functions at least.
- kaba0 3y agoSubclassing may not always be possible (final class, or method) and can break class invariants. Util classes with helper methods and/or extension methods are not prone to these problems.
- rogerkeays 3y agoYes, inheritance is a nightmare!
- misja111 3y ago> Extensions are searchable by syntax This would be very useful. But how are these extension methods more searchable by syntax than the 'old fashioned' static util methods? I admit I haven't tried, but I suspect that code completion in my IDE wouldn't include these extension methods.
- sjrd 3y agoAt least in Scala, code completion in the IDE does include available extension methods.
- jdmichal 3y agoThey're more discoverable, because typing in `object.` tells the IDE that you are looking for methods on the type of `object`. If the IDE is aware of extension methods, it can also expose them the same as instance methods. Java specific: If you're looking for a static utility method, then `UtilClass.` will also autocomplete. However, what if the function you're looking for isn't in `UtilClass`, but `SomeOtherClass`? What if you don't even know whether a method already exists for what you're trying to accomplish, and it could possibly exist in multiple libraries? Your discoverability engine quickly becomes Google.