473,785 Members | 2,459 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Philosophical question: Template Method

OK, so I've gotten into a philosophical disagreement with my colleague at
work. He is a proponent of the Template Method pattern, i.e.:

class foo
{
public:
void bar() { do_bar(); }
protected:
virtual void do_bar() {}
};

class baz: public foo
{
protected:
virtual void do_bar() {} // overridden
};

As you can see, the non-virtual public method foo:bar() exists only to invoke
the virtual method do_bar, which derivatives of the class can override like a
regular virtual method.

The advantage to this method, my colleague claims, is that future implementors
may change the pre- and post-processing behavior of the virtual do_bar method
(such as adding semaphore acquisition/relinquishment calls before/after the
call to do_bar, respectively) without changing the classes that derive from
foo.

Furthermore, he claims that this separates the decision to make a method
public/private from the decision to make a method virtual--a significant
advantage, he claims.

He has pointed me to articles on C++ Users Journal which seems to support the
Template Method pattern, even going so far as to say that all public virtual
methods should be banned in favor of the Template Method.

See http://www.cuj.com/documents/s=8000/cujcexp1812hyslop/

I, on the other hand, prefer the simple

class foo
{
public:
virtual void bar() {}
};

class baz: public foo
{
public:
virtual void bar() {} // overridden
};

And being a big fan of Java, I also appreciate the Interface pattern:

class foo // interface
{
public:
virtual void bar() = 0;
};

class baz: virtual public foo
{
public:
virtual void bar() {} // implementation
};

Besides, the Template Method can be ruined if a derived class decides that it
needs a different pre- and post-operation for the virtual method...

class foo
{
public:
void bar() { do_bar(); }
protected:
virtual void bar() {}
};

class baz: public foo
{
public:
void bar() { frobnicate(); do_bar(); } // I need something different!
proctected:
virtual void bar() {} // overridden
};

In the above class hierarchy, the two calls...

baz baz_object;
foo& foo_reference(b az_object);
baz& baz_reference(b az_object);

foo.bar();
baz.bar();

....would yield two different call paths.

Of course you can say "don't do that", but I can also say "but I need to
override the default behavior for this class".

So what say you, gentle coders? Are Template Methods worth the hassle? Do they
trade one class of errors for another? Is the convenience of changing pre- and
post-operations at the base class actually masking the fact that we have made
a design error and honestly need to re-examine every descendant class?

The Template Method pattern is not compatible with the Interface method, not
because it can't be done, but because it makes no sense to combine them. Empty
non-virtual public methods whose jobs it is is to simply call pure virtual
protected methods--that's just silly.

So it's one or the other, then. What's the better design paradigm?

Jul 19 '05
11 3626

"David White" <no.email@provi ded> wrote in message
news:E1******** ********@nasal. pacific.net.au. ..
Although, all that tells you is that it's virtual in that class.


....and any derived classes of course.

DW

Jul 19 '05 #11

"David White" <no.email@provi ded> wrote in message
news:E1******** ********@nasal. pacific.net.au. ..
"Risto Lankinen" <rl******@hotma il.com> wrote in message
news:ub******** **********@news 1.nokia.com...

Some consider
it good style to label the overriding function virtual as
well, though.


It doesn't
tell you that it's overriding a base-class function.


Omission of "virtual" in the overriding declaration
doesn't tell that either.

- Risto -

Jul 19 '05 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1789
by: Scott | last post by:
The following is the XML I have to work with. Below is the question <Table0> <CaseID>102114</CaseID> <CaseNumber>1</CaseNumber> <DateOpened>2005-06-14T07:26:00.0000000-05:00</DateOpened> <OnCallPerson /> <CallType>Exposure</CallType> <ExposureReason>General</ExposureReason> <OtherExposureReason>Unintentional</OtherExposureReason> <ClientName>Test Client</ClientName>
16
2741
by: Kitty | last post by:
Hi, everyone. Given a vector<int>, what is the fastest way to find out whether there is a repeated element in it? The result is just "true" or "false". Thanks. Kitty
6
1705
by: Gonalo Rodrigues | last post by:
Hi all, The following (test) program is not working as I expected. Note: The code is a bit long but is easy to understand: There is a class Object implementing ref counting. A Ref<T> template (with a full Ref<Object> specialization) that works like a smart pointer to the Object-rooted hierarchy. The only way to create Object instances is via a static factory that returns a Ref<Object> to a heap allocated object.
21
4082
by: Jon Slaughter | last post by:
I have a class that is basicaly duplicated throughout several files with only members names changing according to the class name yet with virtually the exact same coding going on. e.g. class A { std::vector<B*> Bs; public:
7
1266
by: Joe Fallon | last post by:
I have a WinForm that is a Base class. It has many controls on it and a lot of generic code behind. When I inherit the form I override 5 methods and now each child form has the same look and feel and functionality. This part all works fine. (I learned this morning that if you override a method that also has an Event Handler then you should NOT include the event handler a 2nd time. I had a devil of a time figuring out why a block of code...
15
2144
by: Jiří Paleček | last post by:
Hello, I know the rules for const handling in C++, but I'd like to ask what is the "right" way to use them, eg. when is it appropriate to make a member function const? This came across this question when I was thinking about implementation of a class implementing some lazy data structure or cache. The C++ rules allow among other possibilities making all member functions non-const, or making all member functions const and all members...
18
2087
by: yinglcs | last post by:
Hi, I have a newbie XSLT question. I have the following xml, and I would like to find out the children of feature element in each 'features' element. i.e. for each <featuresI would like to look up what each feature depends on and gerenate a text file. For example, in the following file, I would like to find out feature A depends on A1 and A2 and feature B depends on B1 and B2. And write that to a text file.
7
2118
by: Markus Svilans | last post by:
Hello, My question involves virtual functions and inheritance. Suppose we have a class structure, that consists of "data" classes, and "processor" classes. The data classes are derived from BufferBase, and customized in order to be able to a type of data (of any kind, such as chunks of audio samples from a sound card). The processor classes are derived from ProcessorBase, and are customized to handle BufferBase-derived objects. Each...
16
3191
by: Jeroen | last post by:
Hi all, I have a question which is illustrated by the following piece of code: template <class T> class A { T my_value; }; In a list, I'd like to store pointers to objects of class A. But I don't
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
10325
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8972
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7499
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5381
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4050
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2879
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.