473,842 Members | 1,933 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

"All public methods should be virtual" - yes or no / pros & cons

I'm on a team building some class libraries to be used by many other
projects.

Some members of our team insist that "All public methods should be virtual"
just in case "anything needs to be changed". This is very much against my
instincts. Can anyone offer some solid design guidelines for me?

Thanks in advance....
Nov 15 '05
175 8932
> In my opinion they should be nonvirtual and internally call a
protected(priva te in C++) virtual method that may be overridden. Look up
"Template Method" and "Design by Contract". Making a public method virtual
means that you give your client no guarantee what so ever as to what will
happen when they invoke the method on a subclass. It also means that you've [snip]

You make it sound like the norm is for a programmer to use an existing class
library, add a couple of overridden methods, and then repackage that and
hand/sell it off to someone else.

In most cases, anyone that is overriding a method to an established interface
is ultimately the end user, and (provided they are informed and careful
programmers), has no need to adhere to the original 'design by contract', per
se.

We really need to make sure that we don't confuse a designer w/ a user -- I
understand the potential problems w/ a designer that overrides a previous
designer's work, but my discussions have been limited to the end user of an
interface that has the desire to monitor or change behavior (that will in
most/all cases not be subsequently used by someone else).

Magnus Lidbom wrote:
"Bret Pehrson" <br**@infowest. com> wrote in message
news:40******** *******@infowes t.com...
First, virtual methods do not come free, they perform worse than non-virtual methods.


This is a generalized statement regarding an *IMPLEMENTATION * of the

language,
not the language itself.
Another thing. If something is declared virtual, that is a statement on the part of the designer. It implies some generic behavior that may need to be altered somehow for any derived.class in order to obtain the desired...


It doesn't/shouldn't imply anything. If the user relies in implications,

they
are going to have problems with their code regardless of the construct at

hand.

Remember, that virtual doesn't mean that the overriding method has to do
*anything*, it may be simply tracking, monitoring, or triggering a

response.
These are all *VALID* uses of virtual, and have absolutely NOTHING to do

w/
changing behavior.
Imagine every public method of a fairly complex class being virtual. Most of them will implement fixed behavior that is not supposed to be

overridden.

If they MUST NOT be overridden for **ANY** reason, then they shouldn't be
virtual. If they shouldn't be overridden in such a way as to change

behavior,
they should be virtual and that fact should be in the documentation.

In my opinion they should be nonvirtual and internally call a
protected(priva te in C++) virtual method that may be overridden. Look up
"Template Method" and "Design by Contract". Making a public method virtual
means that you give your client no guarantee what so ever as to what will
happen when they invoke the method on a subclass. It also means that you've
made at statement that when I inherit your class I may replace the
functionality of the method. If what you mean can be expressed clearly in
code, you should do so.You shouldn't write code that says one thing and say
another in the documentation.

/Magnus Lidbom


--
Bret Pehrson
mailto:br**@inf owest.com
NOSPAM - Include this key in all e-mail correspondence <<38952rglkwdsl >>
Nov 15 '05 #131

"Bret Pehrson" <br**@infowest. com> wrote in message
news:40******** *******@infowes t.com...
Magnus Lidbom wrote:
In my opinion they should be nonvirtual and internally call a
protected(priva te in C++) virtual method that may be overridden. Look up
"Template Method" and "Design by Contract". Making a public method virtual means that you give your client no guarantee what so ever as to what will happen when they invoke the method on a subclass. It also means that
you've [snip]

You make it sound like the norm is for a programmer to use an existing class library, add a couple of overridden methods, and then repackage that and
hand/sell it off to someone else.

In most cases, anyone that is overriding a method to an established interface is ultimately the end user, and (provided they are informed and careful
programmers), has no need to adhere to the original 'design by contract', per se.

We really need to make sure that we don't confuse a designer w/ a user -- I understand the potential problems w/ a designer that overrides a previous
designer's work, but my discussions have been limited to the end user of an interface that has the desire to monitor or change behavior (that will in
most/all cases not be subsequently used by someone else).

So you feel that if at the present moment you don't expect anyong else to
become a client of your code, lets not get into the odds of that, you should
write code that would be unacceptable if anyone else needs to use it?

You said:
"If they MUST NOT be overridden for **ANY** reason, then they shouldn't be
vrtual. If they shouldn't be overridden in such a way as to change
behavior, they should be virtual and that fact should be in the
documentation."

So you feel that one should write code that doesn't express your intent and
then document the intent when you don't expect it to be used by others? My
opinion is that you should always write code that expresses your intent. In
this case it's also very simple to do so:

