Do non-member functions improve encapsulation in D?

Lars T. Kyllingstad via Digitalmars-d digitalmars-d at puremagic.com
Mon Apr 21 06:55:24 PDT 2014


On Monday, 21 April 2014 at 13:03:50 UTC, Ola Fosheim Grøstad 
wrote:
> On Monday, 21 April 2014 at 08:33:21 UTC, Lars T. Kyllingstad 
> wrote:
>> On Sunday, 20 April 2014 at 13:01:53 UTC, Gary Willoughby 
>> wrote:
>>> Yeah it does. If the function can be used generically across 
>>> many different parts of the program then it would be much 
>>> better implemented as a non-member function, even if it's 
>>> defined in the same module as an associated class.
>>
>> I agree.  If a function is generally useful outside the 
>> context of a class, it should not be defined in the class.
>
> I think this view is too simple. Even if a function is 
> generally useful you risk ending up with maintenance problems 
> later on when you need to optimize your code. So if in doubt, 
> make it local.

I agree, but I think that's more a question of *when* a function 
is considered "generally useful".  To me, that is when I have an 
actual use case for it beyond the one for which it was originally 
designed, and not just because I think it might come in handy 
some time in the future.  "If in doubt, make it private" is 
always a good guideline.


More information about the Digitalmars-d mailing list