On Sunday, 20 April 2014 at 13:01:53 UTC, Gary Willoughby wrote:
On Sunday, 20 April 2014 at 11:12:42 UTC, Lars T. Kyllingstad wrote:
However, in D, all functions defined in the same module as a class will have access to the private state of that class, on an equal footing with its member methods. Therefore, the above statment doesn't really help in deciding which to use.

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.


Functions which are focused to only deal with data associated with a particular class then these would be better suited to be implemented as a method of that class.

This is the tricky part, an it is where I have a hard time deciding which to use. For example:

    struct File {
        private int fileno;
        void read(ubyte[] buf) {
core.sys.posix.unistd.read(fileno, buf.ptr, buf.length);
        }
    }

Why, or when, is the above preferable to the following?

    struct File {
        private int fileno;
    }
    void read(File f, ubyte[] buf)
        core.sys.posix.unistd.read(f.fileno, buf.ptr, buf.length);
    }

I still haven't heard any fact-based, logical arguments that advise me on which style to use, and so far it seems to be just that -- a matter of style.

There are a few clear-cut cases, such as when a function should be virtual, or when it is part of a predefined interface (e.g. input range), but in the general case one seems just as "encapsulated" as the other.

Reply via email to