protected virtual void Extention(){}
public void DoStuff()
{
//dostuff
Extention();
}

/Magnus Lidbom


Nov 15 '05 #132
> I have yet to read *anything* in either the C or C++ spec that deals w/
performance. The thread is about the positives and negatives of MI, not
implementation-specific or performance.
Aren't you confusing different news threads here? This is about polymorphism
through virtual methods and whether it is appropriate to apply it as a means
of implementing a plug-in mechanism.
My example does NOT change the behavior of the **CLASS**.
Perhaps you would care to elaborate as to why you think it does...
The behavior of the class is changed by sub-classing it. What is the point
of stating that a base class is not changed by the descendant? The way we
look at it there is no point in creating a descendent class if not either
behavior or data members are changed./ extended.
You code is the first line if you are working *in the code*. Although not
explicitly defined as such, this thread has been primarily limited to the
presumption that only the interface is avaialble (i.e. header files). My
documentation comments are based on that.
For interface definitions it is even more important that they are
self-explanatory and clear on their intended use than it is for
implementation code.
the only reasons that I've heard against MI are 'poor style' (with
absolutely no justification) and 'bad documentation' --


What do you mean with MI ? "MI" has not been part of the discussion I have
been participating in.

Martin.
Nov 15 '05 #133
> It is extremely difficult (at best) to determine expected behavior from
prototypes and definitions alone (meaning, no documentation, *NO* comments). If *you* can take naked prototypes and definitions and understand the usage, behavior, and characteristics of the interface, then you are in a definite
minority. Personally, I rely heavily on the documentation.


I think you missed the point of the discussion. We are not against
documentation, neither does any of us feel strongly it should be made
redundant by code at all times. It was about particular design patterns,
whether they could be labeled "misleading code constructs" and if it was a
good thing to use them or not. To what extend we should assume coders to
recognize these patterns and understand the intend, if we should better not
use them anymore in C# now that it has more natural solutions to the
initially targeted problem like delegates.

So when someone sais "If the code does not tell the whole story, there's
always the documenttion to make up for that" we said that's no good because
once the code has given us the wrong impression yet the feeling that we
understand we are not likely to read the ducumentation.

Martin.
Nov 15 '05 #134
> What do you mean with MI ? "MI" has not been part of the discussion I have
been participating in.
Yep, my mistake. MI discussions are in a different thread, and I confused
them.
"Martin Maat [EBL]" wrote:
I have yet to read *anything* in either the C or C++ spec that deals w/
performance. The thread is about the positives and negatives of MI, not
implementation-specific or performance.


Aren't you confusing different news threads here? This is about polymorphism
through virtual methods and whether it is appropriate to apply it as a means
of implementing a plug-in mechanism.
My example does NOT change the behavior of the **CLASS**.
Perhaps you would care to elaborate as to why you think it does...


The behavior of the class is changed by sub-classing it. What is the point
of stating that a base class is not changed by the descendant? The way we
look at it there is no point in creating a descendent class if not either
behavior or data members are changed./ extended.
You code is the first line if you are working *in the code*. Although not
explicitly defined as such, this thread has been primarily limited to the
presumption that only the interface is avaialble (i.e. header files). My
documentation comments are based on that.


For interface definitions it is even more important that they are
self-explanatory and clear on their intended use than it is for
implementation code.
the only reasons that I've heard against MI are 'poor style' (with
absolutely no justification) and 'bad documentation' --


What do you mean with MI ? "MI" has not been part of the discussion I have
been participating in.

Martin.


--
Bret Pehrson
mailto:br**@inf owest.com
NOSPAM - Include this key in all e-mail correspondence <<38952rglkwdsl >>
Nov 15 '05 #135
Ya, I've lost interest in the thread.

Thanks for the discussions/comments/interactions. I've learned some new
things, and will apply them to my coding practices.

Magnus Lidbom wrote:

"Bret Pehrson" <br**@infowest. com> wrote in message
news:40******** *******@infowes t.com...
Magnus Lidbom wrote:
In my opinion they should be nonvirtual and internally call a
protected(priva te in C++) virtual method that may be overridden. Look up
"Template Method" and "Design by Contract". Making a public method virtual means that you give your client no guarantee what so ever as to what will happen when they invoke the method on a subclass. It also means that

you've
[snip]

You make it sound like the norm is for a programmer to use an existing

class
library, add a couple of overridden methods, and then repackage that and
hand/sell it off to someone else.

In most cases, anyone that is overriding a method to an established

interface
is ultimately the end user, and (provided they are informed and careful
programmers), has no need to adhere to the original 'design by contract',

per
se.

We really need to make sure that we don't confuse a designer w/ a user --

