473,842 Members | 1,863 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 8928
[snip]
The general point Brandon is making is that in C++ you will easily
"use" a lot of nifty features that you do not understand without
being aware of it, it is unfornunately not a choice in many cases (no
pun intended). That has been acknowledged by the C# designers.
I don't see why it is C++ fault when ignorant programmers abuse features
they don't understand. Moreover, C# is getting more complex with the next
version and even today people criticize C# for being too complex:

http://groups.google.com/groups?hl=e...tron.net#link1

[snip] And oh (I almost forgot): "my language is better than yours".


Language wars are silly.

Regards,

Andreas

Nov 15 '05 #81
"Bronek Kozicki" <br**@rubikon.p l> wrote in message
news:rq******** *************** ******@40tude.n et...
[still crossposting and asking for crosspost]
Nah, let them read it here.
On Wed, 28 Jan 2004 00:21:47 +0100, Martin Maat [EBL] wrote:
I am not saying that polymorphism and events are equivalent, I am
saying that the example provided by Carl is a good example of
when you should not use polymorphism if you do have a more
natural alternative like events
Could you please provide example code in C#, with the same (or better ;) )
functionality as Carl's example ? It would be interesting to compare
idiom your are proposing with the one described by Carl.


Okay, we used a number of terms in the past posts ranging from polymophism
to events and delegates. What the purpose of Carl's example boils down to is
to that of a callback. In C# "delegates" are used to implement both events
and callbacks. One could argue that events basically are callbacks, let's
not get into that right now.

I say if you really want a callback, then don't use polymorphism because
using ploymorphism is a semantical statement (I like big words, please
forgive me). It implies that there is some basic entity that may have
different incarnations. In Carl's example this is not the case, there it is
plain vanilla straight ahead processing with the possibility for the client
to hook into the control flow (I am really enjoying this).

I read about delegates a couple of weeks ago in "Inside C# 2nd edition" and
grasped about half of it. The identifier names weren't all that well chosen
which made it hard to read and I thought I'd have a closer look the first
time I would need it. Which is now, you gave me the little push I needed.

I tried to stay close to the original idea of a series of tasks that should
be inaccessable from the client's side apart from one particular sub-task
that the client may replace. A string is build and the client gets the
oppurtunity to insert its piece in it. If it declines a defaul piece is used
instead.
=============== START OF CODE =============== ====

using System;
using System.Text;

class PlugHost
{
private string data;

public delegate void ExternalProcess orDelegate(ref string data);
public void DoProcessingAnd DelegatePartOfT heWork(External ProcessorDelega te
custom)
{
data = "_StandardPartA _";

// (only) if the client provided its own logic,
// use that to obtain the middle part.
if (custom == null)
{
data += "_StandardPartB _";
}
else
{
string strCustom = null;
custom(ref strCustom);
data += strCustom;
}

// add another standard part
data += "_StandardPartC _";
}
public string GetResult() { return data; }
}

class App
{
static private void MyCustomProcess or(ref string s)
{
// add my two cents to the effort
s = "CustomPart ";
}

static void Main()
{
PlugHost plugHost = new PlugHost();
// wrap reference to MyCustomProcess or in delegate
PlugHost.Extern alProcessorDele gate myProcessorDele gate = new
PlugHost.Extern alProcessorDele gate(MyCustomPr ocessor);

// call DoProcessingAnd DelegatePartOfT heWork, passing the delegate
plugHost.DoProc essingAndDelega tePartOfTheWork (myProcessorDel egate);

Console.WriteLi ne("Result: {0}", plugHost.GetRes ult());
}
}

=============== END OF CODE =============== ====
Martin.
Nov 15 '05 #82
> > The general point Brandon is making is that in C++ you will easily
"use" a lot of nifty features that you do not understand without
being aware of it, it is unfornunately not a choice in many cases (no
pun intended). That has been acknowledged by the C# designers.
I don't see why it is C++ fault when ignorant programmers abuse features
they don't understand. Moreover, C# is getting more complex with the next
version and even today people criticize C# for being too complex:


