Discussions

News: C++ Creator talks about Object Orientation

  1. C++ Creator talks about Object Orientation (82 messages)

    Bjarne Stroustrup, the designer and original implementer of C++, is interviewed by Bill Venners about the perils of staying too low level and venturing too object-oriented. Although Bjarne does talk about C++, he also makes comments on Java, and his thoughts are interesting.

    He starts off by saying that developers can tend to hit too extemes on their designs:

    1. C++ == C + a little bit springled on top
       
       We have all seen this code. It may have "class", and "new" as keywords, but it is basically C code.

    2. Everything is an object

       Bjarne says: "They believe that you should do everything by creating a class as part of a class hierarchy with lots of virtual functions. This is the kind of thinking that's reflected in a language like Java for instance, but a lot of things don't fit into class hierarchies. An integer shouldn't be part of a class hierarchy. It doesn't need to. It costs you to put it there. And it's very hard to do elegantly."

    He then delves into good class design, using invariants, and simple interfaces. Interesting stuff, from an interesting chap.

    Read A Conversation with Bjarne Stroustrup

    Threaded Messages (82)

  2. Stroustrup is obviously a very, very intelligent man, but I think to some extent he's blinded himself to the problems inherent in C++. Alot of that may the nature of the work he does, but I think alot also is due to an inherent distrust in languages that aren't "close to the metal", and which aren't in tune with the idea of Unix processes from the original 70's Unix core. For all of his talk about robustness, the plain fact is that I see a wide variety of core dumps from C++ programs on a daily basis - programs written by very, very sharp people who know the language inside out.

    There is, perhaps, a place in the world for a generics/OOP oriented C, but I think that place is much, much smaller than Stroustrup believes. The legacy of obsessive performance mindedness, ancient linker limitations, and a language mindset that is a effectively a model of Unix processes in the 70s is going to doom alot of us to alot of pain for decades to come. In which lot I sadly include myself - in addition to my primarily Java focus I still have to slog alot of C++ code on the side, and "slog" is the most charitable word I can come up with.

        -Mike
  3. Ugh, you said it...[ Go to top ]

    Slather, spotch, flotch, learch...

    Whatever word you want to use, navigating c++ code in emacs is torture not because of the difficulty involved - emacs (or jed, pico, vi) is just another editor. What makes it painful is knowing how much easier it would be to develop using a nice Java IDE on <insert your platform here>.

    There is a rather large sect of the Unix-process people you refer to, and they don't give-up easily. It will take a few of us breaking the mold and really, truly demonstrating the power of Java/J2EE before people really start jumping on board.

    I think a lot of people got burned by Java in the past few years. Since they jumped on the ship and the ship started taking on water (the Java ship, that is) from all the weight, the hull has since been reinforced. Java has come a very long way, and it is a pleasure to do my job via Java. I can't say that I have the same fun writing c, c++, or even perl.

    Best,

    JCD
  4. Ugh, you said it...[ Go to top ]

    I actually have no problem with C. It has its limitations, but it's very straightforward. I see it as a shining example of truth in advertising - "This language is very fast, very low level, and you'd better know what the hell you're doing".

    I have a love/hate relationship with Perl. I love using it for many tasks. But it's the only language that I _literally_ relearn every year. Yes, literally - I go away for several months doing other things, come back to Perl, and then I have to crack the books all over again.

    C++ is the only language that I have a hate/hate/[hate even more] relationship with. I would much rather use C and be guaranteed that not only am I constrained to the basics, but so is every other programmer working along side me - both the professionals and the occasional nutjobs.

         -Mike
  5. i hear you...[ Go to top ]

    i have the following problem: there is a cool C++ application which i would like to extend.. It's in the domain of automatic planning, hence a typical domain where "high performance" is the primary goal.

    I am not sure whether i should directly work with the original C++ code (and get into this terrible hell of memory leaks, etc. again), or port it to java first and start from there.

    The questions i have to answer myself are:
    * how much slower will the Java version be (is factor 1.5 correct or is it even slower)?
    * what is more expensive: a) porting a C++ application (20-30 class) to Java or b) working on C++ code with all the obstacles and distractions...

    had anyone such a decision to make ?

    cheers
    Joe
  6. C++ -> Java[ Go to top ]

    I Joachim,

    I can't tell you how much slower Java *is* than C/C++, but I had experience about a HTML parser writen in C and Lex, which was ported to Java (1.2 version) + JavaCC. It was slower by a foctor of two, but fet in mind that it was on the first semester of 2000. Big improvment have been made from now on.

    I also experienced a porting of a hudge application writen in C++ (with templates and all the C++ stuff that make it ugly), something like 250 classes and 100 000 lines of code. It was quite straightforward except that :
     - you don't have templates in Java, so you must create has many classes as you have differents templates
     - beware of function's arguments that are not pointers (I mean, passing an object by value, not a reference); you *must* pass a copy of this object if your function is to modify it, or assume the side effect!
     - if the code use the String class to manipulate strings (the article is pretty clear on this !), it's perfect. If not, you'll spend time to translate all the while (*d++ = *s++) {} !!! Not to mention pointer's manipulation to get a substring and so on.

    It's just my experience, and I must admit that knowing well both langages make things easier.

    Emmanuel Lécharny
  7. C++ -> Java[ Go to top ]

    hi Emmanuel !

    thanks for the insights and hints !

    (PS: yea, for the most part, the code is written in modern style, making use of std::string& and of the whole STL... so.. there is hope ;-)

    cheers
    joe
  8. C++ -> Java[ Go to top ]

    \lecharny emmanuel\
     - you don't have templates in Java, so you must create has many classes as you have differents templates
    \lecharny emmanuel\

    If you absolutely have to have compile-time safety this is true. If you can forgoe this safety a bit, you can use common ancestors (all the way up to Object) and collapse those "N" classes into a single one. In practice this is what most Java developers do, and it works quite well.

    \lecharny emmanuel\
     - beware of function's arguments that are not pointers (I mean, passing an object by value, not a reference); you *must* pass a copy of this object if your function is to modify it, or assume the side effect!
    \lecharny emmanuel\

    Java's calling convention are actually pretty simple (at least compared to C++).

    All objects are passed by reference, all primitives are passed by value. There is no automatic way to pass an object by value.

         -Mike
  9. C++ -> Java[ Go to top ]

    <Mike>
    Java's calling convention are actually pretty simple (at least compared to C++).

    All objects are passed by reference, all primitives are passed by value. There is no automatic way to pass an object by value.
    </Mike>

    Actually, it's even simpler than that: Everything is pass-by-value. It just *feels* like objects use pass-by-reference since you're really passing a reference, not an object.

    Kris
  10. C++ -> Java[ Go to top ]

    \Kris Schneider\
    Actually, it's even simpler than that: Everything is pass-by-value. It just *feels* like objects use pass-by-reference since you're really passing a reference, not an object.
    \Kris Schneider\

    Yes, that's true. But most C++ people get very confused when you try to explain it that way, and you have to start explaining why:

        MyClass foo(1,2,3);

    ...doesn't work, or why you can't say:

        (*foo).blah

    and the whole conversation just slides downhill from there into the 1,001 ways you can do such things in C++, and the idea of the Java semantics is hopelessly lost. And trying to explain what a Java reference is only makes it worse as it gets hopelessly tangled in C++ references, then someone asks if you can add 1 to get to the next one, and then my head starts to slowly implode on itself...

         -Mike
  11. C++ -> Java / Templates[ Go to top ]

    \mike spille\
    ... you can use common ancestors (all the way up to Object) and collapse those "N" classes into a single one. ...
    \mike spille\

    This is a way to handle the issue, but that means 'cast'. I just prefer to create N classes whith one ancestor that casts objects. It's obviously painfull to cast a myHashMap.get(key) to the Class you have stored, because that means that you must remember which type is the stored object. Not to mention that you could have stored an instance of an other class in yout HashMap! This is just why Templates are great ...
  12. C++ -> Java / Templates[ Go to top ]

    \lecharny emmanuel\
    This is a way to handle the issue, but that means 'cast'. I just prefer to create N classes whith one ancestor that casts objects. It's obviously painfull to cast a myHashMap.get(key) to the Class you have stored, because that means that you must remember which type is the stored object.
    \lecharny emmanuel\

    This is something that seems painful in theory and when you first encounter it.

    In practice, after years of Java development, you find that it's not much of an issue. In the absence of templates, and combined with Java's excellent runtime typing, casts are actually pretty safe. And the alternative of creating "N" classes is considered _far_ more painful than casts are.

    \lecharny emmanuel\
     Not to mention that you could have stored an instance of an other class in yout HashMap! This is just why Templates are great ...
    \lecharny emmanuel\

    Again, this almost never happens in practice. Despite what early OO theorists thought about use of heterogenous collections, it's just about never done in practice - collections are almost always used with a homogenous type. Mistakes are very, very quickly caught. And, again, the common Object ancestor and the runtime typing are extremely handy here in catching problems early.

    Don't get me wrong - it would be nice to have statically typed collections (and static typing for similar constructs), and supposedly Java 1.5 will have that. But for me it's firmly in the "nice" category, not a must have.

    Certainly, in the C++ case you have what I consider a textbook example of good intentions meeting horrible design. The concept of generics is sound and has many practical applications. But the physical incarnation of generics in C++ - templates - almost entirely blows the good intentions out of the water.

    Yes, you get some nice things out of templates in C++, but you pay a horrific cost in complexity - complexity at many levels and from different directions. To me this is a case where the benefits are outweighed (swamped, really) by the downsides.

         -Mike
  13. C++ -> Java / Templates[ Go to top ]

    I must admit that I share your position. I've been desesperate the first time I saw this 'syntaxic sugar' used to create templates (on those times where C++ was a C-preprocessor, RIP glockenspiel), and found it awfull and useless.

    If you convince yourself that stack<MyClass> looks-like (MyClass)stack, you are really safe using casts and Objects.

    In my experience, porting C++ app not writen by myself to Java, I had 60 classes that were templates : Tupe<something>. I found it usefull to create TupleType1, TupleClass2, and so on, because it was easier to read. It took me half an hour to create those 60 classes, because they were wrappers extending an ancestor that was doing the real job. It was just a copy/paste operation, renaming the class and changing the cast (thanks eclipse!).

    I don't say that, on a new project, I will create those 60 classes. I did it to stick with the C++ design of the ported application...

    It helped me whan I had to store int and long as Tuples, because I didn't had to bother about creating new Integers and Longs :

    TupleInt tupleInt = new TupleInt();
    ...
    tupleInt.add(3);
    int sixthValue = tupleInt.get(6);
    ...

    is easier than :

    ArrayList intArrayList = new ArrayList();
    ...
    intHashMap.add(new Integer(3));
    int sixthValue = ((Integer).intArrayListget(6)).intValue();
    ...
  14. An aside on casts....[ Go to top ]

    ...as an aside, you should realize that casting in the Java world is whole different ballgame than it is in the C++ world.

    In the C++ world, traditionally casts have been demonized, and with good reason. In the olden days, a bad cast could easily lead to corrupted data or core dumps/GPFs. Even with the advent of the "new" safe casting styles, casts are still demonized in C++.

    Alot of C++ "experts" will give you all sorts of OO reasons why casts are bad, and the majority of them entirely miss the real issues. The reasoning behind casting being bad is tied entirely to the C++ implementation and has little to do with general OO theory.

    In C++, casting is bad because there is no single-rooted hierarchy. It's bad because there are some constructs that have no safe cast to help you out of a jam. It's bad because C++ runtime typing/discovery support sucks rotten eggs (yes, even with RTTI it still sucks).

    In more dynamic languages with single-rooted object hierarchies, casting isn't demonized at all - it's more of a fact of life. I don't encourage people to cast willy-nilly all over the place - encapsulation and minimal knowledge of details is always a good thing - but there's a difference between the place casting has in general OO theory, and with dynamic/single rooted languages in particular, vs. what the casting issues are in C++.

         -Mike
  15. An aside on casts....[ Go to top ]

    "Alot of C++ "experts" will give you all sorts of OO reasons why casts are bad, and the majority of them entirely miss the real issues. "

    No way, dude.

    Casting can take away compile time type checking. In general, compile time type checking is preferable to run time type checking.

    Casting also means that the developer has to "know" something more than what's there.
    Assumptions have to be made. That weakens the system.

    I'm of the opinion that if you have to cast something than something is wrong with the design, especially dynamic_casts. Stroustroup makes the same point.

    In Java, of course, you must cast things left and right. Generics being added will help a little. But the implementation still lacks a little.
  16. i hear you...[ Go to top ]

    i have the following problem: there is a cool C++ application which i would like to extend.. It's in the domain of automatic planning, hence a typical domain where "high performance" is the primary goal.

    >
    > I am not sure whether i should directly work with the original C++ code (and get into this terrible hell of memory leaks, etc. again), or port it to java first and start from there.

    I'm actually working on a program in a similar area of automatic planning. It is being written in Java as a fresh solution approach to replacing a 20 year old legacy system. As far as Java performance for just loop cranking and converting input data into optimizable planning constraints, I would say Java should be an OK choice, but you should be concerned about choosing a JVM. Not all are created equal. We are deploying on windows, so there are some additional JVMs for Linux I couldn't try, but I compared the same 100% CPU program run across Sun (1.3.1 and 1.4.1), IBM 1.3 and JRockit 8.1. I can send you my full matrix of times I recorded, but by significant margins JRockit > Sun > IBM. And of all weird things, JRockit running code compiled by IBM was faster than when compiled by JRockit.

    Also, with Java, there are a number of performance tools that will help you determine your bottlenecks, although I have found they can take a while to run. You will be amazed by the diffence different data structure implementations have (Sun JDK HashMaps vs Trove hash maps for example. google for Trove and you should find and article on Orielly network about this).

    So I think Java is a good choice where you can at least focus on the problem and not the pointers, but Java != Java in all cases of vendors and platforms.

    Daniel
  17. Ugh, you said it...[ Go to top ]

    Mike, I completely agree. I really enjoy writing code in C; to me it's "high level assembler" -- to be used when in "hardware mode" and need to work at that level.

    But when I'm in "software/abstraction/Object mode", Java feels like the best thing currently available for working *that* level.

    C++ always felt like it was awkwardly trying to straddle both modes -- "high level assembler with Objects." Yeah, you could make it work, but you could probably make Objects work in FORTRAN too, or any other language, given enough rules and conventions applied on top. I know C++ does more than that (e.g. vtables) but it still felt it was stretching to be more than it was.

    Randy
  18. Ugh, you said it...[ Go to top ]

    I like using Perl for various server automation tasks - it is basically OO, and there are some pretty cool libs for it, and the interpreter comes installed on almost every distribution of linux. For anything else, it is pretty dangerous, IMHO.

    I haven't used C since my machine language course in College (4 years ago). Any application of C for me could easily be replaced by Java. If there were performance concerns that could be solved by a hardware upgrade, it is easy to cost-justify the hardware cost via cohesion and consistency in platform (using Java across the board), as well as potential maintenance costs with maintaining C code (Colleges are pumping out Java programmers at a furious rate these days - the MIS program at The University of Arizona's Eller College, a top 4 program ahead of Stanford, strongly suggests a working knowledge of Java).
  19. What about Java?[ Go to top ]

    I agree with Mike about preferring C to C++. C++ is great if you're working alone, but once you add another person (or a larger team) these "subsets" do cause a lot of havoc.

    That being said C++ was designed to be a "better C" and when created was saddled with C compatability. Java was built from scratch, but now as it's maturing, it's saddled with it's own backwards compatability. Mike's examples (which brought up painful memories :) ) about pointer vs reference and all the different collection libraries makes me think about the similiarities with Java. Consider io vs nio, jdbc vs ejb vs jdo, awt vs swing, and that's just in the core. When you extend to defacto-standard open-source, look at Struts vs WebWork, log4j vs java logging, etc. Some are obvious improvements over others, but everyone still has there own "subset" they prefer or are familiar with.

    Is it just me or is standard java (and I include J2EE in this) starting down the same path where there are so many standard competing options that we are heading for the same fate?

    Trevor

    I'm not an anti-java guy, I love the language and make a living using it, but I'm wondering if anyone else sees the same warning signs (or if I'm just out-to-lunch).
  20. Ugh, you said it...[ Go to top ]

    I think a lot of people got burned by Java in the past few years. Since they jumped on the ship and the ship started taking on water (the Java ship, that is) from all the weight, the hull has since been reinforced.
    Would that be a good idea? Unless they used something like titanium, wouldn't reinforcement increase the weight? Perhaps trying to reduce the amount of ballast would be wiser...

    Sorry, couldn't resist :-)
  21. "...I see a wide variety of core dumps from C++ programs on a daily basis - programs written by very, very sharp people who know the language inside out.
    "

    The article mentions the issue of people using new, malloc, etc. That is a cause for much of those core dumps I bet.
    If the developers really know the language inside out they wouldn't have core dumps.
    Using smart pointers and leveraging the fact that desuctors are called at determinable times makes memory management and resource management rather easy.

    "I still have to slog alot of C++ code on the side, and "slog" is the most charitable word I can come up with. "

    I'm of a different opinion. I've written software professionaly using:
    Pascal, C, C++, and now Java.

    C++ was a big improvement over C but Java, in many respects, was a big step backward from C++.
  22. \Sartoris Snopes\
    The article mentions the issue of people using new, malloc, etc. That is a cause for much of those core dumps I bet.
    \Sartoris Snopes\

    No, the vast majority of the code uses plain old new and plain old delete.

    A big problem in a language with C++ is object-lifetime, object ownership, and invalid deletes.

    Is this object on the stack or heap? It's a rather important distinction, and also rather difficult to tell. Do I own it and have the responsibility to delete it (or, damn, is it on the stack)? Do I do delete or delete[]?

    Think also on double-deletes - more common than you might think.

    A trivial oversight results in a destructor not being virtual when it should be - again, boom.

    Using a 3rd party API with (void *) callbacks (still very prevalent) - very easy to get the cast wrong.

    Compiler template bugs - oh what fun is to ride on that one.

    Holding a reference to a stack based object and dereferencing after it's out of scope - Woo-who, now we're cookin!

    Occasionally, people slip up on NULL checks. In Java, that's an NPE, in C++ that's core dump city. In C++ it's trivial to screw up and use an uninitialized value off the stack. Again - core dump city _if you're lucky_, totally screwed up program that still runs whackily if you're not lucky.

    If you try to be a very, very good boy and use only "modern" C++ exclusively with auto_ptr and smart pointers and the STL and templates and what have you, you still get screwed because not all APIs/frameworks will use them. And not all your compatriots will use them. And you probably have a mountain of legacy code that does not use them. And you are leveraging a C library which obviously can't use them.

    Shall I go on Sartoris and enumerate further in how many different ways a competent C++ developer can get unanticipated core dumps? Even hard-to-reproduce ones?

    \Sartoris Snopes\
    If the developers really know the language inside out they wouldn't have core dumps.
    \Sartoris Snopes\

    There are only two words to respond to on that - bull and shit.

    \Sartoris Snopes\
    Using smart pointers and leveraging the fact that desuctors are called at determinable times makes memory management and resource management rather easy.
    \Sartoris Snopes\

    Smart pointers help, as a poor-man's reference counting garbage collector. However, even when they help not everyone uses them. Even when you try, you are 100% guaranteed to be using someone else's framework or API which does not use them.

    I've encountered several people who have told me "resource management can be easy in C++". In every case I've investigated in depth, its turned out that their idea of "easy" was radically different from my own.

         -Mike
  23. I can't agree more with you Mike. Your comments about the problems using C++ bring up very painful memories. Gee, the single most important thing in improving the quality of my life was to switch to Java.
  24. "A big problem in a language with C++ is object-lifetime, object ownership, and invalid deletes. "

    If you create a bunch of global objects or have a poor design these can be problems.
    Otherwise, if object a owns/aggregates/etc another object which it creates on the heap then it deletes it. This is done quite easily usign auto_ptrs.

    "Think also on double-deletes - more common than you might think. "
    Set the darn thing to null after the call to delete. No more problem. Or, again, moderately good design makes this a non-problem.

    "A trivial oversight results in a destructor not being virtual when it should be - again, boom. "

    A trivial fix takes care of this.

    I'm getting bored with this.

    \Sartoris Snopes\
    If the developers really know the language inside out they wouldn't have core dumps.
    \Sartoris Snopes\

    There are only two words to respond to on that - bull and shit.

    I've worked on several very high profile projects 100% C++ that after normal testing had none of the problems you describe. So, my statement is true.
    (I must admit to one project that got a bit hairy - but that was because of CORBA complexities).

    "I've encountered several people who have told me "resource management can be easy in C++". In every case I've investigated in depth, its turned out that their idea of "easy" was radically different from my own. "

    Pick your poison. With the Java safety net comes a bit of downside.
  25. \Sartoris Snopes\
    If you create a bunch of global objects or have a poor design these can be problems. Otherwise, if object a owns/aggregates/etc another object which it creates on the heap then it deletes it. This is done quite easily usign auto_ptrs.
    \Sartoris Snopes\

    Any problem which can lead to core dumps in C++ can be managed around, by employing a number of practices (some of which you mention) plus alot of discipline and education of new developers. Likewise, you can release a program in assembler which is 100% bulletproof.

    The question isn't whether or not it can be done; it's how much effort is involved, and how much _true_ safety you have. In my experience, the effort is quite significant to employ all these practices (and to always remember to use them). The reason I call it "significant" is the litany of issues that can easily arise due to C++'s design: you have to remember all of the little traps.

    I also mention "true" safety, because C++ gives you 0, zip, nada true safety. One junior developer creating a minor feature off in the weeds of your program can trivially do:

       char *cp;
       strcpy (cp, "hey there!");

    ...and thereby blow your entire program out of the water _in a mannner hard to reproduce_ (since cp is on the stack with a random value; it may even work for several releases).

    "A trivial oversight results in a destructor not being virtual when it should be - again, boom. "

    \Sartoris Snopes\
    A trivial fix takes care of this.

    I'm getting bored with this.
    \Sartoris Snopes\

    You can trivially fix any of these problems. The problem is that people do mistakes, and C++ has an enormous number of areas where a developer has to track a large number of minute details. And when fallable people do make a mistake, tracking it down can be a real headache (in meanwhile, core dump). Please do not tell me it's trivial to find a non-virtual destructor, or using an uninitialized pointer - it can be damn hard to track down these problems.

    But anyway - the problem is not the triviallity of any one issue. The problem is aggregate weight of all of the issues taken together and slapped in the lap of developers.

    \Sartoris Snopes\
    I've worked on several very high profile projects 100% C++ that after normal testing had none of the problems you describe. So, my statement is true.
    (I must admit to one project that got a bit hairy - but that was because of CORBA complexities).
    \Sartoris Snopes\

    It can be done, as I have admited above. But the development cost to get there can be extremely high, and requires the cooperation of all the developers touching the code. I've seen C++ processes that have run fine for _years_, and then a small change totally destabilized the process. With the end result of several gruelling hours of debugging discovering that the real culprit was a double-free, or uninitialized pointer, or a bad cast, or any number of tiny "trivially fixed" items that coincidentally trashed unusued memory (until new code was added).

        -Mike
  26. Thanks Mike[ Go to top ]

    Your comments are bang on right, and it is such a pleasure to read such excellent analysis.

    Mr. Snopes get a grip, and stop being so clever, there are way too many geeks like you in this world, who value complexity, simply because it strokes their ego to have mastery of it...there are more important considerations, and the key one, is human productivity.


    Mike,

    I don't have any professional experience with C++, i used it in school for about three semesters, and that was quite enough for me to see what a dog's breakfast it was.

    The syntactical complexity is breathtaking, and it was pretty obvious that all of that syntax was designed to help compilers make things super-duper efficient, and had nothing at all to do with making code readable and easy to work with, for humans.

    In C++, compilers come first, humans a distant second.


    When i caught on to Java, 4 or 5 years ago, i set aside a weekend and implemented a simple linked list. The big stumbling block for me was i couldn't figure out how it was possible to *do" anything without pointers. I still chuckle about that, to this day.

    Anyway, the effort did not take a weekend, it took about three hours, and for me, being a student and all, the experience was earth shattering. It felt so liberating to work in Java, and so damn productive, and most importantly the language was really clean and easy to understand, even for a humble student.

    And, if i made a mistake, no core dumps, (holy crap!), just a nice stack trace displayed to your console, that was even kind enough to provide a class name, and line number of where the error occurred.

    But best of all:

           (*), &, (**), (***), ->, ((**)char*), etc, etc, etc...and etc.

    collapses to one thing:

           an object reference


    Anyway, that was enough for me, i was sold, and i haven't looked back, and am now gainfully employed developing advanced J2EE applications, and hobbying with embedded Java chips, and life is good.

    Whenever i talk to my peers from school that went the Win32/MFC/C++ route, i listen to their nightmare development scenarios, and i shudder, and i quietly thank myself for taking that weekend to develop a linked list in Java.


    Thanks for your posting Mike.

    Peter
  27. Thanks Mike[ Go to top ]

    "When i caught on to Java, 4 or 5 years ago, i set aside a weekend and implemented a simple linked list. The big stumbling block for me was i couldn't figure out how it was possible to *do" anything without pointers. I still chuckle about that, to this day. "

    and

    "But best of all:

           (*), &, (**), (***), ->, ((**)char*), etc, etc, etc...and etc.

    collapses to one thing:

           an object reference
    "

    You are helping make the point of the article where BS talks about C++ being used as C with classes. If your code looks like the above then you're not taking advantage of the language.

    In most cases C++ code looks every bit as clean as Java code.

    "The big stumbling block for me was i couldn't figure out how it was possible to *do" anything without pointers. "

    Java object handles are pointers. If you can do it in Java then you can do it in C or C++.

    I think one big stumbling block with this is that objects in C++ that are passed by value are copied. That confueses people.


    "And, if i made a mistake, no core dumps, (holy crap!), just a nice stack trace displayed to your console, that was even kind enough to provide a class name, and line number of where the error occurred. "

    A good C++ IDE will stop right at the offending line in debug mode, too. They even detect memory leaks. It's actually pretty simple.
  28. Clean code[ Go to top ]

    Sartoris:
    In most cases C++ code looks every bit as clean as Java code.

    Of course, this remark can go unchallenged forever because everyone has a different idea of what "clean" code is, but personally, I have written and read a lot (A LOT) of code, both Java and C++ and both on UNIX and Windows (yes, I have even programmed in Java on Win32).

    I started programming in C++ circa 1988, so I used to breathe its syntax day in day out for years.

    The readability of C++ has never come close to that of Java. Ever.

    I am not talking about occasional methods or fragments of code, but at a higher level, when you try to figure out the flow of code, the hierarchy, the sense behind it. The C++ syntax keeps getting in the way, both when you read it but mostly when you write it.

    --
    Cedric
  29. Clean code[ Go to top ]

    You guys are rough!

    "The readability of C++ has never come close to that of Java. Ever. "

    Java syntax comes largely from C/C++. {, for, while, if, foo(), void, int, long, char, [], public, class, constructor form, etc.


    "C++ syntax keeps getting in the way, both when you read it but mostly when you write it. "

    Give me an example, please.
  30. Clean code[ Go to top ]

    \Sartois Snopes\
    Java syntax comes largely from C/C++. {, for, while, if, foo(), void, int, long, char, [], public, class, constructor form, etc.
    \Sartois Snopes\

    Bzzt, thank you for playing. Java is based on C, and has almost (but not quite zero) syntax from C++. All of the non-C pieces in C++ that have a Java equivalent are almost always done completely differently in Java, with the exceptions being highly superficial.

    If you want to truly understand the differences between the two, take a look at a full-featured C++ parser and a full-featured Java parser. Java parsers compared to C++ parsers are like comparing ants to the Empire State building.

    In that vein, the tiny size of Java parsers is reflecting in the pretty tiny effort Java developers go through in figuring out what a given piece of code means. Likewise, the massive C++ parser size directly reflects the effort a human must go through to parse C++.

         -Mike
  31. Clean code[ Go to top ]

    ack
  32. Clean code[ Go to top ]

    Oops, Fat Fingered the lasr one.

    "Bzzt, thank you for playing. Java is based on C, and has almost (but not quite zero) syntax from C++."

    That's like saying integers are real numbers but not complex numbers.
    C++ is a superset of C. If Java is based on C, then it is also based on C++.

    "In that vein, the tiny size of Java parsers is reflecting in the pretty tiny effort Java developers go through in figuring out what a given piece of code means."

    That is a non sequitor.
  33. Clean code[ Go to top ]

    \Sartoris Snopes\
    That's like saying integers are real numbers but not complex numbers.
    C++ is a superset of C. If Java is based on C, then it is also based on C++
    \Sartoris Snopes\

    Ah, no. The useful syntax that Java "borrowed", for lack of a better term, was the C part. Where Java diverged from C, it went on its own (except for some superficial bits).

    Using your rather interesting reasoning, you could also say that Java syntax is based on Objective C because Objective C is based on C.

    Putting it into the realm of the absurd...if in future years someone created D++, E++, etc up to Z++, and Z++ happened to be a superset of C, then by your reasoning Java would be a superset of Z++. Making it really crazy, if the same thing happened with Objective-C, going up to Objective-Z, then you'd say that Java was based simultaneously on the syntax of C, Objective-Z, and Z++ all at the same time. Indeed, you could say that Java is based on Objective-Z even though it doesn't exist at this time.

    \Sartoris Snopes\
    That is a non sequitor.
    \Sartoris Snopes\

    Comparing parser sizes is a demonstration of comparative language complexity, and parser complexity is an indicator of the difficulty a human would have in parsing a language. It's not an absolute comparison, but it can be used as a rough yard stick.

    As such I do not believe it's off-topic or a non-sequitor, but, rather, demonstrates the point I was making fairly neatly.

        -Mike
  34. Clean code[ Go to top ]

    "Ah, no. The useful syntax that Java "borrowed", for lack of a better term, was the C part. Where Java diverged from C, it went on its own (except for some superficial bits). "

    My understanding was that the Java creators started from C++ and worked backwards.
    http://ei.cs.vt.edu/~wwwbtb/book/chap1/java_hist.html
    backs up my claim.

    "Putting it into the realm of the absurd...if in future years someone created D++, E++, etc up to Z++, and Z++ happened to be a superset of C" etc

    My point was that commonality exists between C++ and Java by virtue of C being a subset of C++. If E++ were created as you suggest, Java would then still share commonality with it ex post facto.
  35. Clean code[ Go to top ]

    Mike's comment about parser size is reasonable. C++ is a big language with a fairly big library. The initial learning curve is the language - you can always use a reference book for the library. Java has a smaller, less complex language (although some of the recent 1.5 additions add compiler complexity in exchange for syntactic simplicity) so the learning curve is easier. Java's library is enormous and, in many places, seriously non-intuitive (IMO) although, again, you can live and die by a reference book and survive.

    The comments about only knowing 50% of C++ after many years are spot on. Even Bjarne himself admitted that C++ was too big and complex for one person to know all of it back in the late 90's. (I was on the C++ committee with him for eight years and I was secretary of J16 - the ANSI committee - for three years. I started working in Java in early '97 and had pretty much stopped doing C++ eighteen month later).

    I'm surprised this article has generated so much discussion here since his basic points are simply:
    a) to use C++ effectively, you need to know some of the out-of-the-box features (well, duh!)
    b) to write effective OO programs you need to tread a middle ground between too concrete and too abstract (which seems a bit of a "duh!" to me as well)
  36. Clean code[ Go to top ]

    <sean corfield>
    > I'm surprised this article has generated so much discussion here since his basic points are simply:
    > a) to use C++ effectively, you need to know some of the out-of-the-box features (well, duh!)
    > b) to write effective OO programs you need to tread a middle ground between too concrete and too abstract (which seems a bit of a "duh!" to me as well)
    </sean corfield>

    Unlike Mike, what I can't seem to understand is what the heck is wrong with getting to know some out-of-the-box features if that will help you program effectively? I mean Doh.. I want to use something to its fullest potential I gotta do what it takes. If you want to crib you can always find another language -- that is what choice is supposed to be, right?

    --Dilip
  37. Clean code[ Go to top ]

    \Dilip Ranganathan\
    Unlike Mike, what I can't seem to understand is what the heck is wrong with getting to know some out-of-the-box features if that will help you program effectively?
    \Dilip Ranganathan\

    To bring the discussion around back to the original interview, and counterpoints offered here: what the interview fails to mention, and has been pointed out here, is that much of Stroustrup's advice is rooted in speed, memory efficiency, and C compatability. Not in OO theory or usability, but speed/efficiency/compatability. As someone else said, I'd take Stroustroup's OO design and development advice with a grain of salt. He's not talking about the best way to program; he's talking about the best way to squeeze extra bytes and cycles, and how to keep an escape hatch to C open, and _after_ those considerations have been meant by-the-way-how-to-do-it-with-OO-generics.

    As many people have found out, once you get away from "squeeze extra bytes/faster/C compatible", and move towards "more maintainable/more reliable, more robust/more understandable/larger systems for comparable effort", they hit themselves on the head and say "D'oh - why am I using C++?".

    Forget about Java for a moment - just about _any_ language is going to be better for you than C++ if your primary goals are not squeezing the last cycle and last byte out of your programs.

        -Mike
  38. Java and Objective-C[ Go to top ]

    Mike_Spille wrote:

    "Using your rather interesting reasoning, you could also say that Java syntax is based on Objective C because Objective C is based on C."

    Perhaps not syntax, but Java's semantics were certainly strongly influenced by Objective-C. This according to Patrick Naughton in a USENET posting: Message-ID 861588294 dot 27029 at dejanews dot com or see http://www.cs.umd.edu/users/seanl/stuff/java-objc.html.

    On C++ complexity compared to Java, Stroustrup has said this:

    "Much of the relative simplicity of Java is - like for most new languages - partly an illusion and partly a function of its incompleteness. As time passes, Java will grow significantly in size and complexity. It will double or triple in size and grow implementation-dependent extensions or libraries. That is the way every commercially successful language has developed. Just look at any language you consider successful on a large scale. I know of no exceptions, and there are good reasons for this phenomenon. [I wrote this before 2000; now see a preview of Java 1.5.]" (http://www.research.att.com/~bs/bs_faq.html#Java)

    Marc
  39. Java and Objective-C[ Go to top ]

    "On C++ complexity compared to Java, Stroustrup has said this:"

    Yes, and so far Stroustrup has been proven utterly wrong. Even if you take in everything in Java 1.5, it still does not approach C++'s complexity by even an order of magnitude.

    Stroustrup has, in fact, been proven wrong about a number of his prostications. Face it, the man lives and breathes C++ and does not even acknowledge anything outside of that realm (other than, perhaps, Simula and C).

         -Mike
  40. Clean code[ Go to top ]

    [ Apologies to regular TheServerSide readers for posting this pollution here ]

    Here is some examples of C++ code. Compare it to the readability of Java, and the number of language constructs in play. Note that I purposely did not pick out intentionally obfuscated C++, weird stuff, typical production code with a thousand #IFDEFs, or the like. This is vanilla stuff which C++ developers deal with on a daily basis.

    Note that the first one is a pretty clean C++ example, not one picked of excessive uckiness:

     namespace std {
        template<class X> class auto_ptr {
           template<class Y> struct auto_ptr_ref {};
        public:
          typedef X element_type;
      
          // 20.4.5.1 construct/copy/destroy:
          explicit auto_ptr(X* p=0) throw();
          auto_ptr(auto_ptr&) throw();
          template<class Y> auto_ptr(auto_ptr<Y>&) throw();
          auto_ptr& operator=(auto_ptr&) throw()
          template<class Y> auto_ptr& operator=(auto_ptr<Y>&) throw();
          ~auto_ptr() throw();
      
          // 20.4.5.2 members:
          X& operator*() const throw();
          X* operator->() const throw();
          X* get() const throw();
          X* release() throw();
          void reset(X* p=0) throw();
      
          // 20.4.5.3 conversions:
          auto_ptr(auto_ptr_ref<X>) throw();
          template<class Y> operator auto_ptr_ref <Y>() throw();
          template<class Y> operator auto_ptr<Y>() throw();
        };
      }

    Another one. Please, Sartoris, point out the number of syntactical items in this example that Java has in common:

      Child& Child::operator=(const Child& source) {
          if (this != &source) {
              this->Parent::operator=(source);
              . . . // copy all our own fields here.
          }
          return *this;
      }

    Always a favorite...

      #if UINT_MAX >= (1 <  typedef unsigned int punycode_uint;
      #else
      typedef unsigned long punycode_uint;
      #endif

    Gotta love operator overloading and templates in combination:

      template < typename LeftOpd, typename Op, typename RightOpd >
      struct LOP
      {
        LeftOpd lod;
        RightOpd rod;
      
        LOP(LeftOpd lhs, RightOpd rhs): lod(lhs), rod(rhs) {}
      
        ADT operator[](const unsigned int i)
        {
          return Op::apply(lod[i], rod[i]);
        }
      };
      struct Plus
      {
        static double apply( double a, double b) { return a+b; }
      };
      template <typename LeftOpd>
      LOP< LeftOpd, Plus, Vec > operator+(LeftOpd a, Vec b)
      {
        return LOP<LeftOpd, Plus, Vec>(a, b);
      };

    And a very recent favorite from comp.lang.c++.moderated. Looks simple, but it's not. All the lovely constness and constructors and implicit copying is fun, isn't it?

      class C
      {
       public:
         C(char *)
         {}
       private:
         C(const C&);
      };
      class D : public C
      {
       public:
         D() : C("d")
         {}
      };
      int foo(const C& c)
      {
          return 0;
      }
      static int bar = foo(D()); // Is this legal c++? Is it necessary to copy
      the D object?

    Another headache inducer, aren't temporaries fun? This was a question on the C++ moderated list along the question of the meaning ""a temporary bound to a reference member in a constructor's ctor-initializer (class.base.init) persists
    until the constructor exits".

      struct T { .. };
      T tempT () { return T (); }
      struct U
      {
        const T& t;
        U (): t (tempT ()) { }
      };
      struct V
      {
        const T& t;
        V (const T& tt): t (tt) { }
      };
      int main ()
      {
        U u; // the t temporary only lasts as long as the constructor
        V v (tempT ()); // the t temporary lasts as long as the entire
                        // statement
      }


        -Mike
  41. Clean code[ Go to top ]

    <Mike>
    > Here is some examples of C++ code. Compare it to the readability of Java, and the number of language constructs in play. Note that I purposely did not pick out intentionally obfuscated C++, weird stuff, typical production code with a thousand #IFDEFs, or the like.
    <Mike>

    Actually to have #IFDEFs in java is not a bad idea, take a look at
    http://www.ftponline.com/javapro/2003_03/magazine/columns/proshop/
    good read.

    oleg
  42. Clean code[ Go to top ]

    \oleg shteynbuk\
    Actually to have #IFDEFs in java is not a bad idea
    \oleg shteynbuk\

    I concur most heartily that conditional compilation would make large-scale software development easier in Java. And a lightweight but fully language-aware macro processor would be even more welcome to me (although I know some would quail at the notion).

    But the implementation details are just as important as the abstract concepts. C++ benefits in an abstract way from having a macro processor. In reality, it's inherited the truly ancient and brain-dead C macro processor, whose crudeness strips away most of the benefits you could get from it.

    Plus, the preprocessor has to be used in C++ (just as in C) for portability concerns that shouldn't have to be concerns to a software developer. That's why I picked the example I did - the old bugaboo of "what size is my int?". Even more insidisuous is the "what sign's my char?".

    So agree that Java might benefit from conditional compilation (and go further and propose a real macro system to boot), but C++ shows us how _not_ to go about it (just as it does with the ideal of generics vs. the reality of templates).

         -Mike
  43. Clean code[ Go to top ]

    <Mike>
    > But the implementation details are just as important as the abstract concepts. C++ benefits in an abstract way from having a macro processor. In reality, it's inherited the truly ancient and brain-dead C macro processor, whose crudeness strips away most of the benefits you could get from it.
    >
    > Plus, the preprocessor has to be used in C++ (just as in C) for portability concerns that shouldn't have to be concerns to a software developer. That's why I picked the example I did - the old bugaboo of "what size is my int?". Even more insidisuous is the "what sign's my char?".
    <Mike>

    Stroustrup mention, probably in D&E, that one of the reasons for creating C++ was to get rid of C preprocessor but he realized that there are still cases when it is needed. And if you look at K&R C and what improvement to it came from part of C++ that is known as a “better C” then your arguments are pretty close to Stroustrup’s.

    C++ is a system language and a hybrid one not a pure OO, after all not everything in the world is OO, and C++ is closer to hardware then java. Stroustrup always said that there will be other languages that for some applications more suitable then C++ and I believe he considered C++ as an evolutionary language, just a step in evolution and not the end, and what he done is amazing and all without any big companies marketing just grassroots support. Just consider that before C++ OO was like a cult technology and now it is a mainstream.

    oleg

    oleg
  44. Clean code[ Go to top ]

    \oleg shtenynbuk\
    Stroustrup mention, probably in D&E, that one of the reasons for creating C++ was to get rid of C preprocessor but he realized that there are still cases when it is needed. And if you look at K&R C and what improvement to it came from part of C++ that is known as a ?better C? then your arguments are pretty close to Stroustrup?s.
    \oleg shtenynbuk\

    This makes a lot of sense in the context of the times. But please realize that the core principles of C++ were pretty well set over two decades ago (not the core language but the principles).

    What perhaps made sense in the early eighties up to the mid nineties is, IMHO, starting to fall apart when you consider things in 2003.

    As I said in another post, it is possible that C++ was necessary as a bridge to get the world to seriously consider OO. But in many ways it's a bridge made of duct tape, popsicle sticks, and gum. And the reasons for this are because of the core principles of efficiency, C compatibility, and a love of complexity.

    The killer is the last one - the love of complexity. The world clearly could use "a better C", and C++ fulfilled that need by the late 80's. Not ideally in my book, but sufficiently. But Stroustrup and the ANSI/ISO committees were not satisified, and went into an orgy of feature creation. Nothing was ever removed, just new stuff was added on top to cure fundamental problems.

    For over two decades, almost nothing has been subtracted from the language, but lots of things have been added. Hacks little, and hacks writ large, from "explicit" to "Exceptions" retroactively added to a language/library not previously aware of them, to an ungodly Template implementation have not just been added, but have been force-fit into the original core structure.

    The end result is not what I'd consider a good design, but rather a clever one. I consider it amazing that developers have been able to hold this level of complexity together and find ways to shoe horn new things into it, but even this level of clever technical genius is showing signs of collapse. C++ is now a language where experts in the language bitterly disagree over the semantics of 20 line code snippets - such as a couple that I posted here.

    The concept of doing OO in the most C-ish way possible - C++ - may have been necessary to get people on the bandwagon. But it's an approach that, if sustained, is ultimately doomed to fail because the underpinnings aren't sound. Personally, I think the people who use straight C, or Objective-C (which clearly splits OO from C), or Java or any number of other languages are alot saner than those who continue to pound on C++.

    Java, for example, is a language where I get a sense of pride when I've help knit together a quite large enterprise application system with my own messaging code. C is a language that I descend into in small doses when I need the ultimate in deterministic speed, and my satisifaction there comes from seeing my code run blazingly fast. C++ is a language where my sense of pride and satisfaction comes from debugging someone else's 4 classes, and emerging hours later having figured out what it's actually supposed to do. C++ is a language where I feel like a genius when a modest set of .C files and headers just gets past the compiler.

    It is, perhaps, ironic that Stroustrup is now looking down on people who use C++ as a "better C", and is doling out advice on OO theory. But while doling out his OO theory advice he still, twenty years later, insists on C compatability as being critical, still insists after all these years that free-floating C-style functions are superior to OO techniques, and still has his mind fixed on Java as it was in the alpha days in '95/'96.

    In a sane world, you'd have to work extra hard to get to the old C preprocessor - you'd need 8 compiler switches to enable it. Most developers would use a much saner preprocessor that would be the default, and only the crazy speed addicts (or those who absolutely need compatibility) would use the old cpp. In a sane world, GC would be the default, and could be disabled for blocks that need to descend into C mode. In a sane world, objects would never live on the stack, and an entire class of C++ problems would dissolve - but Stroustrup found that "new" was slow in Simula back in the 70s, and thereby doomed generations of programmers to stack-based-object bugs and "the lifetime of temporaries". In a sane world, there would be a clear demarcation between clean, modern OO and generic programming in C++ and the dirtying-your-soul practice of enabling C compatibility mode for the few files that need it.

    If you want to point to any one thing, though - in a sane world, modern OO programming would not absolutely require you to utilize a crippled C-Preprocessor which was written in the early 70's. But it does. C++ needs headers, and the only way to use them is via the old cpp.

        -Mike
  45. Examples of C++ code?[ Go to top ]

    This is vanilla stuff which C++ developers deal with on a daily basis.


    I'm a C++ developer. I do not use code like you've included. I haven't even seen code that looks like that. In the same way that people don't really write Xlib code anymore, you don't need to write such horrid C++ code anymore unless you want performance and C compatibility. I'd think most people don't need that anymore.

    At my previous job, I wrote telco software in Java. I saw more bad code (and difficult-to-debug crashes/errors) then than I have since I changed jobs and started working with C++.

    Both C++ and Java are very big and complex. What java lacks in syntax it makes up for in libraries. I didn't use all of Java before and I don't use all of C++ now.

    Link
  46. Examples of C++ code?[ Go to top ]

    \Lincoln Ramsay\
    I'm a C++ developer. I do not use code like you've included. I haven't even seen code that looks like that. In the same way that people don't really write Xlib code anymore, you don't need to write such horrid C++ code anymore unless you want performance and C compatibility. I'd think most people don't need that anymore.
    \Lincoln Ramsay\

    The code I referenced wasn't "such horrid C++ code". One was a fairly modern implementation of <auto_ptr>. Another is fairly standard overloading of operator-[]. Two of the examples were posted on comp.lang.c++.moderated within the past week.

    It sounds to me like you're in a shop that has agreed upon their own subset of C++. If so, great for you! But if you use any external code, expect to see such things regularly.

    \Lincoln Ramsay\
    At my previous job, I wrote telco software in Java. I saw more bad code (and difficult-to-debug crashes/errors) then than I have since I changed jobs and started working with C++.
    \Lincoln Ramsay\

    Perhaps we haven't seen a comparable breadth and depth of software? I've yet to find a Java system I couldn't puzzle out. I _have_ found many C++ code snippets (let alone systems) which have not only puzzled me, but give different results on different compilers.

    \Lincoln Ramsay\
    Both C++ and Java are very big and complex. What java lacks in syntax it makes up for in libraries. I didn't use all of Java before and I don't use all of C++ now.
    \Lincoln Ramsay\

    I don't think it's valid to combine syntax with libraries. Your average developer can pick up Java syntax very rapidly and confidently know all of it. Your average C++ developer can't hope to know the entire C++ language.

    Java does have a much bigger suite of libraries, both standard and open source. But for the most part, these too are in the straightforward Java syntax. If you have a problem with a Java library, chances are better than even that you can get source for it and puzzle out what it does from that (assuming the javadocs don't cut it for some reason).

         -Mike
  47. Examples of C++ code?[ Go to top ]

    <mike>
    > The code I referenced wasn't "such horrid C++ code". One was a fairly modern implementation of <auto_ptr>. Another is fairly standard overloading of operator-[]. Two of the examples were posted on comp.lang.c++.moderated within the past week.
    </mike>

    Nobody disagrees the C++ isn't the most expressive langauge in the world but you seem to be confusing power with expression. If you look at Modern C++ Design by Alexandrescu you'd probably get brain seizures but the compile-time type-safety it offers is mind-blowing.

    <mike>
    > Perhaps we haven't seen a comparable breadth and depth of software? I've yet to find a Java system I couldn't puzzle out. I _have_ found many C++ code snippets (let alone systems) which have not only puzzled me, but give different results on different compilers.
    </mike>

    Don't understand this point either. C++ code puzzles you -- fine. Goes to say something about your understanding rather than anything about the language per se -- unless you happen to be Scott Meyers or Herb Sutter of course.

    <mike>
    > I don't think it's valid to combine syntax with libraries. Your average developer can pick up Java syntax very rapidly and confidently know all of it. Your average C++ developer can't hope to know the entire C++ language.
    </mike>

    and you shouldn't. As far back as 1997 we C++ programmers have been taught this:
    http://www.gotw.ca/publications/advice97.htm

    <mike>
    ...... straightforward Java syntax ....
    </mike>

    what is that supposed to mean? that you can write convoluted Java syntax if you want to? see where I am going with this..?

    Seriously aren't we beating a dead horse here? Use the right tool for the job and move on. You and me have a product to ship, remember?

    --Dilip
  48. Examples of C++ code?[ Go to top ]

    \Dilip Ranganathan\
    Nobody disagrees the C++ isn't the most expressive langauge in the world but you seem to be confusing power with expression. If you look at Modern C++ Design by Alexandrescu you'd probably get brain seizures but the compile-time type-safety it offers is mind-blowing.
    \Dilip Ranganathan\

    I've read it, a very good book. I don't see what your point is, though. What I'm saying is that C++ is a very complex language, and you have to work very, very hard to achieve a level of safety. There are many C++ problems which don't exist in a simpler language like Java.

    And, of course, you get close to zero runtime safety with C++.

    \Dilip Ranganathan\
    Don't understand this point either. C++ code puzzles you -- fine. Goes to say something about your understanding rather than anything about the language per se -- unless you happen to be Scott Meyers or Herb Sutter of course.
    \Dilip Ranganathan\

    I've been doing C++ for a number of years, as have my colleagues. I've read the entire ISO C++ standard several times over. My first professional job was working for a C compiler company, and the in-depth language deconstruction interests I picked up in that job carried over to C++ as well (and Java too). In short, I'm not a C++ duffer.

    As a non-duffer, there are lots of C++ that I find confusing as hell. comp.lang.c++.moderated is full of posts of "what is this supposed to do according to the standard?".

    You may not realize it, but this sort of thing doesn't happen with Java code.

    \Dilip Ranganathan\
    and you shouldn't. As far back as 1997 we C++ programmers have been taught this:

       http://www.gotw.ca/publications/advice97.htm

    \Dilip Ranganathan\

    Yes, that's useful advice, but only limited in nature. The problem is that, by and large, you and I and most other developers cannot choose only to work with our own code, or work with the code of a select few who agree with our subset of C++. Most of us are forced by circumstance to work with others' code, sometimes quite often, and the code those others use may not match my preferred C++ subset. This means C++ developers can spend alot of time hunting through reference manuals and battling compilers, because even if you try to avoid areas of C++ that are inscruitable to you, chances are you'll have to maintain someone else's code that happens to touch one of those areas anyway.

    This doesn't happen to me in Java. This doesn't mean I'm an idiot who can't understand C++, or I'm some sort of freaking genius because I understand Java. What it means is that Java is easy enough to understand that developers don't waste time puzzling out "hmmm, now I wonder what the compiler will do with this?".

    \Dilip Ranganathan\
    what is that supposed to mean? that you can write convoluted Java syntax if you want to? see where I am going with this..?

    Seriously aren't we beating a dead horse here? Use the right tool for the job and move on. You and me have a product to ship, remember?
    \Dilip Ranganathan\

    I believe you are missing the point. Show any competent Java developer a code snippet or collection of source code, and we can tell you definitively what that code does. You may obfuscate it with horrible variable and method names and the like, but the fact is that there is a very limited number of semantic structures you can express in Java, and that means there's no places where a competent developer should be left scratching his head.

    Even with modern C++ style it's trivial to come up with 10 lines of C++ code that experts argue over. This does not happen in Java.

        -Mike
  49. Examples of C++ code?[ Go to top ]

    <mike>
    > I've read it, a very good book. I don't see what your point is, though. What I'm saying is that C++ is a very complex language, and you have to work very, very hard to achieve a level of safety. There are many C++ problems which don't exist in a simpler language like Java.
    </mike>

    You have to put in effort in any kind of language to get any kind of safety -- compile-time or otherwise. Its the degree that usually varies. If you want to be spoon-fed you always have VB to turn to.

    <mike>
    > And, of course, you get close to zero runtime safety with C++.
    </mike>

    That is the point behind Generic programming a.k.a template meta-programming -- to get away with as much compile-time type safety as possible.

    > As a non-duffer, there are lots of C++ that I find confusing as hell. comp.lang.c++.moderated is full of posts of "what is this supposed to do according to the standard?".
    >
    > You may not realize it, but this sort of thing doesn't happen with Java code.

    So what? The questions about standard-conformance comes about for 2 reasons:
    * I am writing some non-trivial piece of code which by definition forces me to delve into something exotic (IIRC, Jim Coplien used to do stuff like these waaaaaaaaaay back). I want to know if I can do that without violating the standard and I don't have time time to wade through a standards document (I am dense).
    * I am worried about portability.

    The C++ standard is a vast document. It isn't possible to know every nook and cranny of what is possible and what is not unless you happen to be part of the working group or maybe if you are so sado-masochistic that you live and breathe standards every day! For most regular programmers like us, Effective C++ and More Effective C++ with a sprinkling of Vandevoorde's C++ Templates do just fine.

    <mike>
    > This doesn't happen to me in Java. This doesn't mean I'm an idiot who can't understand C++, or I'm some sort of freaking genius because I understand Java. What it means is that Java is easy enough to understand that developers don't waste time puzzling out "hmmm, now I wonder what the compiler will do with this?".
    </mike>

    your credentials are well established here and I am not questioning that. What is more I agree with your bottomline statement. But my conclusion is different -- I take that as an opportunity to learn more about the language. Everyday I learn so many new things in C++ that helps me avoid pitfalls. See, C++ gives you the ammo to blow your leg off as Stroustrup is fond of saying. We realize that and we work with that in mind. Beyond that we can always quibble on which is the most complex language down the block.

    <mike>
    > I believe you are missing the point. Show any competent Java developer a code snippet or collection of source code, and we can tell you definitively what that code does. You may obfuscate it with horrible variable and method names and the like, but the fact is that there is a very limited number of semantic structures you can express in Java, and that means there's no places where a competent developer should be left scratching his head.
    </mike>

    I don't know how you define a "competent" programmer but IMHO, any proper C++ programmer who has a sound grounding on the basics may scratch his head *only* when he comes across a feature which he has hitherto never encountered. For example only a few months ago I realized that a reference bound to a temporary will make the temporary remain for the lifetime of the reference. Its not a straight forward no-brainer but it isn't that difficult to realize once you think about it. This only shows the breadth of C++ and its associated C baggage.

    <mike>
    > Even with modern C++ style it's trivial to come up with 10 lines of C++ code that experts argue over. This does not happen in Java.
    </mike>

    Experts by definition always disagree. On the other hand consider a library like Boost. At one point people like us almost thought if a given C++ compiler can compile all of the library then the compiler has achieved 100% standards conformance (that is NOT true just to be clear). I scan the Boost list archives regularly and most of the time I see arguments about semantics, not syntax (and we are not talking about 10 lines of code here...)

    --Dilip
  50. Examples of C++ code?[ Go to top ]

    \Dilip Ranganathan\
    You have to put in effort in any kind of language to get any kind of safety -- compile-time or otherwise. Its the degree that usually varies. If you want to be spoon-fed you always have VB to turn to.
    \Dilip Ranganathan\

    The degree of effort to achieve "correctness", for lack of a better word, is at least an order of magnitude less in Java than for C++, at least in my experience.

    As for safety - if you lay aside performance for a moment, Java's runtime safety comes with no effort from me. A NullPointerException gives me a nice stack trace, and only affects the thread generating it. A NULL in C++ can give a SIGSEGV, bus error, or may just run and quiet trash memory.
    In C++ you most certainly must work for your safety, in Java you only have to work for correctness, safety is always taken care of.

    \Dilip Ranganthan\
    That is the point behind Generic programming a.k.a template meta-programming -- to get away with as much compile-time type safety as possible.
    \Dilip Ranganthan\

    To get the compile-time type safety from templates, I have to pay a heavy complexity cost.

    Worst - the safety is illusionary. I said elsewhere, a completely unrelated module can easy say:

       {
         char *cp;
         strcpy (cp, "Hey there");
       }

    ...and blow all of the most carefully crafted compile-time safety right out of the water.

    \Dilip Ranganathan\
    The C++ standard is a vast document. It isn't possible to know every nook and cranny of what is possible and what is not unless you happen to be part of the working group or maybe if you are so sado-masochistic that you live and breathe standards every day! For most regular programmers like us, Effective C++ and More Effective C++ with a sprinkling of Vandevoorde's C++ Templates do just fine.
    \Dilip Ranganathan\

    I agree, it is a vast document. But I disagree that various books and libraries are enough, even for just regular programmers.

    If it's in the compiler, someone will use it.

    \Dilip Ranganathan\
    But my conclusion is different -- I take that as an opportunity to learn more about the language. Everyday I learn so many new things in C++ that helps me avoid pitfalls. See, C++ gives you the ammo to blow your leg off as Stroustrup is fond of saying. We realize that and we work with that in mind. Beyond that we can always quibble on which is the most complex language down the block.
    \Dilip Ranganathan\

    For myself - I have no interest in investing that much time in learning a language. I may be forced to, by my job, but it's not a very good use of my time. I learned Java back in the mid-90's, each release has added maybe a couple of days worth of new knowledge I needed to know, and I'm good. 8 years later, there's no need for me "to learn more about the language". I know it, I use it daily in my job, and there are no (language) surprises.

    With C++, at least once a week I haul out a dusty tome or google around, or get into yet another duel with my compiler. It's an enormous waste of time.

    \Dilip Ranganathan\
     don't know how you define a "competent" programmer but IMHO, any proper C++ programmer who has a sound grounding on the basics may scratch his head *only* when he comes across a feature which he has hitherto never encountered. For example only a few months ago I realized that a reference bound to a temporary will make the temporary remain for the lifetime of the reference. Its not a straight forward no-brainer but it isn't that difficult to realize once you think about it. This only shows the breadth of C++ and its associated C baggage.
    \Dilip Ranganathan\

    In reply to this, I'll repost one of my code examples. This isn't C baggage involved, it's not some esoteric bit that no one's ever heard of. It's just an innocent intersection of references and temporaries and constructors.

      struct T { .. };
      T tempT () { return T (); }
      struct U
      {
        const T& t;
        U (): t (tempT ()) { }
      };
      struct V
      {
        const T& t;
        V (const T& tt): t (tt) { }
      };
      int main ()
      {
        U u; // the t temporary only lasts as long as the constructor
        V v (tempT ()); // the t temporary lasts as long as the entire
                        // statement
      }

    The insidious thing with C++ is code like the above may be in your overall code base right now, and your code may run, but some day it will explode with a SEGV or the like, and then some developer will have to know this obscure bit of C++ arcana to understand what's going on and fix it.

         -Mike
  51. Examples of C++ code?[ Go to top ]

    "struct T { .. };
      T tempT () { return T (); }
      struct U
      {
        const T& t;
        U (): t (tempT ()) { }
      };
      struct V
      {
        const T& t;
        V (const T& tt): t (tt) { }
      };
      int main ()
      {
        U u; // the t temporary only lasts as long as the constructor
        V v (tempT ()); // the t temporary lasts as long as the entire
                        // statement
      }

    The insidious thing with C++ is code like the above may be in your overall code base right now, and your code may run, but some day it will explode with a SEGV or the like, and then some developer will have to know this obscure bit of C++ arcana to understand what's going on and fix it.
    "

    You can get yourself in trouble in Java in much the same way. I've seend it happen more than a few times; "Good" Java developers not grasping the concept of shallow versus deep copies. They make a shallow copy of an object thinking they have a new independent object, they change the object and then the original object is changed un-awares to them.
    Other areas:
    when/how to implement hasCode(), equals(), clone()
    Not knowing how serialization works and having to implement read/writeObject().
    anonymous classes, custom collections, etc.
    Understanding object lifetimes.

    There's plenty of ugliness in Java as well. I think the ugliness of C++ has been overstated. And almost all of it can be avoided.

    Try this snippet:
    int i = 1;
    int j = 2;
    int k = 3;
    Integer l = new Integer(4);
    System.out.println(1 + 2 + 3 + "123" + 4 + 5);
    System.out.println(i + j + k + l.toString() + "ijk");

    try this then, too
    System.out.println(i + j + k + l.toString() + "ijk");

    I doubt you'd guess the output of this.
  52. Examples of C++ code?[ Go to top ]

    \Sartoris Snopes\
    You can get yourself in trouble in Java in much the same way. I've seend it happen more than a few times; "Good" Java developers not grasping the concept of shallow versus deep copies. They make a shallow copy of an object thinking they have a new independent object, they change the object and then the original object is changed un-awares to them.
    Other areas:
    when/how to implement hasCode(), equals(), clone()
    Not knowing how serialization works and having to implement read/writeObject().
    anonymous classes, custom collections, etc.
    Understanding object lifetimes.
    \Sartoris Snopes\

    Certainly you can get yourself into trouble in any language. But bundle up all of the rules in Java and you can, literally, know them all in a very short amount of time. _KNOW THEM ALL_. There are perfectly ordinary Java programmers that know the whole kit 'n' kaboodle.

    Now go and find me some C++ programmers that know just 75% of the language. That's 25% off at no cost to you :-)

    Incidentally, "understanding object lifetimes" probably shouldn't be on your list. In Java, if you can see it, it's alive :-)


    There's plenty of ugliness in Java as well. I think the ugliness of C++ has been overstated. And almost all of it can be avoided.

    \Sartoris Snopes\
    Try this snippet:
    int i = 1;
    int j = 2;
    int k = 3;
    Integer l = new Integer(4);
    System.out.println(1 + 2 + 3 + "123" + 4 + 5);
    System.out.println(i + j + k + l.toString() + "ijk");

    try this then, too
    System.out.println(i + j + k + l.toString() + "ijk");

    I doubt you'd guess the output of this.
    \Sartoris Snopes\

    What, rules of Java String contenation 101? The ability to read from left to right and know when we switch from an int expression into a String one? I'd call it very mildly tricky.

    I agree concatenation can be a bit ugly, but I can count the Java uglies on two hands. We'd have to haul out population of a small town to count the ones for C++.

    And I'd say I'm not overstating C++'s ugliness. If anything, I'm understating it by quite a bit. You may notice that I purposefully gave pretty mild C++ examples. On top of that, the various C++ gurus on the planet are busy putting together another C++ standard with even more stuff layered onto what's already there. Plus there's of course Boost and other goodies hither and yon.

    Every 4 years C++ actually grows even further beyond where it is, and shows no signs of stopping. Which means every 4 years the average programmer is further and further away from hoping to understand it all. Hell, post one file from a Standard C++ library and most C++ developers run away screaming in fear (as I did with the <auto_ptr> example which people erroneously thought was "old-style" C++).

        -Mike
  53. Examples of C++ code?[ Go to top ]


    > Worst - the safety is illusionary. I said elsewhere, a completely unrelated module can easy say:
    >
    > {
    > char *cp;
    > strcpy (cp, "Hey there");
    > }
    >
    > ...and blow all of the most carefully crafted compile-time safety right out of the water.

    I won't carry this conversation any further but let me just point out that if you start throwing red herrings like the above it would be difficult to have reasonable arguments. If you have a developer who writes code like that pls send him to a guillotine -- don't blame the language for that -- and the above code has nothing to do with C++ anyway... if you are using standard C++ like the rest of us are you wouldn't be talking about anachronistic little beasts like char*

    --Dilip
  54. Examples of C++ code?[ Go to top ]

    \Dilip Ranganathan\
    I won't carry this conversation any further but let me just point out that if you start throwing red herrings like the above it would be difficult to have reasonable arguments. If you have a developer who writes code like that pls send him to a guillotine -- don't blame the language for that -- and the above code has nothing to do with C++ anyway... if you are using standard C++ like the rest of us are you wouldn't be talking about anachronistic little beasts like char*
    \Dilip Ranganathan\

    A few points on this:

      - I used a simple example to illustrate the point. You can get the same effect by saying:

          MyClass foober ();
          foober.x->value = 15;

    ...where "x" wasn't initialized. So long as you are using pointers you are exposed to this sort of problem. Or are you claiming that modern C++ code doesn't use pointers anymore?

      - C++'s almost complete lack of runtime safety (as opposed to static type safety) is not a red herring. It has rather far-reaching implications for software robustness and correctness.

      - You consider "char*" an anachronistic little beast? I suppose you'll claim that you don't use "char *" anywhere in your overall C++ code base - right? Not just your own personal code, but the whole code base doesn't have any "char *" (or void *, or the like). Right? I suppose all the third party libraries you interact with all use string and STL too - right?

        -Mike
  55. <Sartoris>
    > Using smart pointers and leveraging the fact that desuctors are called at determinable times makes memory management and resource management rather easy.
    <Sartoris>

    It is all true but pretty difficult to enforce, especially reference counting smart pointers, unless you have your own small closed world.

    In java there are some coding guidelines and javadoc that by some miracle got accepted and used most of the time; and the credit for this probably goes to the Sun than Java as a language.

    oleg
  56. <Sartoris>
    > Using smart pointers and leveraging the fact that desuctors are called at determinable times makes memory management and resource management rather easy.
    <Sartoris>

    It is all true but pretty difficult to enforce, especially reference counting smart pointers, unless you have your own small closed world.

    In java there are some coding guidelines and javadoc that by some miracle got accepted and used most of the time; and the credit for this probably goes to the Sun than Java as a language.

    oleg
  57. Sartoris:
    If the developers really know the language inside out they wouldn't have core dumps.

    That's a bit naive, isn't it?

    I know Java pretty well but I still write programs that crash. On a daily basis.

    With C++, I do remember it was on an hourly basis.

    I still have a lot of respect for Bjarne, he was an inspiration to us all on the C++ committee for his pragmatism and humility. Looking back, I am realizing how sad it is that such a great language designer had to work within the confines of performance and backward compatibility with C that led to C++ as we know it today.

    I shiver when I imagine a language created by him and Anders Hejlsberg...

    --
    Cedric
  58. \Cedric\
    I still have a lot of respect for Bjarne, he was an inspiration to us all on the C++ committee for his pragmatism and humility. Looking back, I am realizing how sad it is that such a great language designer had to work within the confines of performance and backward compatibility with C that led to C++ as we know it today.
    \Cedric\

    Well, I'm not so sad about - it was his choice (well, his and Bell Labs') to work within the confines of C and certain performance goals.

    What I believe is a tragedy is the number of people who don't understand those underlying constraints and the effect they have on the language as a whole. My sympathy is even further extended to the poor developers who write C++ compilers for a living.

        -Mike
  59. IMHO, backward compatibility with C, being good or bad, is what gave C++ its huge acceptance in many areas. So maybe this compatibility was a good thing after all, despite all the problems it created. If instead of C++ it was just another new and different OO language, we could have stuck with just another Smalltalk. Adoption would be much harder, and either we would all be still coding in C today, or different OO languages would be fighting to enter the new OO "space" that was appearing at that time (years before Java), ending up with a much more fragmented market. C++ was a clear "winner" at that time, and one of the reasons was its backward compatibility with C.

    Henrique Steckelberg
  60. In general, I'd say you're right. The number one advantage C++ had going for it in the day was that you could link it to C code with only a small effort, and use the native C bindings for the underlying OS and various libraries directly.

    And, in the grand scheme of things, you may be correct that the world needed a C++ at that critical juncture in time, and that without it we might not have Java or even a vibrant OO community. Sometimes you need a bastardized middle-solution that straddles two worlds to get people to see that there is another world to begin with.

    However, I say that only in the grandest and most general sense. There are many, many other aspects of C++ that could have done completely differently that would not have changed the course of history negatively - but which would have IMHO been a much better solution for the time _and_ for pointing to future directions. And I don't mean this in the sense of 20/20 hindsight, but more in the fundamental outlook of Stroustrup which has effectively gone on unchanged for over 2 decades. C++ could have had a common Object root class, a decent library, garbage collection, and a host of other features without damaging C compatability or underlying efficiency needs, but Stroustrup didn't see the need for them now and doesn't see the need now (except for the library thing).

        -Mike
  61. Except for the GC, Objective-C had all of the capabilities you mentioned, was available since the late 80's at least, was simpler in many ways than even Java, and under the NeXTStep environment was part of an OO dev environment way ahead of its time. Had C++ not caught on, I think Objective-C would have, and the development world would have been a better place.
  62. "Sartoris:
    If the developers really know the language inside out they wouldn't have core dumps.

    That's a bit naive, isn't it?

    I know Java pretty well but I still write programs that crash. On a daily basis. "

    I was refering to production or near-production ready software.
  63. "Sartoris:

    > If the developers really know the language inside out they wouldn't have core dumps.
    >
    > That's a bit naive, isn't it?
    >
    > I know Java pretty well but I still write programs that crash. On a daily basis. "
    >
    > I was refering to production or near-production ready software.

    I knew a developer once who used to say that after 8 years, he knew about 50% of C++. Is this what's your talking about? If they knew C++ inside out, what is that?
    We, the humans, went to the moon, ran 100 m in under 10 seconds, yeah, and we can know C++ inside out and do something that won't crash.

    This is about productivity, but you don't seem to get that.
  64. "I knew a developer once who used to say that after 8 years, he knew about 50% of C++. Is this what's your talking about? If they knew C++ inside out, what is that?
    "

    People can get a medical degree in 8 years. That statement says more about his ability than it does C++. Maybe he's in the wrong field.

    Most Java developers don't know 100% about Java either. And that after many years of experience. What's the point?

    "This is about productivity, but you don't seem to get that. "

    No, I do get it. I never argued that A was more or less productive to B. Java in many cases is better suited in my opinion, too.

    Java can be and is misused just like other languages. Most of the time it's because of intellectual laziness.
  65. \Sartoris Snopes\
    People can get a medical degree in 8 years. That statement says more about his ability than it does C++. Maybe he's in the wrong field.
    \Sartoris Snopes\

    The statement of only knowing X% of C++ after many years (where X is typically far below 90) is not uncommon. In fact I believe the overwhelming majority of the C++ developers out there only know 50% at best, even the ones with many years experience. IMHO this is a sane reaction to an insanely complex language.

    And when I say "know" I really mean _know_. As in knowing the type promotion rules. Knowing what is signed by default, what's not, and what has no default sign. All of Templates, even the nooks and crannies, and nightmares like template specialization. The precise definition of the lifetime of temporaries. All the various OO overriding rules, including ambiguous vs. potentially ambiguous. Order of initialization. The two constructor initialization styles. The old and new style casts. All of RTTI. Virtual Inheritance. And on and on - I'm frankly too tired to type out the whole list. But anyway, most C++ programmers I know only know about half at best, and the very partial list above shows why.

    \Sartoris Snopes\
    Most Java developers don't know 100% about Java either. And that after many years of experience. What's the point?
    \Sartoris Snopes\

    The overwhelming majority of Java developers I know know about 99% of the Java language. The remaining 1% invariably is in areas like Classloaders and class identity, bit twiddling, and a very small number of nooks and crannies. A minority of developers (maybe 20%) literally know the entire inside and out cold. By contrast I'd say 1% of C++ developers know the entire language.

    \Sartoris Snopes\
    Java can be and is misused just like other languages. Most of the time it's because of intellectual laziness.
    \Sartoris Snopes\

    The richness of life is not in absolutes but in shades of differences.

    To give you an idea of what I mean - it's extremely difficult on a large project _not_ to misuse C++. By contrast, Java is simple enough that you actually have to work a bit to abuse it. Both languages can be abused, but the importance is the relative ease of abuse.

        -Mike
  66. makes perfect sense....[ Go to top ]

    I think the article breaks down what an object should be to bair bones level. The principles discussed are sound and applicable in Java.

    There are lessons in that article for all OO practioners.
  67. makes perfect sense....[ Go to top ]

    I concur. There are some good points which are extremely relevant to Java as well.

    "Or even worse make a virtual base class with virtual get_name and set_name functions and so on, and override it with the one and only representation. That's just elaboration. It's not necessary." <-- I have seen (and written :( ) a lot of java code this way.

    "..you have to have some semantics that you are defending before you start having private data."

    "Anything that's just using the data, but not defending the invariant, doesn't need to be in the class". (I assume the same doesnt apply to get*() methods :) ) ... given efficient element access, a find function for searching in a vector is best provided as a non-member..
  68. makes perfect sense....[ Go to top ]

    \Nene\
    [Stroustrup]Or even worse make a virtual base class with virtual get_name and set_name functions and so on, and override it with the one and only representation. That's just elaboration. It's not necessary." <-- I have seen (and written :( ) a lot of java code this way.
    \Nene\

    You may think that what Stroustrup is saying is widely applicable, but in reality this interview is fairly truncated and he's not giving the full story (as he does in other areas).

    The real motiviation behind his example is about speed and binary compatibility. With a plain "struct" you have no vtable overhead, no fancy games, and you can pass it back and forth with C code. The minute you add a virtual member and call it a class, you trigger a bit of overhead and your old struct is no longer usable from C.

    I've read through the article a few times, and I still believe that Stroustrup is dressing up old arguments that are grounded in speed and C compatability and memory footprint, and trying to make them into something they're not. He's trying to make it sound like he's targetting robustness and OO theory but in reality he's talking about doing OO-style and generics-style stuff really really fast with the smallest possible memory overhead. And in a tie breaker between expressiveness/maintainability and speed/footprint, speed/footprint _always_ wins in C++.

    So I find the article disappointing, because Stroustrup is only relating half of the story (the half that sounds good to OO people), and is omitting the real reason why he does this sort of thing in his own stuff (speed/footprint/C compatibility). And no, I'm not putting words in his mouth, D&E and several articles discuss these issues in-depth.

         -Mike
  69. makes perfect sense....[ Go to top ]

    No, the argument he is making is that you are wasting your time writing getters and setters for what should be public variables. More computer cycles are wasted while you type (O' Glorious LOC!) than would ever be recovered by avoiding vtable lookups. Putting everything in a class hierarchy just for the sake of some sacred school room diagram (that falls apart on anything more complex than the school room example) is stupid, and he's calling you on it. Ask yourself, why are Entity Beans ridiculed? It's because in practice they are often nothing but data structures with the overhead of persistability and remoting. Unless a getter/setter is actually manipulating a value or protecting one (through a logic type checking process), it is a wasted function. That's what all the template engines (written in java) are trying to overcome.

    Another sacrelige to OOP zealots is his suggestion that a method should be able to manipulate more than one type of object. The blasphemy! It could cut into potential lines of code. That's the only thing I see wrong with it. I don't know where you come from, but over here, developers aren't paid by the character. Java must have been the holy grail for those that are, who revel in loquacity can turn this:

    for (int i=0;i<10;i++) {}

    int this:

    Object temporaryLoopIterator = (Foo.Math.Integer.ShortInt) IteratorFactory.GetIteratorObjectFromPool("int");

    IterationPerformer i = IterationPerformer.Singleton();
    i.init(temporaryLoopIterator, 1, 10)
    i.performIterationOn(objectToPerformIterationOn)
  70. makes perfect sense....[ Go to top ]

    \Aaron Evans\
    No, the argument he is making is that you are wasting your time writing getters and setters for what should be public variables. More computer cycles are wasted while you type (O' Glorious LOC!) than would ever be recovered by avoiding vtable lookups.
    \Aaron Evans\

    Perhaps, if you go only by this interview, you're correct.

    But look at the collected works of Mr. Stroustrup, and you'll find the motivator behind examples such as this one always boil down to:

       1) Speed
       2) Memory Footprint
       3) Compatability with C

    The reason he tells people to avoid "virtual-anything", or classes, or a number of other items is because of the runtime weight involved. His advice, and all of C++'s "default" modes, and the entire header/source file model are all skewed towards efficiency & compatability first, programmer convenience second.

    I rarely invoke this phrase, but trust me on this one. The aggregate inventors of C++ are _paranoid_ about avoiding vtable creations to begin with, let alone lookup.

         -Mike
  71. makes perfect sense....[ Go to top ]

    I believe Mike Spille is correct on this one. A few years ago (97 or 98) in NYC I attended a meeting with Stroustrup at a Wall Street firm which had invited him to discuss his work, during which several developers asked Stroustrup for his take on Java. He responded that Java was a poor language, because he was not convinced that automatic GC could possibly be efficient enough for production use (although people had been developing business apps in Perl for many years already, and Java for a couple of years!), and because he felt the Java designers assumed that most programmers were stupid (I guess because they found it a pain to deal with memory management)! Stroustrup may be a smart guy, but based his responses it was clear to us that he had NO CLUE of what the needs of business developers are, no clue how the nature of business applications development differs from systems programming, and that making developers' lives more convenient was not much of a priority to him. I would take any OO design advice from him with a grain of salt.
  72. small talk[ Go to top ]

    An integer shouldn't be part of a class hierarchy.


    I cannot agree. I played six months with smalltalk in 1997.

    Nice language and eveyrthing was object. Including integer.

    The smalltalk in this time was, where is JAVA now. For example performance.

    Just for bussiness reasons was not succesful.
  73. Wow![ Go to top ]

    I find it unbelievable that in a Java forum we get people saying they prefer C or perl. OO is just a way of structuring one's code. Of the server side code I have seen especially code using the model 1 style, yes, objects do not add much value. DAOs are just C/C++ structs. But, in true GUI applications (not browser applications), the benefits of objects are huge.

    I developed in C++ for about 8 years before I went to Java and C++'s implemention of OO is fine. The ANSI committee has certainly made it a complex language from what it used to be especially with the overloaded meanings of various syntactical characters. But just ignore that cruft and C++ is OK. What I don't like about C++ is header files. I hate having to type a function signature in two locations.
  74. Wow![ Go to top ]

    I can and do use alot of discipline when developing under C++, and use a subset that I can keep under control. Many other developers I know also do the same thing.

    The problem is, no two developers ever agree on the subset. One guy won't use exceptions. Another one avoids multiple inheritence. A third won't use templates. One hates operator overloading. And a fifth guy uses C++ only as "better C" and has a handy-dandy header library of 4,236 macros for fun and amusement. Half of them don't understand references and use pointers exclusively, the other half avoid pointers like the plague. Some joker uses operator() in every class for some funky reason that nobody but him understands.

    On the "positive" side, someone will aggressively use templates. Another has a love affair with operator overloading. A third thinks virtual inheritance is the cat's ass. One uses exceptions whenever possible.


    Now on the "my head is imploding" level, add in a C++ super-user, or a newbie who's determined to use the entire language. Add in a quarter of the code that uses old RogueWave container stuff. Another quarter that uses STL. Another quarter that uses a botched and butchered psuedo-STL that barely crawls along the floor that they got off the net. Another quarter have their own container classes they wrote a five years ago and refuse to part with.Some guys use ISO C++ I/O mechanisms. Some guys use old C mechanisms. A subset of them use C and Unix mechanisms. The guy who has an office but always keeps the lights off uses a Swifty++ I/O package he downloaded off the net 5 years ago. One woman wants to use a Posix threading library, the grizzly-adams-looking guy who has 12 seconds more seniority insists on using the native OS threading libraries directly. The crotechtety old man with 15 monitors surrounding his cube - all VT102 terminals - still uses (void *) for all his callback data. The stunningly beautiful red head on the 5th floor runs ISO compatability suites on everyone's code and sends 37 page e-mails to everyone lambasting them for non-standard code. The equally stunning brunette in the next cube over sends 37 page plus 1 line e-mails detailing why she needs to use every non-standard feature of the compiler and libraries to meet her deadlines.

    Now - try to combine these people's code into a rational system. You can try development standards, mandates, code reviews, and many other practices, but the problem is that C++ is just too damn big, and ironically specifies almost nothing useful library wise, and no two people - even reasonable expert level people - can agree on what's a good practice and what's not.

    The problem isn't finding a subset you can live with. The problem is living with everyone else's subset in addition to yours and trying to make it all work somehow.

         -Mike
  75. Wow![ Go to top ]

    Tell us more about the "...stunningly beautiful red head on the 5th floor"
    and the "...equally stunning brunette in the next cube over".
  76. Wow![ Go to top ]

    \Race Condition\
    Tell us more about the "...stunningly beautiful red head on the 5th floor"
    and the "...equally stunning brunette in the next cube over".
    \Race Condition\

    I'm sorry, hair colors have been changed to protect the guilty.

        -Mike
  77. Exactly[ Go to top ]

    I have seen small groups of developers who have worked together for so long using C++ that they have managed to come to a consensus on the way they should use it. But this is a rare occurrence; the vast majority of C++ developers never achieve this, and thus the chaos that you so eloquently describe
  78. Wow![ Go to top ]

    The solution is, obviously, ask the redhead out and give her something to do with her time than criticise other peoples' code. Grizzly Adams is a punk though, there's nothing much you can do about that.
  79. What I miss...[ Go to top ]

    There's really only two things I miss about C++:

    1) const methods. They allowed you to truly enforce read-only semantics. I wish Java had something like this.

    2) Allocating objects on the stack. There are two things that are usually the cause of performance problems. Excessive use if synchronized, and object creation. C++ allowed, and stack allocation, at least allow you to alleviate that latter.

    For all you Perl fanatics posting here....Python is just so much better.

    Bill
  80. What I miss...[ Go to top ]

    <Bill>
    > 1) const methods. They allowed you to truly enforce read-only semantics. I wish Java had something like this.
    <Bill>

    Const is a great idea but actually pretty difficult to use, it should be consistent and what you often will see is that the first thing folks do are casting const away, to say nothing of physical and logical constness.

    <Bill>
    > 2) Allocating objects on the stack. There are two things that are usually the cause of performance problems. Excessive use if synchronized, and object creation. C++ allowed, and stack allocation, at least allow you to alleviate that latter.
    >
    > For all you Perl fanatics posting here....Python is just so much better.
    <Bill>

    No disagreement on stack and Python

    oleg
  81. What I miss...[ Go to top ]

    There's really only two things I miss about C++:

    >
    > 1) const methods. They allowed you to truly enforce read-only semantics. I wish Java had something like this.

    I agree to this one. Const can be misused, but with a proper approach to const-correctness semantics one could eliminate the need of all the Immutable Strings etc being constructed over and over.

    The other thing I miss is the C++ meaning of protected meaning only subclasses may call. That is great when you are building a family of classes using the Template Method pattern. In Java there is no way to put something off limits to all but subclasses.
  82. Const-correctness[ Go to top ]

    const looks great, and is one of those great theoretical concepts that craters when it touches reality. Everything runs along great in your own little const-correct world - until you run into a block of someone else's code that doesn't use it. Then all your painful const effort gets thrown away in an orgy of casting-away-const-casts.

        -Mike
  83. Const-correctness[ Go to top ]

    Not to mention that given dynamic/late class loading, bytecode generation etc. the JVM would have to be checking constness every time it executes the method. Sort of marking an instance as const from some point and throwing an exception if something tried to modify it. Except if you cast the constness away. In which case, should it be stackable? (i.e. after you finish within the scope of cast-away const, should it be const again?).
    All sorts of problems crop up here.
    Regards,
    Vlad