Question

what is an empty method and how are they used?

I was reading a documented about the BUILDER Pattern and I got a curious about how it is implemented in C++. The author defines that in C++ could be possible to implement empty methods as default in the builder pattern in order to letting clients override only the operations they're interested. Someone may explain me that sentence in more details with some example.

Thank you

Était-ce utile?

La solution

An empty method is just a method, which is to say a function that's part of a class, that doesn't do anything other than perhaps returning some default value.

The author defines that in C++ could be possible to implement empty methods as default in the builder pattern in order to letting clients override only the operations they're interested.

It sounds like this just means that there was some basic implementation of some interface using a base class that had a number of empty methods that are called at interesting points. An empty method is basically a NOOP -- there's something there to call, but it doesn't do anything, so execution just continues. A subclass could then override any of those methods to do something interesting, but wouldn't have to implement any methods that aren't needed. Without that base class, anyone implementing the interface would have to provide all the required methods, even if most of them don't do anything.

Autres conseils

Suppose you had an abstract class called BatchHandler with three methods:

virtual void OnInit()

virtual void OnItem(Item e)

virtual void OnEnd()

If these methods were not empty but merely declared, any non-abstract class deriving from BatchHandler would have to implement all three methods regardless of whether or not they use them.

If instead you declared all three as empty, the derived class can override the method he or she chooses. I believe the author was simply stating that empty methods are the default, so that you would not need to necessarily declare them as such explicitly.

Licencié sous: CC-BY-SA avec attribution
scroll top