No one is blaming anyone or anything. We just feel it is a good idea to
avoid language constructs that are easily misunderstood when designing a
language. We can now look back and make judgements about particular language
features, weighing the costs aganst the benefits. Some features may have
proven to be more of a burden than a bless. Of course it will always be the
programmer's fault but that naked assessment will not make up for the damage
done. It is a good thing that the industry is learning from its mistakes.
Making things "tricky" has proven to be too expensive just to say "fat luck,
you should have hired smarter programmers".

We have safety belts, we have fire alarms and we are going to program
managed code using new languages.

It is only natural to frown on a next generation of anything and since you
are dragging in hot shots to support your case, here's a quote from a
reasonable informed guy in the industry: "I don't need no stinkin' garbage
collector, I obviously know what I'm doing". And he too was turned around
pretty soon too :-).

Martin.
The quote is Jeffrey Richter's, sharing his early emotions on .NET with the
audience at the Developer Days 2002 in The Netherlands.
Nov 15 '05 #83
Martin Maat [EBL] wrote:
The general point Brandon is making is that in C++ you will easily
"use" a lot of nifty features that you do not understand without
being aware of it, it is unfornunately not a choice in many cases
(no pun intended). That has been acknowledged by the C# designers.

I don't see why it is C++ fault when ignorant programmers abuse
features they don't understand. Moreover, C# is getting more complex
with the next version and even today people criticize C# for being
too complex:


No one is blaming anyone or anything. We just feel it is a good idea
to avoid language constructs that are easily misunderstood when
designing a language. We can now look back and make judgements about
particular language features, weighing the costs aganst the benefits.
Some features may have proven to be more of a burden than a bless. Of
course it will always be the programmer's fault but that naked
assessment will not make up for the damage done. It is a good thing
that the industry is learning from its mistakes. Making things
"tricky" has proven to be too expensive just to say "fat luck, you
should have hired smarter programmers".

We have safety belts, we have fire alarms and we are going to program
managed code using new languages.

It is only natural to frown on a next generation of anything and
since you are dragging in hot shots to support your case, here's a
quote from a reasonable informed guy in the industry: "I don't need
no stinkin' garbage collector, I obviously know what I'm doing". And
he too was turned around pretty soon too :-).


I guess I have to clarify that I'm quite fond of C# and I use it for most of
my current programming work (I also still use C++). I only posted in this
thread because someone else made IMO unfounded statements about C++. The
archives'll tell you that I do the same when someone makes IMO unfounded
statements about C#.

Regards,

Andreas

Nov 15 '05 #84
Brian Ross <br**********@r ogers.com> wrote:
[...]
Is it not already possible for derived classes to invoke those functions
anyways. It is a function that belongs to derived afterall? For example:

class Base
{
private:
virtual void f() = 0;
};

class Derived : public Base
{
public:
void g()
{ f(); }

private: // or whatever

virtual void f()
{}

};

I don't see how whether the base class having f() as private or protected
makes any difference to Derived? Additionally, whether 'f()' is protected or
private will make no difference to non-derived classes - it will be
inaccessable.
The difference is, that when you make
'f()' private in the base class, authors
of derived classes won't have to wonder
whether to call 'f()' or not.
Whether 'f()' is protected or private _will_ make a difference if any
derived class tries to call 'f()' statically ( ie.. Base::f() ). If it was
private, it would fail.
Right. Usually that's a good thing.
Brian


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 #85
Martin Maat [EBL] <du***@somewher e.nl> wrote:
The point about "private virtual" is that it allows child classes to
override the method but not call it, if the same method is defined
'protected virtual' then a derived class *can* call it.
Okay, that makes sense. Technically that is.
there are times when it's useful.


Name one :-).


The Template Method pattern:

class Interface {
public:
void algorithm()
{
some_stuff();
customizable_st uff();
some_more_stuff ();
more_customizab le_stuff();
}
private:
void some_stuff() {}
void some_more_stuff () {}
virtual void customizable_st uff() = 0;
virtual void more_customizab le_stuff() {}
};

