Required Reading: "How Non-Member Functions Improve Encapsulation"

Jonathan M Davis newsgroup.d at jmdavisprog.com
Mon Oct 30 20:05:51 UTC 2017


On Monday, October 30, 2017 14:18:56 Steven Schveighoffer via Digitalmars-d 
wrote:
> On 10/30/17 1:40 PM, H. S. Teoh wrote:
> > Page 2 of this article is essentially another reason why UFCS in D
> > totally rawkz.  In D, we can take Scott's advice *without* suffering
>
> > from syntactic inconsistency between member and non-member functions:
> You're missing a key piece here, in that anotherMethod does not ensure
> the encapsulation of C. It can call 'method' just fine.
>
> Yes, it's great that UFCS can help with encapsulation via external
> methods, but it's going to be difficult to prevent access to private
> data, you have to use 2 modules. Not a very clean solution IMO.

Yeah, UFCS helps this whole concept, but the way that private works in D
means that compiler-enforced encapsulation simply doesn't happen at the type
level.

Another thing to think about is that private is private to the module rather
than the class or struct partly on the theory that you should be able to
keep track of everything in the module and maintain it appropriately so that
things like whether the type is fully encapsulated aren't really an issue. I
expect that that logic is mainly the justification for not implementing
friend as opposed to the actual reason, but it does pretty much fly in the
face of the idea that you need to be so worried about encapsulation that you
use free functions to prevent a function from accidentally using a private
member.

Still, UFCS does mean that it's less jarring to make something a free a
function, and it then fits well with the cultural push we have to make
functions generic, in which case, they're generally going to be free
functions. But the gains from making something generic are clear, whereas
the encapsulation gains of using a free function with UFCS are far less
substantial, if they exist at all.

- Jonathan M Davis



More information about the Digitalmars-d mailing list