473,854 Members | 1,595 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 8956
Frank Oquendo wrote:
Carl Daniel [VC++ MVP] wrote:
The reason it damages design by contract is that it allows derived
classes to break the contract, since they can invoke their own
virtual functions without going through the public
(contract-enforcing) interface.
I don't get it. Can you show me an example?


Imagine that you have a class (C++ syntax):

class C
{
public:
virtual ~C() {}
void process()
{
part_a();
part_b();
part_c();
}

private:
void part_a() {}
virtual void part_b() {}
void part_c() {}
};

This class is clearly designed to be used polymorphically : the virtual
destructor and virtual part_b indicate this.

How is a class used polymorphically ? Through a pointer (or reference) to a
base class. Using a pointer to the base class (C), only the process()
method is available - that's the public interface of C.

A derived class can override part_b, but it cannot invoke any of the parts
of process (part_a, part_b, part_c) independently.

Now, imagine that part_a() validates that the object is in a coherent state
and logs the start of process(), while part_c re-validates that the object
is in a coherent state, logs the end of process() and frees resources
acquired in part_a. (Clearly there would be exception safety issues to deal
with, but that's independent of this example).

By having part_b private, a derived class can replace the implementation of
part_b, but cannot ever call it without going through process() - going
through process enforces the invariants of the class:

- The object is in a valid state before the operation
- The start of all operations is logged
- The end of all operations is logged
- The object is in a valid state after the operation

This general pattern is called "Design By Contract" (DBC). C++ lets you
implement and enforce DBC directly. C# and Java prohibit you from builing
an enforceable DBC. Of course, you can create the same mechanisms in C#,
but you can't ensure that they'll be used. If part_b where public or
protected (as required in C#/Java), any other method of a class overriding
part_b could invoke part_b directly thus skipping the invariant checks.
The fact that a method is virtual means that a derived class can
replace it. The fact that a method is private means that only the
declaring class can access it. The two are completely orthogonal
concepts - why tie them together artificially?


They're not tied together at all. The accessibility of a member and
the ability to override that member are controlled through two
separate mechanisms.


If you can't override a private member then they're tied together.

-cd
Nov 15 '05 #31
Carl Daniel [VC++ MVP]
<cp************ *************** **@mvps.org.nos pam> wrote:
The fact that a method is virtual means that a derived class can replace it.
The fact that a method is private means that only the declaring class can
access it. The two are completely orthogonal concepts - why tie them
together artificially?


That may be what private means in C++, but in C# it's much simpler:
private means that the member is in no way visible to any other types
(outside reflection, of course). This is a much simpler view of the
world, IMO, and easier to understand.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #32
Martin Maat [EBL] 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 :-).


See the example I just posted elsewhere in this thread. This is actually a
very useful design pattern - not at all esoteric once you understand it.

-cd

Nov 15 '05 #33
Jon Skeet [C# MVP] wrote:
Carl Daniel [VC++ MVP]
<cp************ *************** **@mvps.org.nos pam> wrote:
The fact that a method is virtual means that a derived class can
replace it. The fact that a method is private means that only the
declaring class can access it. The two are completely orthogonal
concepts - why tie them together artificially?


That may be what private means in C++, but in C# it's much simpler:
private means that the member is in no way visible to any other types
(outside reflection, of course). This is a much simpler view of the
world, IMO, and easier to understand.


It's clearly simpler, and it may well be easier to understand (personally I
din't think so, but then I'm from a C++ background).

The significance of this thread though is to amplify the point that this
simplification comes with a cost: certain very valuable design idioms are
simply not possible in C# (or Java) because of the restriction on overriding
a private method.

-cd
Nov 15 '05 #34
n! wrote:
Because they're unnecessary thanks to the protected keyword. Why
support two ways to override a member when one access modifier has
semantics the other does not?

Considering nothing is virtual by default in C#, it makes perfect
sense to use protected virtual instead of private virtual.


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. Whilst it may
seem esoteric, there are times when it's useful. Though TBH I've
never needed private virtual in C# so far.


It *is* esoteric, and I would wager that the C# language designers chose
simplicity in the interest of industrial robustness. "Industrial
robustness" in the real world means simplifying things so that the vast
majority of average programmers understand what's going on. C++ is a very
tweaky language with lotsa weird cases. C#, philosophically , is clearly an
attempt to clean up C++'s mess.

This observation may be lost on hardcore C++ programmers, and that is
precisely the point. In the long haul, C# will replace C++ for an awful lot
of application programming tasks. It has already happened at Microsoft and
it's only a matter of time for it to happen with the vast majority of
Windows development.

--
Cheers, www.indiegamedesign.com
Brandon Van Every Seattle, WA

20% of the world is real.
80% is gobbledygook we make up inside our own heads.

Nov 15 '05 #35
> > Okay, that makes sense. Technically that is.
there are times when it's useful.
Name one :-).


