Do non-member functions improve encapsulation in D?

Lars T. Kyllingstad via Digitalmars-d digitalmars-d at puremagic.com
Sun Apr 20 00:11:39 PDT 2014


In his article "How non-member functions improve encapsulation" 
[1], Scott Meyers makes a good argument for why free functions 
should generally be preferred over class methods in C++.  TL;DR: 
Fewer member functions means fewer functions that break when the 
class implementation changes, and free functions can be spread 
across different header files, allowing client code to only 
#include the ones that are needed.

In D, the situation is somewhat different.  Firstly, private 
symbols are accessible throughout the module within which the 
class/struct is defined, and secondly, UFC allows us to call free 
functions using the same syntax as member functions.  In other 
words, *any* non-virtual function could in principle be written 
as a free function.

The fact that "private" really means "module private" in D means 
that any number of functions can break when a class/struct 
implementation changes.  So if we are to take Meyers' advice, we 
have to define a new module for each class/struct, and move its 
associated free functions to neighbouring modules.  However, this 
would lead to a proliferation of modules that I doubt anyone 
would want.

So, can anyone think of some good guidelines for when to make a 
function a member, when to write it as a free function in the 
same module, and when to move it to a different module?


[1] 
http://www.drdobbs.com/cpp/how-non-member-functions-improve-encapsu/184401197


More information about the Digitalmars-d mailing list