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
> > Can you tell us about any implementation where this isn't true? Or
even only
describe how such an implementation would work?
I'm not a compiler writer, nor a hardware design engineer. The fact remains, the original statement is about an implementation (whether or not it applies to all current implementations or not is irrelevant).
Ah, "I am ignorant so you can't touch me". The trouble with that philosophy
is that there will be other ignorant but nontheless interested and eager to
learn people taking note of your blunt and uninformed statements. So please
be a little more cautious.
With hardware advanced as it is, especially w/ predictive processing/branching, you can't assume anything about performance.
Polymorphism costs, no matter what the technology will be. There are more
entities involved (memory, lookup tables) and more steps to be taken
(processing). You might argue "for my application this is insignificant" or
"I don't care" but no technology is going to equalize the difference.
The only reason to make a function virtual is to allow it to be
overridden. Overriding a function is changing behaviour. Not true.
And then you provide an example demonstrating just what you are denying.
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.


Documentation should be the second line of support. Your code is the first.
The point made is that it isn't bad if your code leaves one wondering so one
will fall back onto the documentation. What is bad though is when your code
suggests something that isn't true so one will think one understands and one
will proceed with the wrong idea. Sort of like reading one of your posts and
not reading the responses to it because the post was so sure and
self-confident that the guy obviously knew what he was talking about.

Martin.
Nov 15 '05 #121
I just developed a process control system in C# in a matter of months from
design to final shipping.

The performance was way on par with unmanaged code, it was half of what our
requirments was and perfectly more than acceptable performance , actualy it
was more than what we expected and we havnt even done an performance
optimization run on it. This is a very real world time critical appliation
(cycle times in an automated environment with lots of variables like
lighting and continual movement of items).

There is no need for the high risk of unmanaged C++ with the long
development times for this appliation. C# is more than adequate. This is a
time critical application. Automation robotics and vision. cycle times are
very very important. This just hardens my confidence in C# as a real
alternative to high performing real world automation.


<.> wrote in message news:ue******** ******@TK2MSFTN GP10.phx.gbl...
No but hey, tell that to the employers out there advertising for C# skills
:D

What do I know eh.

Sure with hardreal time you dont want dynamic memory allocation, obviously
captain obvious. This are specalized cases, for the more run of the mill
applications C# is perfect with short project cycles (which is more and more common) and managibility of bugs and the current drive for more security via a managed environment.

Ofcourse C++ is still used but watch C# take the mainstream applications and C++ for specific interop and time / memory critical applications. C# will
be the dominant language in the mangaged world and C+/CLI for specific needs however this will be kept and should be kept to a minimum as the
managability of that code is too tangled and messy.

Alot of redesign of applications I have worked on are all going C#. They are moving away from Propriety languages like VB and java towards more
standardized ones for level playing fields and less lockin from the likes of MS and Sun.


"Andreas Huber" <ah****@gmx.net > wrote in message
news:40******** @news.bluewin.c h...
di********@disc ussion.microsof t.com wrote:
And what language do you think will be used most in the CLI world and
where the jobs are :D C#


You don't get it, do you? There are classes of applications for which
C#/Java is either too expensive in terms of ROM/RAM footprint (systems

where
the hardware costs are considerably higher than the one for software) or
simply the wrong choice (hard realtime systems, device drivers). For these applications C++ will be *the* language for *at least* another decade. C# and Java are here to stay and that's a good thing but these languages will not be able to to take over everything from C++.

*Every* language has it's pros and cons and language wars are thus just
plain pointless, especially when you argue with beliefs instead of

technical
facts...

Regards,

Andreas


Nov 15 '05 #122
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

Nov 15 '05 #123
Excellent post. Ken, you can go ahead and follow your instincts.

Bruno.

"Martin Maat" <du***@somewher e.nl> a écrit dans le message de
news:10******** *****@corp.supe rnews.com...
Ken,
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?


They are missing the point of object orientation. The first and foremost
benefit is not "ultimate" flexibility", neither is is re-use. The main
benefits are control of complexity; 1:1 mapping of the real world to a

model and comprehensivene ss.

First, virtual methods do not come free, they perform worse than non-virtual methods. Now this may be an issue and it may not, depending on the kind of
application and the way the methods are used.

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
behavior. It helps the developer understand the problem domain. Declaring
everything virtual is bad because the developer will wonder how he should
deal with the method in e derived class. Must he override it? Must he call
the inherited implementation? Before or after his own actions? Can he leave it like it is? If I were that developer and I had been thinking this over,
trying to understand the purpose of a particular virtual method not
understanding how to deal with it and I finally went go to the designer of
the base class and I would ask why and he would say "For no particular
reason, I just couldn't be bothered thinking too hard about the consequences of sealing it so I left it all open for you, providing ultimate flexibility, so you can do the thinking I could not be bothered with, aren't you happy?" Then I would not be happy.

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. It would only invite developers to screw things up and they would not
understand what is expected of them.