See the example I just posted elsewhere in this thread. This is actually

a very useful design pattern - not at all esoteric once you understand it.


You claim that C++ has this wonderful ability that C# and other OO-languages
lack. Having read your clear example I say DBC can be implemented much, much
nicer and cleaner using events because that is precisely what it is. The
base class provides a way to plug-in client-provided logic. Now C++ does not
support that natively so some horrible hack like a private virtual method
was used to achieve this. I am willing to call the solution "creative" and I
respect the work of the pioneers that started the programming industry as we
know it. Fortunately, we don't have to do it that way anymore these days
:-).

Martin.
Nov 15 '05 #36

"Martin Maat [EBL]" <du***@somewher e.nl> wrote in message
news:10******** *****@corp.supe rnews.com...
Okay, that makes sense. Technically that is.

> there are times when it's useful.

Name one :-).
See the example I just posted elsewhere in this thread. This is

actually a
very useful design pattern - not at all esoteric once you understand it.


You claim that C++ has this wonderful ability that C# and other
OO-languages
lack. Having read your clear example I say DBC can be implemented much,
much nicer and cleaner using events <snip>


No. It most definitely cannot. Private virtuals guarantees that the most
derived override is called once and once only when called from the base
class. Events do no such thing.

<snip>

/Magnus Lidbom


Nov 15 '05 #37
I was going to write a response to this, but Martin said everything I was
going to say, so I'll just say "what Martin said..."

--
Eric Gunnerson

Visit the C# product team at http://www.csharp.net
Eric's blog is at http://weblogs.asp.net/ericgu/

This posting is provided "AS IS" with no warranties, and confers no rights.
"Martin Maat" <du***@somewher e.nl> wrote in message
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 #38
Brandon J. Van Every wrote:
n! wrote:
Because they're unnecessary thanks to the protected keyword. Why
support two ways to override a member when one access modifier has
semantics the other does not?

Considering nothing is virtual by default in C#, it makes perfect
sense to use protected virtual instead of private virtual.
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. Whilst it may
seem esoteric, there are times when it's useful. Though TBH I've
never needed private virtual in C# so far.


It *is* esoteric, and I would wager that the C# language designers
chose simplicity in the interest of industrial robustness.


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.


Simple: If you don't understand it, don't use it and everything will be
well. If you happen to maintain somebody else's code using the private
virtual idiom it should become obvious very quickly how it works. If not,
post an appropriate question to comp.lang.c++ ;-).
I really fail to see how private virtuals hurt "industrial robustness".

Regards,

Andreas

Nov 15 '05 #39

"Martin Maat [EBL]" <du***@somewher e.nl> wrote in message
news:10******** *****@corp.supe rnews.com...
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 :-).
Martin.


DBC (Design By Contract). Public non-virtual interface (interface), private
virtual interface (implementation ). The public interface enforces pre and
post conditions, and delegates implementation to the private virtual
implementation.

Tom.
Nov 15 '05 #40

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

Similar topics

164
8074
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
9901
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
11031
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
10763
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
10371
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
9517
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
7082
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
5942
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4563
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
4159
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.