The 'algorithm()' member function implements
some algorithm. Derived classes can plug into
this and customize some of it.
There is no need for derived classes to call
'customizable_s tuff()' etc. directly, and thus
they shouldn't be allowed. However, they can
(in the pure virtual case: must) replace them.
Just by looking at the class declaration, this
is clear right away to anyone knowing the
pattern.
I am serious, I have been giving this some thought just now but I cannot
come up with a sensible reason to do this. It makes me think of Tommy Cooper
("Pick a card, any card... No, not that one!"). Here's a method, you can use
it.. No you can't!.
"Here is a method, that you can override.
No, you shouldn't call it. Oh right, it
says so on the lable already."
Martin.

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 #86
Martin Maat [EBL] <du***@somewher e.nl> wrote:
[...] However, Jim
Hyslop and Herb Sutter wrote a nice article that provided a reasonable
example: http://www.cuj.com/documents/s=8000/cujcexp1812hyslop/
Hehe, this article says it all. One C++ knoledgable person that loves the
fact that her code is smart and hard to grasp. The next developer needs to
go back to the first one before he can use the class properly.


Only if they don't know the patterns used.
With the very same argument, you can reject
the usage of increment/decrement operators,
since they just hide what's really done
from people who don't know them.
That is the
whole point, it isn't wrong but it works in a counter-intuitive way,
defeating the purpose of having these visibility layers.
In the years I am using C/C++, I have come
across many, many things which I considered
very, very couter-intuitive. Yet they are
done regularly and understood by most (for
some definition of "most") programmers (for
some definition of "programmer s"). For many
of those, it was just that I hadn't learned
enough yet. (For some I'd still argue.)
It was the very same with private virtuals.
If you use google, you might find that at
one (not so long ago) time I was stunned to
learn that this even is possible. Now I use
it regularly. At first, my co-workers were
stunned when they saw it. Any guess what:
Meanwhile, they start to use it, too.
[...]
Martin.


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 #87
Martin Maat [EBL] <du***@somewher e.nl> wrote:
You seem to suggest that C++s support for private virtual functions makes
C++ less robust. Funny, I'd claim exactly the opposite.
"Industrial robustness" in the real world means simplifying things so
that the vast majority of average programmers understand what's going
on.


[...]
I really fail to see how private virtuals hurt "industrial robustness".


The general point Brandon is making is that in C++ you will easily "use" a
lot of nifty features that you do not understand without being aware of it,
[...]


With the same reasoning you could reject
any tool more complicated than a hammer
and a bag of nails, since you can misuse
them in so many hurtful ways. Yet, in the
hand of a skilled craftsman, they can be
very powerful tools that allow him to do
things that are less elegant or very hard
to do without them.
In the private virtual discussion, robustness may not be an issue. I would
call it "not elegant".
I find Template Method a _very_ elegant
pattern. Once you explain it to someone,
they know exactly what it is about, how
to use it, and how to recognize it. And
using private virtuals, it does exactly
what the class declaration indicates it
is doing.
Every time something new comes along the established lot will say "Kid's
stuff, no gain, too slow, don't need it". And after a while we all learn to
appreciate it.
Yeah. Seems like private virtual are new
to many here.
And oh (I almost forgot): "my language is better than yours".
According to which definition of "good"? :)
Martin.


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 #88
Martin Maat [EBL] <du***@somewher e.nl> wrote:
[...]
No one is blaming anyone or anything. We just feel it is a good idea to
avoid language constructs that are easily misunderstood when designing a
language. [...]
Define "easily". Oh, and for whom?
I have been teaching programming and
IMO every language is too hard to
grasp for someone, and easily used
by others.
[...]
Martin.
[...]

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 #89
Martin Maat [EBL] <du***@somewher e.nl> wrote:
[...]
Well, they didn't have these fancy editors back then that enabled the
programmer to collaps the implemantation did they? So seperating interface
and implementation was just practical [...]


If I hadn't been taught it before, the
first time I came across an app that
had a couple 100kLOC, with many people
designing and implementing parts of it
simultaniously, I know what separation
of interface and implementation is good
for. IMHO that's why so many languages
have it.

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

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
9867
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
9709
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
10939
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...
1
10669
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
10308
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
7028
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();...
1
4498
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
2
4086
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3140
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.