Introduce Local Extension

A server class you are using needs several additional methods, but you can't modify the class.

Create a new class that contains these extra methods. Make this extension class a subclass or a wrapper of the original.

image/svg+xml Client Class nextDay(:Date) : Date MfDate nextDay(:Date) : Date Date

Additions

Using Free Functions in C++

Andy Glew

I comment on this in the light of the recent comp.lang.c++.moderated discussion of using object.method() or free functions, possibly friends, in a class interface. I.e. this comment is more C++ oriented than Java oriented.

Briefly, if the original class used free functions for this sort of interface, the assymmetry introduced by wrapping a class's object.methods() would not exist. In C++

    class MfDateSub {
        private: Date _original;
        // wrapping the symmetric operator after(date1,date2)
        public:  friend bool after (MfDateSub arg1, MfDateSub arg2) {
            return after(arg1._original,arg2._original);
        }
        public:  friend bool after (MfDateSub arg1, Date arg2) {
            return after(arg1._original,arg2);
        }
        public:  friend bool after (Date arg1, MfDateSub arg2) {
            return after(arg1,arg2._original);
        }
   };

Now all combinations work; the wrapping is more invisible to the user.

Even better if the free function after(date1,date2) does not require friendship --- although the definition of the extensions gets spread into a few more places.

Note that in the example above, however, an implicit conversion of a MfDateSub value to a Date would suffice.

    class MfDateSub {
            operator Date() const { return _original }
    }

although this approach cannot always work, e.g. when there is extra data to be compared in the extension.

CONCLUSION: using free functions in an interface allows a greater degree of syntactic transparency when wrapping.

Return type for extra methods

Dmitri Colebatch wrote in to ask why when using the subclass I didn't return the subclass in the extra methods. So I have added the nextDay method to MfDate, but it returns a Date not an MfDate. I can't think of any good reason to return the superclass, so I agree with him and suggest returning MfDate instead. The same is true for the wrapper implementation as well. After all if the client is using the extra method, they are aware of the new class. This way they avoid having to futz with the returned object if they want to invoke other extension methods.