UFCS for arguments other than first?

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Fri Nov 11 15:27:30 PST 2016


On Friday, November 11, 2016 22:48:24 Heisenberg via Digitalmars-d wrote:
> Isn't the whole point of UFCS implementation in providing better
> re-usability and scalability, helping the encapsulation, making
> the chaining of function calls easier?

The primary benefit of UFCS is so that generic code can call a function
without caring whether it's dealing with a member function or a free
function, allowing you to declare free functions to act like member
functions for types that are lacking the member function in question or
allowing a member function to provide a specialization of a more general
free function in cases where the type could implement the function more
efficiently than the general implementation would be (e.g. a sorted,
random-access range could implement find itself to do binary search, or if a
range were backed by a binary tree, it could implement find to do a lookup
rather than searching linearly).

The secondary benefit that leads many folks to want to use UFCS is that they
find it easier to read code when the functions are chained with . rather
than by nesting function calls in the normal manner, but that's a matter of
preference rather than providing any actual technical benefit. If the
function is a free function, then it really doesn't matter whether you use
UFCS or not with regards to what the code does or your ability to chain
function calls. It's just personal preference based on what you find easier
or harder to read.

As for reusability and scalability, I don't see how UFCS has any impact on
those at all. Making a function be a generic free function can help with
that, but that doesn't require that you use UFCS. Similarly, if you want to
encapsulate code by using free functions rather than member functions, UFCS
isn't required, and if all you're doing is turning a member function into a
free function that takes that type (as opposed to making the function
generic), then it doesn't even improve encapsulation unless its in a
different module, because everything inside of a module has access to
everything else within a module.

Ultimately, the only technical benefit from UFCS is that it allows you to
call a function without caring whether it's a member function or a free
function, which is of great benefit to generic code and not really much
else. Otherwise, it's just a syntactic preference - albeit one that many
people prefer.

- Jonathan M Davis



More information about the Digitalmars-d mailing list