I
understand the potential problems w/ a designer that overrides a previous
designer's work, but my discussions have been limited to the end user of

an
interface that has the desire to monitor or change behavior (that will in
most/all cases not be subsequently used by someone else).

So you feel that if at the present moment you don't expect anyong else to
become a client of your code, lets not get into the odds of that, you should
write code that would be unacceptable if anyone else needs to use it?

You said:
"If they MUST NOT be overridden for **ANY** reason, then they shouldn't be
vrtual. If they shouldn't be overridden in such a way as to change
behavior, they should be virtual and that fact should be in the
documentation."

So you feel that one should write code that doesn't express your intent and
then document the intent when you don't expect it to be used by others? My
opinion is that you should always write code that expresses your intent. In
this case it's also very simple to do so:

protected virtual void Extention(){}
public void DoStuff()
{
//dostuff
Extention();
}

/Magnus Lidbom


--
Bret Pehrson
mailto:br**@inf owest.com
NOSPAM - Include this key in all e-mail correspondence <<38952rglkwdsl >>
Nov 15 '05 #136
n!
> I'm on a team building some class libraries to be used by many other
projects.

Some members of our team insist that "All public methods should be virtual" just in case "anything needs to be changed". This is very much against my
instincts. Can anyone offer some solid design guidelines for me?

Thanks in advance....


It's too big to be a space station.

n!
Nov 15 '05 #137
> The behavior of the class is changed by sub-classing it. What is the point
of stating that a base class is not changed by the descendant? The way we
look at it there is no point in creating a descendent class if not either
behavior or data members are changed./ extended.
I agree that overriding to change behavior is half of the story. The other
half overriding to create/monitor/track an object's methods. I tried giving an
example of such a case before, just to point out that you can't limit 'virtual'
discussions just to the modification of behavior since it is perfectly
legitimate to override a method and *not* change any behavior.

"Martin Maat [EBL]" wrote:
I have yet to read *anything* in either the C or C++ spec that deals w/
performance. The thread is about the positives and negatives of MI, not
implementation-specific or performance.


Aren't you confusing different news threads here? This is about polymorphism
through virtual methods and whether it is appropriate to apply it as a means
of implementing a plug-in mechanism.
My example does NOT change the behavior of the **CLASS**.
Perhaps you would care to elaborate as to why you think it does...


The behavior of the class is changed by sub-classing it. What is the point
of stating that a base class is not changed by the descendant? The way we
look at it there is no point in creating a descendent class if not either
behavior or data members are changed./ extended.
You code is the first line if you are working *in the code*. Although not
explicitly defined as such, this thread has been primarily limited to the
presumption that only the interface is avaialble (i.e. header files). My
documentation comments are based on that.


For interface definitions it is even more important that they are
self-explanatory and clear on their intended use than it is for
implementation code.
the only reasons that I've heard against MI are 'poor style' (with
absolutely no justification) and 'bad documentation' --


What do you mean with MI ? "MI" has not been part of the discussion I have
been participating in.

Martin.


--
Bret Pehrson
mailto:br**@inf owest.com
NOSPAM - Include this key in all e-mail correspondence <<38952rglkwdsl >>
Nov 15 '05 #138

"Bret Pehrson" <br**@infowest. com> wrote in message
news:40******** *******@infowes t.com...
Simple, you do *anything* and what your class does changes.
No, no, NO!

Come on, my example doesn't change the behaior of the class -- period. It

may (and very well does) change the state or behavior of the *SYSTEM*, but we are *not* talking about that. If your method changes the system, then the behaviour of your class now
includes that change to the system, a classes behaviour is *EVERYTHING*, not
just the class state. Even if it doesn't change the result of the call it
still changes behaviour(and even in your example it *could* change the
result of the call by throwing an exception). Its likely behaviour you
*must* document, and treat as a behaviour change.

Of course, if you don't consider adding the chance of new exceptions, new
ways to fail, or new possible constraints on parameters a change in
behaviour, I think our definitions of the word differ.

In everything but an idealized world, an override should be automatically
considered a change in behaviour. Even if you can guarentee ironclad that it
works without any behaviour change, you still leave the chance that a change
*elsewhere* could change behaviour elsewhere(which is part of the problem, a
code change *anywhere* is a change in behaviour, potentially in the entire
system, even if its not entirely noticable or anything that actually effects
change).
The point was, is, and will continue to be: virtual methods can be used to change behavior ***OR*** for other reasons that *DO NOT CHANGE BEHAVIOR*, which is what I've illustrated.

"Daniel O'Connell [C# MVP]" wrote:

