Do non-member functions improve encapsulation in D?

via Digitalmars-d digitalmars-d at puremagic.com
Mon Apr 21 06:03:48 PDT 2014


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.

Unless you write libraries the primary goal with encapsulation is 
not reuse, but being able to evolve, modify, refactor, optimize. 
So having a local wrapper on top of a generic function or just 
make it local until you need it somewhere else is quite 
acceptable IMO. (But whether it is inside the class or not is 
mostly syntactical?)

I've one time too many done too early refactoring under the 
assumption that it would lead to better, resusable code. It 
seldom does. It often leads to a wasted design effort, less 
intuitive function names and more fragmented code that is harder 
to understand later on.

Ola.


More information about the Digitalmars-d mailing list