Finally, if at some point "something needs to be changed" and polymorphism
would be the answer, then that would be the right moment to open the base
classes source and change the declaration for the particular method to
protected (not public, heaven forbid).
I read the discussion on private virtual methods too. While some languages
may technically allow them they don't make sense. In Delphi for instance you can declare both the base class's virtual methods and the overrided derived class's method private but that only compiles as long as both the base class and the derived class are in the same source file. Once the derived class in in a different source file, all the base class's private methods are
invisible and the project won't compile. Needless to say that little
projects have all classes declared in the same source file. Since it only
works if you put everything together or make everything friend with
everything else it is absolutely pointless because you can in those
situations access anything in your base class from anywhere, it is as good
as putting everything in the same class right away and not derive at all.

So the boys are wrong, you are right. Rub it in.

Martin.

Nov 15 '05 #124
All members that may need to be re-implemented in the future should be
declared virtual.

with regards,
J.V.Ravichandra n
- http://www.geocities.com/
jvravichandran
- http://www.411asp.net/func/search?
qry=Ravichandra n+J.V.&cob=aspn etpro
- http://www.southasianoutlook.com
- http://www.MSDNAA.Net
- http://www.csharphelp.com
- http://www.poetry.com/Publications/
display.asp?ID= P3966388&BN=999 &PN=2
- Or, just search on "J.V.Ravichandr an"
at http://www.Google.com

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 15 '05 #125
> Ah, "I am ignorant so you can't touch me".

Try re-reading. My original point was that you can't assume anything about
performance, because it is strictly tied to the implementation (and underlying
hardware).

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.
The only reason to make a function virtual is to allow it to be
overridden. Overriding a function is changing behaviour.
Not true.
And then you provide an example demonstrating just what you are denying.


Nay, my good friend. My example does NOT change the behavior of the
**CLASS**. Perhaps you would care to elaborate as to why you think it does...
Documentation should be the second line of support. Your code is the first.
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.

Honestly, with the exception of the performance issue(s) (which I feel don't
belong in this discussion), the only reasons that I've heard against MI are
'poor style' (with absolutely no justification) and 'bad documentation' --
funny thing is that neither of these reasons have anything specifically to do
w/ MI, but are really effects of deeper problems and/or a lack of dicipline,
schooling, etc.

Excluding the 'dreaded diamond' issue of MI, can someone substantively say why
MI should *NOT* be part of a language???
"Martin Maat [EBL]" wrote: Can you tell us about any implementation where this isn't true? Or even only describe how such an implementation would work?
I'm not a compiler writer, nor a hardware design engineer. The fact

remains,
the original statement is about an implementation (whether or not it

applies to
all current implementations or not is irrelevant).


Ah, "I am ignorant so you can't touch me". The trouble with that philosophy
is that there will be other ignorant but nontheless interested and eager to
learn people taking note of your blunt and uninformed statements. So please
be a little more cautious.
With hardware advanced as it is, especially w/ predictive

processing/branching,
you can't assume anything about performance.


Polymorphism costs, no matter what the technology will be. There are more
entities involved (memory, lookup tables) and more steps to be taken
(processing). You might argue "for my application this is insignificant" or
"I don't care" but no technology is going to equalize the difference.
The only reason to make a function virtual is to allow it to be
overridden. Overriding a function is changing behaviour.
Not true.


And then you provide an example demonstrating just what you are denying.
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.


Documentation should be the second line of support. Your code is the first.
The point made is that it isn't bad if your code leaves one wondering so one
will fall back onto the documentation. What is bad though is when your code
suggests something that isn't true so one will think one understands and one
will proceed with the wrong idea. Sort of like reading one of your posts and
not reading the responses to it because the post was so sure and
self-confident that the guy obviously knew what he was talking about.

Martin.


--
Bret Pehrson
mailto:br**@inf owest.com
NOSPAM - Include this key in all e-mail correspondence <<38952rglkwdsl >>
Nov 15 '05 #126
> 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.
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 >>
Nov 15 '05 #127

"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



Nov 15 '05 #128

"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 >>

Nov 15 '05 #129
> 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.

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 #130

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
10942
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
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...
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
9452
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 project—planning, coding, testing, and deployment—without 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...
0
7035
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5884
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4499
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
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.