"Bret Pehrson" <br**@infowest. com> wrote in message
news:40******** *******@infowes t.com...
> This does change behaviour. (And I don't
> think I want/need to tell you how.)

Then don't post a response! We are (presumably) all here for constructive
and
educational reasons, so you statement provides nothing and actually confuses
the issue.

Please elaborate on why you think this changes class behavior. I'll

probably
learn something.

Simple, you do *anything* and what your class does changes. If that call
throws an exception you are adding a point of failure, if that call
instantiates objects you are using memory(and perhaps creating a memory
leak), if that call deletes random files you are probably angering users, if that call changes an object or variable the underlying method uses in
another class you could introduce unexpected bugs and it all may rain down on someone elses head because of it. Simply because your call leaves the
instance alone does *NOT* mean that its behaviour isn't changed, its state simply isn't. Behaviour is considerably more than simply what Method A does to Field B. Your example likely doesn't change the object but potentially changes the entire universe the object exists in.

> I expect to read your headers, see and
> recognize common patterns, understand
> your identifiers, and use this interface
> as it is with as little need for looking
> it up in the docs as possible. If you
> don't provide that, then that's one darn
> good reason to look for another provider.

I'm not following. Maybe my statements weren't clear, but my
intention is this: any well-meaning programmer that produces code potentially for

anyone
else (either directly or indirectly), should include complete and correct documentation.

It is extremely difficult (at best) to determine expected behavior from prototypes and definitions alone (meaning, no documentation, *NO*

comments).
If *you* can take naked prototypes and definitions and understand the

usage,
behavior, and characteristics of the interface, then you are in a definite minority. Personally, I rely heavily on the documentation.

Hendrik Schober wrote:
>
> Bret Pehrson <br**@infowest. com> wrote:
> > [...]
> > > The only reason to make a function virtual
> > > is to allw it to be overridden. Overriding
> > > a function is changing behaviour.
> >
> > Not true.
> >
> > class A
> > {
> > public:
> > virtual void a()
> > {
> > // do something
> > }
> > };
> >
> > class B : public A
> > {
> > public:
> > virtual void a()
> > {
> > A::a();
> > trace("processi ng a");
> > }
> > }
> >
> > This doesn't change behavior, but is a very valid and real-world

case of
> > virtual overrides.
>
> This does change behaviour. (And I don't
> think I want/need to tell you how.)
>
> > > Don't expect us to carefully read douments
> > > that contradict your code.
> >
> > ???
> >
> > I do expect you to carefully read documents that define the
behavior, usage,
> > and intent of my interfaces.
>
> I expect to read your headers, see and
> recognize common patterns, understand
> your identifiers, and use this interface
> as it is with as little need for looking
> it up in the docs as possible. If you
> don't provide that, then that's one darn
> good reason to look for another provider.
>
> > [...]
>
> Schobi
>
> --
> Sp******@gmx.de is never read
> I'm Schobi at suespammers dot org
>
> "Sometimes compilers are so much more reasonable than people."
> Scott Meyers

--
Bret Pehrson
mailto:br**@inf owest.com
NOSPAM - Include this key in all e-mail correspondence

<<38952rglkwdsl >>
--
Bret Pehrson
mailto:br**@inf owest.com
NOSPAM - Include this key in all e-mail correspondence <<38952rglkwdsl >>

Nov 15 '05 #139
"Bret Pehrson" <br**@infowest. com> wrote in message
news:40******** *******@infowes t.com...
The behavior of the class is changed by sub-classing it. What is the point of stating that a base class is not changed by the descendant? The way we look at it there is no point in creating a descendent class if not either behavior or data members are changed./ extended.
I agree that overriding to change behavior is half of the story. The other half overriding to create/monitor/track an object's methods. I tried giving an example of such a case before, just to point out that you can't limit 'virtual' discussions just to the modification of behavior since it is perfectly
legitimate to override a method and *not* change any behavior.


Okay, I understand your point now. You are saying it is not a crime to use
polymorphism as an event mechanism. For debugging purposes as in your
example I do not see any harm either. As a design pattern though I say it
should not be done if a more dedicated events mechanism is available in the
particular development environment.

That summarizes most of the noise we all generated on the subject. :-)

Martin.
Nov 15 '05 #140

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

Similar topics

164
8069
by: Ken Brady | last post by:
I'm on a team building some class libraries to be used by many other projects. Some members of our team insist that "All public methods should be virtual" just in case "anything needs to be changed". This is very much against my instincts. Can anyone offer some solid design guidelines for me? Thanks in advance....
0
9870
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, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
9715
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10610
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...
1
10671
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10310
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5696
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
5884
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4088
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3142
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.