Do non-member functions improve encapsulation in D?

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Mon Apr 21 05:45:12 PDT 2014


On Sun, 20 Apr 2014 03:11:39 -0400, Lars T. Kyllingstad  
<public at kyllingen.net> wrote:

> 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?

First, you rightly destroy the main reason for making a module-level  
function vs. a method for D -- module-level functions have access to the  
private data. Therefore, the motivation to make a module-level function is  
significantly diminished. In my opinion, I would say that you should  
always first try making them methods, but under certain cases, you should  
make them functions.

Reasons off the top of my head not to make them module functions:

1. You can import individual symbols from modules. i.e.:

import mymodule: MyType;

If a large portion of your API is module-level functions, this means you  
have to either import the whole module, or the individual methods you plan  
to use.

2. You can get delegates to methods. You cannot get delegates to module  
functions, even if they are UFCS compatible.

3. There is zero chance of a conflict with another type's similarly named  
method.

4. It enforces the "method call" syntax. I.e. you cannot use foo(obj)  
call. This may be important for readability.

5. You can only use operator overloads via methods. D is different in this  
respect from C++.

6. The documentation will be grouped with the object itself. This becomes  
even more critical with the new doc layout which has one page per type.

Reasons to make them module functions:

1. You have more than one object in the same file which implements the  
method identically via duck typing.

2. You want to change how the 'this' type is passed -- in other words, you  
want to pass a struct by value or by pointer instead of by ref.

3. The complement to #1 in the 'against' list -- you want your  
module-level API to be selectively enabled!

4. Of course, if you are actually implementing in a different module,  
Scott Meyers' reasoning applies there.

-Steve


More information about the Digitalmars-d mailing list