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

Walter Bright newshound2 at digitalmars.com
Thu Oct 26 23:29:24 UTC 2017


On 10/26/2017 3:05 PM, Jonathan M Davis wrote:
> As has been pointed out elsewhere in this thread, the encapsulation benefits
> don't exist in the same way in D unless you put the free functions in
> separate modules, and then you have to import other stuff to use them,
> whereas in C++, you can just put the free functions next to the type and
> still get the encapsulation benefits. So, the benefit of splitting the
> functions out within a module is fairly minimal in D. Rather, the main
> reason I see for splitting functions out is in order to make them more
> generic, and I think that the push to do that in D has a tendency to make a
> lot of functions free functions that might have been member functions in
> most other languages.

The point is that functions that do not need access to private fields should NOT 
be part of the class. Most of the discussion here is based on the idea that 
those functions should still be semantically part of the class, even if not 
physically. That idea should be revisited. Why should they be semantically part 
of the class?


You can also do things like:

--- s.d -------
struct S { int x; ref int X() { return x; } }

--- splus.d ----
public import s;
int increment(S s) { s.X() += 1; } // note no access to S.x

--- user.d ----
import splus;
void foo(ref S s) { s.increment(); }


More information about the Digitalmars-d mailing list