Free functions versus member functions

Bruno Medeiros brunodomedeiros+spam at com.gmail
Sat Oct 13 10:47:27 PDT 2007


Walter Bright wrote:
> Continuing the discussion from the thread "questions on PhanTango 
> 'merger'":
> 
> 
> I've been stumped by this design issue before. Should functionality be 
> done as a set of free functions, or as member functions? I remember 
> going over this with Matthew Wilson, and he resolved it by implementing 
> two parallel sets of interfaces: one free, the other member. I thought 
> that doing both was a copout, but couldn't figure out which one was right.
> 
> I eventually ran across this article by Scott Meyers 
> http://www.ddj.com/cpp/184401197
> which made a lot of sense. It gives some good guidelines to use to make 
> such decisions, and backs it up with reasoning that I find compelling.
> 
> Isn't it funny how we've completed the circle? We went from all free 
> functions in C, to all member functions in C++, and now back to free 
> functions? <g>

I don't think I fully agree with some points of that article. He states 
that a function that can be implemented as a "non-friend non-member" 
function instead of a member function, should be implemented that way, 
since it would reduce encapsulation. Well, sorta. Just because a 
function is written as a member function doesn't mean we have to access 
the classes fields directly in that function, one can use the class's 
external API just as if the function was non-member, and thus have no 
decrease in encapsulation.

Second, I think that many times it is useful to have as part of the 
class API certain utility functions (that are not part of the minimal 
set and as such could be implemented as free functions), simply because 
they would be commonly useful. He mentions this aspect in the end of the 
article, but he gives the impression that he thinks including such 
functions is only worthwhile in rare occasions, and that classes should 
always have the minimal set of members, or close to it. I on the other 
hand think that most functions that could be expected to be used often 
should be part of the API. For instance, consider the IPath class of 
Eclipse:
http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/api/org/eclipse/core/runtime/IPath.html
It's a class that represents a path name: a collections of path segments 
plus a device id. I think that class API/interface is ideally defined in 
terms of number of member functions, but according to Meyers, the class 
should have a lot less member functions.

-- 
Bruno Medeiros - MSc in CS/E student
http://www.prowiki.org/wiki4d/wiki.cgi?BrunoMedeiros#D



More information about the Digitalmars-d mailing list