Article Discussion
Versioning, Virtual, and Override
Summary: Anders Hejlsberg, the lead C# architect, talks with Bruce Eckel and Bill Venners about why C# instance methods are non-virtual by default and why programmers must explicitly indicate an override.
31 posts.
The ability to add new comments in this discussion is temporarily disabled.
Most recent reply: November 15, 2004 0:53 PM by Shital
    Bill
     
    Posts: 409 / Nickname: bv / Registered: January 17, 2002 4:28 PM
    Versioning, Virtual, and Override
    September 16, 2003 5:22 PM      
    Anders Hejlsberg says, "We will never catch up. We will never fill all the capacity that Moore's law is heaping on us. The way we get more functionality these days is by doing more and more leveraging of existing infrastructure and existing applications. As systems are becoming longer lived, versioning is becoming more important."

    Read this Artima.com interview with C# creator Anders Hejslberg:

    http://www.artima.com/intv/nonvirtual.html

    What do you think of Anders' comments?
    • robert
       
      Posts: 35 / Nickname: funbunny / Registered: September 23, 2003 5:08 AM
      Re: Versioning, Virtual, and Override
      September 23, 2003 9:12 AM      
      this DbC stuff sounded familiar -> Eiffel, in fact. here's a msg posted by BM: http://groups.google.com/groups?q=%2Boutput+%2Bcontract+group:comp.lang.eiffel&hl=en&lr=&ie=UTF-8&group=comp.lang.eiffel&selm=139%40feiffel.UUCP&rnum=4

      or, go to comp.lang.eiffel, search +output +contract. you'll find it. from 1995.
      • Geoff
         
        Posts: 6 / Nickname: geoffs / Registered: April 24, 2003 6:15 AM
        Re: Versioning, Virtual, and Override
        September 26, 2003 7:44 PM      
        > this DbC stuff sounded familiar -> Eiffel [...]

        Absolutely! I've not looked really far into the history of software development, but to my knowlege much of the current focus on separation of interface and implementation derives from Meyer's work on DbC. In fact, the group I'm working with frequently talk of the combination of our Java 'Interface' classes and JUnit tests as defining the contract for a particular concrete class (or classes). In a couple of cases, we've even tried refactoring our tests to allow multiple implementation classes to be tested by the same test-suite, as a way of validating that all the implementations are subsitutable.

        Cheers,

        Geoff Sobering
    • David
       
      Posts: 3 / Nickname: davj / Registered: September 27, 2003 1:19 AM
      Virtual, and Override?
      September 27, 2003 5:25 AM      
      "Bill Venners: In Java, instance methods are virtual by default—they can be overridden in subclasses unless they are explicitly declared final."

      Default methods are NOT dynamic (or virtual) - Child methods that override default methods from Parent (of a different package) are statically bound.

      After reading this first sentence,I could not read any further .
      • Frank
         
        Posts: 11 / Nickname: fmitchell / Registered: January 31, 2003 9:53 AM
        Re: Virtual, and Override?
        September 27, 2003 9:07 AM      
        > Default methods are NOT dynamic (or virtual) -
        > Child methods that override default methods from Parent
        > (of a different package) are statically bound.

        It took me a couple of tries to parse this sentence, but I think you're referring to the case where method x in class a.A has default protection (i.e. not protected or public), and class b.B extends a.A and defines its own method x. In that case, yes, there's no relationship between a.A.x and b.B.x, and both compiler and runtime will prevent calls to a.A.x from within package b.

        However, the original quote doesn't mention which package the subclass resides in. A class a.C that extends a.A and overrides x will require dynamic binding for x. Furthermore, the JVM must always be prepared to load a.C with the correct semantics, even if it isn't in the same jar as a.A, unless the jar containing a.A is sealed.

        In those (common) cases, then, even methods with default protection are "virtual". HotSpot may statically bind them as an optimization, but it must undo the optimization as soon as a.C is loaded.
    • Sakesun
       
      Posts: 8 / Nickname: sakesun / Registered: August 18, 2003 10:00 PM
      Re: Versioning, Virtual, and Override
      September 17, 2003 0:40 AM      
      As a long time delphi user, no wonder why I quite agree with Anders. Recently, I'm learning java. Though never have any experience in large java project, I always wonder how often does java programmer make a mistake by mis-typing the overriding method name. Without explicit "override" keyword the mis-typed method will undesireably become a new method. Also, without override it's must be very difficult to change base-class method name, since the compiler cannot help you find out where that method was overriden in the sub-classes.
      • Robert C.
         
        Posts: 5 / Nickname: unclebob / Registered: April 25, 2003 6:39 AM
        Re: Versioning, Virtual, and Override
        September 23, 2003 10:32 AM      
        It never happens to me. I think if you are disciplined about writing your unit tests you'll never have this problem.
      • Robert C.
         
        Posts: 5 / Nickname: unclebob / Registered: April 25, 2003 6:39 AM
        Re: Versioning, Virtual, and Override
        September 23, 2003 10:32 AM      
        > As a long time delphi user, no wonder why I quite agree
        > with Anders. Recently, I'm learning java. Though never
        > have any experience in large java project, I always wonder
        > how often does java programmer make a mistake by
        > mis-typing the overriding method name. Without explicit
        > "override" keyword the mis-typed method will undesireably
        > become a new method. Also, without override it's must be
        > very difficult to change base-class method name, since the
        > compiler cannot help you find out where that method was
        > overriden in the sub-classes.

        It never happens to me. I think if you are disciplined about writing your unit tests you'll never have this problem.
      • Robert C.
         
        Posts: 5 / Nickname: unclebob / Registered: April 25, 2003 6:39 AM
        Re: Versioning, Virtual, and Override
        September 23, 2003 10:33 AM      
        > As a long time delphi user, no wonder why I quite agree
        > with Anders. Recently, I'm learning java. Though never
        > have any experience in large java project, I always wonder
        > how often does java programmer make a mistake by
        > mis-typing the overriding method name. Without explicit
        > "override" keyword the mis-typed method will undesireably
        > become a new method. Also, without override it's must be
        > very difficult to change base-class method name, since the
        > compiler cannot help you find out where that method was
        > overriden in the sub-classes.

        It never happens to me. I think if you are disciplined about writing your unit tests you'll never have this problem.
      • Aleksander
         
        Posts: 1 / Nickname: aslom / Registered: May 5, 2003 8:11 AM
        Re: Versioning, Virtual, and Override
        September 23, 2003 4:42 PM      
        > As a long time delphi user, no wonder why I quite agree
        > with Anders. Recently, I'm learning java. Though never
        > have any experience in large java project, I always wonder
        > how often does java programmer make a mistake by
        > mis-typing the overriding method name. Without explicit
        > "override" keyword the mis-typed method will undesireably
        > become a new method. Also, without override it's must be

        good IDE such as CodeGuide will indicate graphically if method is overriding existing virtual method (in CodeGuide it shows small red ball with arrow up and by cllicking it you can jump to overriden method). still i like idea of "override" keywor as it is good to have such delcarations in code so compiler and JVM can enforce it.
      • Robert C.
         
        Posts: 5 / Nickname: unclebob / Registered: April 25, 2003 6:39 AM
        Re: Versioning, Virtual, and Override
        September 23, 2003 10:36 AM      
        > As a long time delphi user, no wonder why I quite agree
        > with Anders. Recently, I'm learning java. Though never
        > have any experience in large java project, I always wonder
        > how often does java programmer make a mistake by
        > mis-typing the overriding method name. Without explicit
        > "override" keyword the mis-typed method will undesireably
        > become a new method. Also, without override it's must be
        > very difficult to change base-class method name, since the
        > compiler cannot help you find out where that method was
        > overriden in the sub-classes.

        It never happens to me. I think if you are disciplined about writing unit tests then it just won't happen in practice.
        • Sakesun
           
          Posts: 8 / Nickname: sakesun / Registered: August 18, 2003 10:00 PM
          Re: Versioning, Virtual, and Override
          September 25, 2003 10:50 PM      
          "Don't let the fear that testing can't catch all bugs stop you from writing the tests that will catch most bugs."
          --Martin Fowler

          Similarly, some nice compiler features might not be able to catch all bugs, but I'm not fear to embrace them if they can catch some. Explicit overriding can catch some bug at cost of just few keystrokes. I prefer to type them rather than spending time in debugger or writing trivial unit-test. Unit-test is not the answer for everything. I write unit-test for most of my code recently, but not all.

          Anyway, luckily, as my experience in OO-design grows, I've found most of the time the method I'm overriding is abstract. :)
          • Geoff
             
            Posts: 6 / Nickname: geoffs / Registered: April 24, 2003 6:15 AM
            Re: Versioning, Virtual, and Override
            September 26, 2003 7:31 PM      
            One feature I've found myself wanting recently is the ability to indicate that a class does not add any methods to the public interface of it's parent (class or interface). Using Java terms, I'm thinking of keywords like 'only_implements' and 'only_extends'; perhaps the 'purely_subsitutable' would be better. The rule would be that the child class can have no public methods/attributes that are not defined in the parent.

            A side effect of this feature would be to allow the compiler to detect when a method intended as an override no longer has a match in the parent, but my primary interest is allowing a developer to communicate/express the intent that a sub-class does not add anything to the contract/interface of the parent, it merely changes the implementation.

            In some respects, the C# mechanism is too fine-grained.

            Cheers,

            Geoff Sobering
      • Jon
         
        Posts: 2 / Nickname: jstrayer / Registered: September 19, 2003 6:58 AM
        Re: Versioning, Virtual, and Override
        October 1, 2003 7:43 AM      
        > Without explicit"override" keyword the mis-typed method
        > will undesireably become a new method.

        Which you will find about 10 seconds into your first unit test.


        > Also, without override it's must be
        > very difficult to change base-class method name, since the
        > compiler cannot help you find out where that method was
        > overriden in the sub-classes.

        No, but the editor can. And if it misses it, the unit tests will point it out.
        • David
           
          Posts: 3 / Nickname: davj / Registered: September 27, 2003 1:19 AM
          Re: Versioning, Virtual, and Override
          October 10, 2003 5:49 AM      
          >However, the original quote doesn't mention which package the subclass resides in.

          That is true.The original quote is a blanket statement:"instance methods are virtual by default"
          Not: "instance methods are somtimes virtual by default"

          >A class a.C that extends a.A and overrides x

          When C shares the SAME package (a) as A ???? - this is a unique scenario.

          >In those (common) cases, then, even methods with default protection are "virtual"

          The MOST comon case with default protection is for a child class ( C )
          to be in a different package as A (a) and to be *NOT* virtual.


          >HotSpot may statically bind them as an optimization?... unless the jar containing a.A is sealed?

          Hotspot has NOTHING to do with it. Hotspot or no hotspot.Sealed or unsealed.
          Instance methods are *NOT* virtual by default. To say otherwise is baffling.


          Its really very simple:
          protected or public - Virtual
          private or default(package) - NOT virtual (If you say sometimes - go ahead).


          > I thought that Anders' most compelling argument for having non-virtual
          > be the default was that people don't usually design for subclassing.

          I am baffled.The most compelling argument for using virtual methods
          is that they are more intuitive. Polymophism requires dynamic binding.


          >The point about performance is a bit fuzzier. Bjarne Stroustrup brought up the performance
          >cost of virtual methods compared to non-virtual ones in his interview this past week.

          Performance costs are negligible when compared to maintenance costs. Build tools are going
          to be overworked trying to update all your high performance inlined methods.
      • Vincent
         
        Posts: 40 / Nickname: vincent / Registered: November 13, 2002 7:25 AM
        Re: Versioning, Virtual, and Override
        September 17, 2003 1:42 AM      
        > Also, without override it's must be
        > very difficult to change base-class method name, since the
        > compiler cannot help you find out where that method was
        > overriden in the sub-classes.

        Once a base class has been published and others have started using it then you may never have visibility of the sub-classes that others have based upon it. When that's the case, the presence or absence of a keyword such as overrides is surely acedemic.

        Vince.
        • Sakesun
           
          Posts: 8 / Nickname: sakesun / Registered: August 18, 2003 10:00 PM
          Re: Versioning, Virtual, and Override
          September 17, 2003 3:48 AM      
          > Once a base class has been published and others have
          > started using it then you may never have visibility of the
          > sub-classes that others have based upon it. When that's
          > the case, the presence or absence of a keyword such as
          > overrides is surely acedemic.

          Changing base-class method name can happen even on unpublished base class. C# (or Delphi) programmer can be more confident in changing method name while they are coding than java (or c++). A fancy refactoring tool can help java on this issue however.

          Also, I think it's more explicit for someone reading the code later, to know which method was intend to be a new one or an overriding one.
          • tushar
             
            Posts: 2 / Nickname: tusha0 / Registered: February 11, 2003 0:11 PM
            Re: Versioning, Virtual, and Override
            September 17, 2003 9:51 AM      
            I currently work on a fairly sizable Java code base (approx. 220,000+ lines). I've seen two different defects this year caused by the signature of a virtual method being changed by the addition of a single parameter - causing the overridden methods in derived classes to be silently ignored by virtual calls :-) Scary stuff.

            When you change the signature of a method, do you remember to check if there are any overridden methods that might fall off the shelf? I don't, and I don't know anyone that meticulous.

            The trouble is that unless you have enough tests, you won't know about the side effects of your minor signature changes until much later. javac certainly doesn't tell you!

            For this horrible reason, I've been trying to get into the habit of using Eclipse's 'Refactor->Rename', or 'Refactor->Change Method Signature' actions for every signature change :-)
            • Robert C.
               
              Posts: 5 / Nickname: unclebob / Registered: April 25, 2003 6:39 AM
              Re: Versioning, Virtual, and Override
              September 23, 2003 10:45 AM      
              > I currently work on a fairly sizable Java code base
              > (approx. 220,000+ lines). I've seen two different defects
              > this year caused by the signature of a virtual method
              > being changed by the addition of a single parameter -
              > causing the overridden methods in derived classes to be
              > silently ignored by virtual calls :-) Scary stuff.

              What's scary is that you didn't write the unit tests that would have found that before it became a significant problem. Test Driven Development is a cure for this kind of ill.

              > When you change the signature of a method, do you remember
              > to check if there are any overridden methods that might
              > fall off the shelf? I don't, and I don't know anyone that
              > meticulous.

              Do you run all the unit tests in the system after you make that change? When you do, do they catch the error? If not, why not?

              > The trouble is that unless you have enough tests, you
              > won't know about the side effects of your minor signature
              > changes until much later. javac certainly doesn't tell
              > you!

              In that case the trouble is that you don't have enough tests.

              > For this horrible reason, I've been trying to get into the
              > habit of using Eclipse's 'Refactor->Rename', or
              > 'Refactor->Change Method Signature' actions for every
              > signature change :-)

              Always a good idea. Eclipse or (better yet) IntelliJ provide wonderful tools for making changes like that. And tests are the way to be sure that those changes don't harm you.
          • Matt
             
            Posts: 62 / Nickname: matt / Registered: February 6, 2002 7:27 AM
            Re: Versioning, Virtual, and Override
            September 17, 2003 9:55 AM      
            Having now done plenty of C++, Delphi, Java and C#, I'd say there is no particular advantage to the more explicit inheritance mark-up in C# to offset the annoyance of extra typing and spurious (unrelated to the task I'm really working on and trying to think about) decision-making. The problems it ostensibly solves don't seem to be big ones, they are corner-cases and the solution only shifts to different problems. Conversely, I never had much of a problem in other languages with accidentally overriding base methods -- is this really such a common problem that it needs to be so aggressively tackled? Anyone else out there have experiences where this was a huge problem? Would the C# syntax have solved it?

            As far as versioning goes, I thought that the side-by-side execution of assemblies was intended to solve problems arising from interface (and implementation) changes. Amusingly, the experience I've had so far with this is that the bloated, but unfortunately commonly-used, MSI installer's most common behavior shoots this feature right in the head. Usually, when you upgrade a software package, it cleverly does an uninstall+install, effectively removing all the assemblies it uses from the Global Assembly Cache, then installing the new versions; if any other compoents depend on these assemblies and didn't update the reference count (a common mistake), they are completely hosed and will unceremoniously croak on starup -- not much better than "dll hell," if you ask me. In any cases, it seems like this particular explicit stamping of a method's vituality doesn't solve the problem by any means.

            Anders was complaining that in Java, designers don't use the final keyword often enough. If this is a problem, then why does C# have any default at all? Why not force the designer to declare all methods virtual or final, then there is no need for the override and new silliness. (By the way, overloading the meaning of new in this way is probably especially confusing for new (!) programmers -- I was a little confused on the meaning of using when I first started in C#, because it is likewise overloaded and used in to completely different contexts).

            The only real advantage I can see to this is performance, since methods are all final by default. This helps particularly well when touting C# performance over Java's by doing little comparisions between C# and Java code speed, because most observers will fail to notice that they are comparing a C# program running final methods with a Java program running virtual methods. However, I also think that people pay too much attention to the performance effects of virtual vs. final, which I think are small compared to bigger inefficiencies that are usually just bugs in design or coding of a particular subsystem.
            • Geoff
               
              Posts: 6 / Nickname: geoffs / Registered: April 24, 2003 6:15 AM
              Re: Versioning, Virtual, and Override
              September 19, 2003 7:48 AM      
              > Anders was complaining that in Java, designers don't use
              > the final keyword often enough. If this is a
              > problem, then why does C# have any default at all?
              > Why not force the designer to declare all methods
              > virtual or final ...
              > The only real advantage I can see to this is performance,
              > since methods are all final by default
              > However, I also think that people pay too much
              > attention to the performance effects of virtual vs.
              > final

              I agree 100% that performance is a red-herring. However, I believe there is a very strong design reason for the explicit use of virtual and final. As Hejlsberg points out, developers do a very poor job of considering the two APIs that every class exports: 1) the "client API" (i.e. all public methods), and 2) the "extension API" (i.e. all protected and virtual methods). I personally try and keep both in mind, and find that most of my methods are public final, protected final, or some flavor of abstract. Rarely do I find the case where I need to allow a sub-class to over-ride a method (and especially, a public method) on a super-class (LSP is a hash mistress!); more often I find that the extension API is more clearly defined (and controlled) using either a protected abstract or virtual protected method (in the latter case, commonly with an empty body) in a sort of Template Method pattern sense. This gives the extension developer a specific place to alter a specific behavior of the class, while allowing the super-class to protect it's client API contract.

              > ... there is no particular advantage to the more explicit
              > inheritance mark-up in C# to offset the annoyance of extra
              > typing and spurious (unrelated to the task I'm really
              > working on and trying to think about) decision-making.
              > The problems it ostensibly solves don't seem to be big
              > ones, they are corner-cases and the solution only
              > shifts to different problems ...

              I agree. For example, Hejlsberg notes that in C#, if a new method (ex. foo()) is added to a base-class when a sub-class has already used the same name, then:

              >> Now there are two virtual foos. There are two VTBL
              >> slots. The derived foo hides the base foo, but that's
              >> fine. The base foo wasn't even there when the derived
              >> foo was written, so it's not like there's anything
              >> wrong with hiding this new functionality.

              This is all true if the sub-class had a virtual foo(), but what if the sub-class developer had not intended his/her foo() to be part of the extension API of the class and had correctly declared it 'final'? Similarly, what if the base-class developer did not intend the new foo() method to be part of the base-class extension API, and declared it 'final'? I can't think of a reasonable way to resolve either case other than a compile/link error. Note that Hejlsberg's argument for the desirability of 'final'ity for methods which are not explicitly part of the extension API would make it more likely that one (or both) of the above cases would occur and nothing is gained by the C# way of doing things (or worse, if some language hack silently "resolves" the problem then one is left with very confusing code).

              Cheers,

              Geoff Sobering
            • Bill
               
              Posts: 409 / Nickname: bv / Registered: January 17, 2002 4:28 PM
              Re: Versioning, Virtual, and Override
              September 27, 2003 10:57 PM      
              > Having now done plenty of C++, Delphi, Java and C#, I'd
              > say there is no particular advantage to the more explicit
              > inheritance mark-up in C# to offset the annoyance of extra
              > typing and spurious (unrelated to the task I'm really
              > working on and trying to think about) decision-making.
              > The problems it ostensibly solves don't seem to be big
              > ig ones, they are corner-cases and the solution only
              > shifts to different problems. Conversely, I never had
              > much of a problem in other languages with
              > accidentally overriding base methods -- is this
              > really such a common problem that it needs to be so
              > aggressively tackled? Anyone else out there have
              > experiences where this was a huge problem? Would the C#
              > syntax have solved it?

              The people who struggle with the breakage problem are those who create reusable libraries that have wide distribution, for example, Microsoft with the .NET Framework and Sun/Java Community with the Java API. Most programmers are able to access all subclasses of their classes. That doesn't mean that it isn't a good idea. It is unlikely that this will happen to any individual, but it is likely that it will happen to some people for any Java release. The breakage can be completely avoided by expressing the programmer's intent more clearly with something like an override keyword. Whether the extra finger typing is worth solving this problem is a judgement call, but it does solve a real problem.

              The point about performance is a bit fuzzier. Bjarne Stroustrup brought up the performance cost of virtual methods compared to non-virtual ones in his interview this past week. It does exist in the C++ world, but the world of VMs is a bit murkier. Most modern JVMs in long running processes can inline virtual method calls if they matter to performance, so there's no cost really in that kind of situation.

              I do also agree with Anders that people don't usually really design classes to be subclassed. I think Anders' point about that fits with Josh Bloch's comments in Effective Java that we should design for inheritance or disallow it. (Note that this was also coming from someone who works with widely distributed reusable components.) I thought that Anders' most compelling argument for having non-virtual be the default was that people don't usually design for subclassing.
              • David
                 
                Posts: 3 / Nickname: davj / Registered: September 27, 2003 1:19 AM
                Re: Versioning, Virtual, and Override
                October 10, 2003 6:49 AM      
                Bill Venners> I thought that Anders' most compelling argument for having non-virtual be the default was that people don't usually design for subclassing.

                I could not disagree more.
                People that don't design for subclassing probably dont expect thier classes to be subclassed (unexpected children).
                Users of these Non-virtual (subclass) methods may need Asprin -they may suffer head-aches.

                A class with dynamicly bound methods is better suited (designed?)to be subclassed than a class with static (NON-virtual) methods.

                A class with default (non virtual) methods probably should be declared final.
    • George A
       
      Posts: 3 / Nickname: zgas / Registered: September 25, 2003 3:46 AM
      Re: Versioning, Virtual, and Override
      September 25, 2003 0:23 PM      
      We have experienced the corner case where unit testing would NOT have caught the problem.

      Specifically we use the Generative Pattern (code generates the base class) with externally provided meta-data. We then override the behavior in the manually coded sub-class(es) where appropriate. Since we don't write tests for all the "lame" generated code, but only the overridden methods, the fact that the meta-data was changed and the base class's method is GONE, would not be caught. In this case at least having the option of specifying that a method is "overriding" would be nice.
      • Todd
         
        Posts: 27 / Nickname: tblanchard / Registered: May 11, 2003 10:11 AM
        Caused by generated code
        October 13, 2003 7:57 PM      
        Generation of code is its own problem as its a violation of Blanchard's Law.

        From a practical standpoint, I find the existence of expllicit virtual/non-virtual control in an OO language to be a frequent barrier to flexibility.

        Many are the shortsighted Java developers who have declared methods final that I wanted to override. Ditto for C++ developers who neglect to declare methods virtual that need to be overridden. These problems would go away if all methods were always dispatched dynamically.

        I definitely don't buy the efficiency argument. Not when I've got a multiGHz computer in my backpack. IOW, I've got nearly 1000 times the computing power of when I started programming. I'm not going to give efficiency a thought until there's a problem. So why are these language designers burdening us with this clutter?

        Wake up and smell the clock rate!
      • Patrick
         
        Posts: 1 / Nickname: padraig / Registered: October 23, 2003 1:16 AM
        Re: Versioning, Virtual, and Override
        October 23, 2003 6:57 AM      
        > We have experienced the corner case where unit testing would NOT have caught the problem.

        Nevertheless, RCM is right. Unit tests and test-driven development are the real issues here.

        With TDD, we no longer have to rely on the mafioso of gigantically complex compilers and language syntax to protect us from type problems, versioning problems, and male pattern baldness. Exhaustive suites of automated unit tests do a much better job of protecting us from arbitrary, radical change, at the application level, than compilers can possibly do.

        Languages like Smalltalk and Ruby anticipate this new kind of freedom, where syntax lucidly reveals programmer intent, uncluttered by gobs of "protective" cruft. Protected by their own tests, instead of compilers, programmers can concentrate their efforts on clarity, simplicity, and (as required) extensibility.
    • Howard
       
      Posts: 25 / Nickname: hlovatt / Registered: March 3, 2003 1:20 PM
      Re: Versioning, Virtual, and Override
      November 13, 2003 8:34 PM      
      I notice that Java 1.5 has @Overrides as part of the annotations extension.
    • Darren
       
      Posts: 2 / Nickname: dhobbs / Registered: January 12, 2004 9:30 PM
      Re: Versioning, Virtual, and Override
      January 13, 2004 2:37 AM      
      If you find yourself suffering because you changed the signature of a method and overriding methods were no longer overriding, you might want to think about using interfaces rather than concrete superclasses. The compiler would then be able to let you know that the implementing class no longer implemented the interface correctly.

      I see a lot of code using concrete inheritance where interfaces would have made far more sense, as well as breaking the brittle dependency chains that can form with deep inheritance trees.

      I rarely find I need to override a concrete (non abstract) method, and on those rare occasions I do, changing the inheritance relationship into one of composition usually leads to a cleaner solution, as well as providing a clean extension point for any future modifications.
    • Darren
       
      Posts: 2 / Nickname: dhobbs / Registered: January 12, 2004 9:30 PM
      Re: Versioning, Virtual, and Override
      January 13, 2004 2:44 AM      
      By making methods final by default, and having to explicitly state which ones can be overridden, you are forcing developers to try and anticipate all possible future uses of the code they write.

      It encourages a sort of protectionist attitude that says 'You're not smart enough to understand how my code works, so I'm going to only let you override the bits that I choose to allow'.

      I write code to be useful, and if someone sees a use for it that I didn't anticipate, by overriding a method, then thats a good thing and should be lauded, not repressed.
      • Thomas
         
        Posts: 2 / Nickname: teyde / Registered: April 11, 2004 6:20 AM
        Re: Versioning, Virtual, and Override
        April 14, 2004 4:29 PM      
        Why do I have to express my intentions in two places? First a virtual, then an override? Wouldn't the override do? It's very annoying when I refactor and move the common part of two methods up to the superclass and have to write both virtual and override. Talk about flow killer!

        There is an other issue about the non-virtualness:


        ArrayList l = new ArrayList();
        l.Add(new MyBase());
        l.Add(new MyDerived());

        foreach (MyBase b in l)
        {
        l.DoSomething();
        }


        l.DoSomething() will never call MyDerived.DoSomething() when no keywords are used. That behaviour contradicts what I find intuitive: That it is the instance you call the method on which should decide which implementation to use, not the reference type.
        • Thomas
           
          Posts: 2 / Nickname: teyde / Registered: April 11, 2004 6:20 AM
          Re: Versioning, Virtual, and Override
          April 14, 2004 4:34 PM      
          And, yes, I agree with Darren. In my words: I think it's arrogant to imagine that I can predict every future use of my code.

          The last days I have struggled with the User Interface Application Block. Every attempt to make it do what I want has been effectively been stopped by a sealed class, an internal class or a static method. And the object creation happens deep down below the sea level. It's impossible to inject a specialized class into that mess. Not all classes can be correctly created from config information alone.
    • Shital
       
      Posts: 1 / Nickname: sytelus / Registered: November 15, 2004 7:46 AM
      Re: Versioning, Virtual, and Override
      November 15, 2004 0:53 PM      
      Here's my take:

      http://www.shitalshah.com/blog/default.aspx

      One major issue that Anders mentioned was performance issue. I think its easy to mitigate the performance issue by making hot methods non-virtual explicitly. Also this is applicable to only public methods. Its far more difficult to analyse every side effect of overriding every method by someone someway. The problem is that people does want to let their methods overridable but they don't have time to analyse effects and make promise that overriding would work normally. So the solution is compiler warning rather then making it fianl-by-default.