"break"? What is this you speak of?



  • On a whim, I ran NDepend against the wonderful code base that exists here, to see what sort of thing it would find (Methods with 13 parameters, several constructors with well over 100 lines of code, a class with 123 instance methods, another with 153 static methods). Looking into one of the methods it reported on (due to a large number of local variables), I spotted this:

    while (_dataReader.Read() && _listCount <= _recipientLimit)
    {
    	if (_listCount == _recipientLimit)
    	{
    		_listWithinLimits = false;
    		_listCount++; //This gets us out of the loop.
    	}
    	else
    	{
    		//Other stuff
    	}
    }
    

    I should also note that the underscore prefixed variables are locals, and not instance variables. Words escape me.



  • Not to mention that you could just change the less-than-or-equal test in the while condition to be a strictly-less-than test, which gets rid of the need for an if statement or break statement entirely.



  • You're missing the _listWitinLimits. May be useful to know whether the list fit on the page.

     Personally, I'd have only put the dataReader() in the while, and used if( count++ >= limit ) { in_limit = false; break; }



  • @PleegWat said:

    Personally, I'd have only put the dataReader() in the while, and used if( count++ >= limit ) { in_limit = false; break; }

    That's probably more of a WTF than the OP's snippet. I've spent many a debugging hour boggling over giant loops failing to iterate over the whole dataset as desired because a previous dev hid a break condition somewhere other than the while() condition.

    And that ++ there isn't doing anyone any favors.



  • @PleegWat said:

    You're missing the _listWitinLimits. May be useful to know whether the list fit on the page.

     Personally, I'd have only put the dataReader() in the while, and used if( count++ >= limit ) { in_limit = false; break; }

    The thing is, this isn't display code. The purpose of this code is to build up a list of email recipients from the database, up to a set limit.

    A sane person might of used a SELECT TOP statement, or something like that, or .Take() if you've ventured into the realms of a LINQ data provider. But the almighty DBManager class doesn't allow for that. Instead, we have this:

     _sql = string.Format(@"EXEC [dbo].[upMailMergeEmailList] @IsContacts = {0}, @IsProspects = {1},
                            @IsOtherContacts = {2}, @IsReferralSources = {3}, @CommunityIDY = {4},
                            @SelectionsPros = {5}, @OptionsPros = {6}, @SelectionsRef = {7},@OptionsRef = {8},
                            @OnlyIncludeInEmail = {9}",
                            _isContracts, _isProspects, _isOtherContracts, _isReferral, _communityIDY, 
                            SQLMethods.ToSQL(_selProspect), SQLMethods.ToSQL(_optionProspects),
                            SQLMethods.ToSQL(_selReferrences), SQLMethods.ToSQL(_optionReferrences),
                            SQLMethods.ToSQL(_onlyIncludeInEmail));
    

    Someone, in the cloudy past, heard that stored procedures were more secure/performant... and then started doing things like this, losing any benefits you might get from a proc. And because that's how we've always done it, that's how we're going to keep doing it.



  •  Matter of taste and more. I don't like testing against the limit twice, which is the alternative in this usecase.

     Typically I'd pull it into the SQL...



  • This gets us out of the loop

    I guess not!



  • @ArrivingRaptor said:

    That's probably more of a WTF than the OP's snippet. I've spent many a debugging hour boggling over giant loops failing to iterate over the whole dataset as desired because a previous dev hid [b]I was incapable of finding[/b] a break condition somewhere other than the while() condition.

    [b]That's[/b] more of a WTF than the OP.


  • Discourse touched me in a no-no place

    @ArrivingRaptor said:

    I've spent many a debugging hour boggling over giant loops failing to iterate over the whole dataset as desired because a previous dev hid a break condition somewhere other than the while() condition.
    TODO: add ArrivingRaptor to the list of people to not hire as a developer.

    Seriously, going seriously wrong because of missing a break doesn't put you in a good light. Either you're full of fail, or (if the loop is big/complex enough to hide its nature) you're someone who is too lazy to refactor.



  • @dkf said:

    Seriously, going seriously wrong because of missing a break doesn't put you in a good light. Either you're full of fail, or (if the loop is big/complex enough to hide its nature) you're someone who is too lazy to refactor.

    It seems that you think my previous job had any degree of automated testing, or some other easy way to verify that refactoring didn't break functionality. That's adorable!


  • Discourse touched me in a no-no place

    @ArrivingRaptor said:

    It seems that you think my previous job had any degree of automated testing, or some other easy way to verify that refactoring didn't break functionality. That's adorable!
    You are aware that there are tools that can automatically apply some refactorings? They need some supervision, but are much safer than doing it all by hand.



  • @dkf said:

    @ArrivingRaptor said:
    It seems that you think my previous job had any degree of automated testing, or some other easy way to verify that refactoring didn't break functionality. That's adorable!
    You are aware that there are tools that can automatically apply some refactorings? They need some supervision, but are much safer than doing it all by hand.

    Actually, no I wasn't. Though my last job was in PL/SQL, and as the Stack Overflow thread that pops up on Google for "pl/sql refactoring tool" says, "[There are no tools because] refactoring as a concept comes from the OOP paradigm, and PL/SQL is not object oriented." I don't care to research further since I no longer use PL/SQL and never intend to go back.

    Though it's moot because even if I did any sort of refactoring, repository check-ins were controlled by non-technical managers who made it a huge hassle to try making the code base less hilariously fragile. Such is the life of a cog at a multinational conultancy, I suppose.



  • @ArrivingRaptor said:

    Actually, no I wasn't. Though my last job was in PL/SQL, and as the Stack Overflow thread that pops up on Google for "pl/sql refactoring tool" says, "[There are no tools because] refactoring as a concept comes from the OOP paradigm, and PL/SQL is not object oriented."

    Wow. When are we going to get some posts on the ball of failure that is StackOverflow?



  • @blakeyrat said:

    When are we going to get some posts on the ball of failure that is StackOverflow?

    SO is what you get when people try to decide reality by consensus. This is how you end up with nightmares like this.

    I also learned from SO that Google created their own Javascript killer. So now we know a lot of those "20 percents" are spent re-inventing the wheel. Seriously, the twin jokes of Go and Dart have shaken any faith I had in Google as a competent organization.



  • @morbiuswilters said:

    This is how you end up with nightmares like this.

    Are you fucking kidding me? How on Earth is this possible? I knew that SO was crap but this is unbelievable bullshit



  • @morbiuswilters said:

    I also learned from SO that Google created their own Javascript killer. So now we know a lot of those "20 percents" are spent re-inventing the wheel. Seriously, the twin jokes of Go and Dart have shaken any faith I had in Google as a competent organization.

    Dart looks awesome (if only because Javascript is absolute shit), but sadly knowing Google's track record with designing programming languages, it will only be implemented in some obscure third-party fork of Firefox. Keep in mind that Google probably designed about 10% of modern JavaScript through Google Gears.



  • I loved the guy who was talking up Vim (as an IDE, match), and someone asked him how it compared to XCode and he said: I've never heard of XCode. NEVER HEARD OF IT. I mean, never used it, ok. But never HEARD of it? How is it possible to be that out-of-touch?



  • @blakeyrat said:

    I loved the guy who was talking up Vim (as an IDE, match), and someone asked him how it compared to XCode and he said: I've never heard of XCode. NEVER HEARD OF IT. I mean, never used it, ok. But never HEARD of it? How is it possible to be that out-of-touch?

    I've heard of it but never used it. From the stories I've heard from people who have used it, however, they all wish they could forget it. Maybe that guy succeeded?



  • @blakeyrat said:

    I loved the guy who was talking up Vim (as an IDE, match), and someone asked him how it compared to XCode and he said: I've never heard of XCode. NEVER HEARD OF IT. I mean, never used it, ok. But never HEARD of it? How is it possible to be that out-of-touch?

    That entire discussion is full of fail, my favorite part is when they call an IDE a "fancy tool" equating it to a luxury. Is like the people writing there are time travelers



  • @serguey123 said:

    @blakeyrat said:
    I loved the guy who was talking up Vim (as an IDE, match), and someone asked him how it compared to XCode and he said: I've never heard of XCode. NEVER HEARD OF IT. I mean, never used it, ok. But never HEARD of it? How is it possible to be that out-of-touch?

    That entire discussion is full of fail, my favorite part is when they call an IDE a "fancy tool" equating it to a luxury. Is like the people writing there are time travelers

    These are the people who heard Gates' "640kb should be enough" quote and took it as a lifelong personal challenge.



  • @MiffTheFox said:

    Dart looks awesome (if only because Javascript is absolute shit)...

    I like Javascript. Sure, it's full of stupid crap, but so is every language. Also, it had the balls to be a quasi-functional, prototypal language in a class-based languages' world. So what is Dart? It's a class-based language. Sigh.



  • @MiffTheFox said:

    Keep in mind that Google probably designed about 10% of modern JavaScript through Google Gears.

    10% is also the percentage of the world's supply of crack cocaine that Miff consumed before typing that sentence.


  • Winner of the 2016 Presidential Election

    @morbiuswilters said:

    it had the balls to be a quasi-functional, prototypal language

    But it didn't have the balls to choose a name which wouldn't forever cause non-technical users to conflate it with Java.



  • @joe.edwards said:

    @morbiuswilters said:
    it had the balls to be a quasi-functional, prototypal language

    But it didn't have the balls to choose a name which wouldn't forever cause non-technical users to conflate it with Java.

    Another feature. Then when I hear somebody say something like "Javascript comes from Java", I know I can ignore anything that person has to say, forevermore.



  • @morbiuswilters said:

    @MiffTheFox said:
    Dart looks awesome (if only because Javascript is absolute shit)...

    I like Javascript. Sure, it's full of stupid crap, but so is every language. Also, it had the balls to be a quasi-functional, prototypal language in a class-based languages' world. So what is Dart? It's a class-based language. Sigh.

    Maybe it's not a coincidence that the top five programming languages are object-oriented? I bet Dart's still going to be quasi-functional though. What are they going to do, rewrite the entire HTML API to be blocking?

    Also, Blakey, some time when I'm not working I'm going to make a comparison list of all the new HTML 5 API features and compare them to those of Gears. It's true that Google didn't have much say over the language itself, but I was including the standard library, which should be part of a language when discussing it. (Pre-emptive strike: Node.js? Maybe JS isn't a WTF in it, but from what I've heard of it it's a major WTF to run. I'm specifically referring to JavaScript as interpreted as part of the HTML suite, which is the only use of JavaScript Dart seeks to replace.)



  • @MiffTheFox said:

    Maybe it's not a coincidence that the top five programming languages are object-oriented?

    C isn't object-oriented. You can kind of fake it and follow OO conventions, but the language itself is not OO. Also, JS is OO, it's just a different type (prototypal vs. class).



  • @MiffTheFox said:

    Maybe it's not a coincidence that the top five programming languages are object-oriented? I bet Dart's still going to be quasi-functional though. What are they going to do, rewrite the entire HTML API to be blocking?

    1. The Tiobe index is shit.

    2) JavaScript is object-oriented, so I don't get what point you're trying to make exactly.

    @MiffTheFox said:

    Also, Blakey, some time when I'm not working I'm going to make a comparison list of all the new HTML 5 API features and compare them to those of Gears.

    Those are all in DOM. None of them are in JavaScript.

    @MiffTheFox said:

    It's true that Google didn't have much say over the language itself,

    They have as much as anybody else; there's an ECMA standards process.

    @MiffTheFox said:

    but I was including the standard library,

    JavaScript's standard library is tiny. It includes basically the Math object and Date object and... uh. That's about it. This is because the entire point of JavaScript is to be embedded in other applications, and therefore the application-specific library you use is 99,000 times more important than any standard library ECMA might come up with.

    You're talking about DOM, which is not JavaScript's standard library. It's HTML's standard library. HTML is one of many environments JavaScript can be plugged in to. Similarly, DOM can be used by languages other than JavaScript-- C# being a good example.

    The worst part, Miff, is that we've had this EXACT DISCUSSION on this forum like 3 times, and you still DON'T EVEN KNOW WHAT JAVASCRIPT IS. Please try to let some of the information I've provided you sink into your skull this time, so we don't have to have the discussion again.



  • @MiffTheFox said:

    I'm specifically referring to JavaScript as interpreted as part of the HTML suite, which is the only use of JavaScript Dart seeks to replace.



  • @MiffTheFox said:

    I'm specifically referring to JavaScript as interpreted as part of the HTML suite, which is the only use of JavaScript Dart seeks to replace.

    "JavaScript as part of the HTML suite" still doesn't include DOM. As I said, DOM can be used by many non-JavaScript languages.


  • Winner of the 2016 Presidential Election

    @blakeyrat said:

    @MiffTheFox said:
    I'm specifically referring to JavaScript as interpreted as part of the HTML suite, which is the only use of JavaScript Dart seeks to replace.

    "JavaScript as part of the HTML suite" still doesn't include DOM. As I said, DOM can be used by many non-JavaScript languages.

    Filed under: awkward phrasing won't save you this time

    I think you're being the pedantic dickweed this time; he didn't say DOM, but DOM was clearly what he meant by "HTML suite".



  • @joe.edwards said:

    I think you're being the pedantic dickweed this time; he didn't say DOM, but DOM was clearly what he meant by "HTML suite".

    Fine; that's what he meant.

    But we're talking about JavaScript, NOT DOM. So it's irrelevant to the discussion.



  • Actually, we were talking about Google Dart, but if you want to go all Stallman on me, fine. For now on it's DOM/JavaScript.

    Besides, I had thought the term DOM was deprecated when the DOM spec was incorporated into HTML5's. Guess not.

    Going back to my original statement before you got all pedantic on me, keep in mind that Google probably designed about 10% of modern DOM/JavaScript through Google Gears. Happy now?



  • @MiffTheFox said:

    @blakeyrat said:
    ...

    Actually, we were talking about Google Dart, but if you want to go all Stallman on me, fine. For now on it's DOM/JavaScript.

    LOL. They're both unattractive fanatics in their own way.



  • @MiffTheFox said:

    Going back to my original statement before you got all pedantic on me, keep in mind that Google probably designed about 10% of modern DOM/JavaScript through Google Gears. Happy now?

    No because DOM has nothing to do with JavaScript.

    DOM is just one of the many libraries JavaScript can access. That's like saying if I download Twitterizer third-party library for C#, the guy who wrote Twitterizer "designed" C#... it's complete nonsense.

    I'm not being a pedantic dickweed, other than pointing out that 1) words have meanings, and 2) if you plug the meanings into the statements Miff is making, it's GIBBERISH.

    And also he's dodging the bit about how he seemed to be implying that JavaScript wasn't object-oriented when it clearly is. Conclusion: Miff is an idiot.



  • @blakeyrat said:

    @MiffTheFox said:
    Going back to my original statement before you got all pedantic on me, keep in mind that Google probably designed about 10% of modern DOM/JavaScript through Google Gears. Happy now?

    No because DOM has nothing to do with JavaScript.

    DOM is just one of the many libraries JavaScript can access. That's like saying if I download Twitterizer third-party library for C#, the guy who wrote Twitterizer "designed" C#... it's complete nonsense.

    I'm not being a pedantic dickweed, other than pointing out that 1) words have meanings, and 2) if you plug the meanings into the statements Miff is making, it's GIBBERISH.

    And also he's dodging the bit about how he seemed to be implying that JavaScript wasn't object-oriented when it clearly is. Conclusion: Miff is an idiot.

    JavaScript was designed by Netscape. DOM was designed by Netscape. JavaScript was designed to interface with DOM and vice versa.

    To make your example more apt, it's like saying that the guys who designed ASP.NET or LINQ designed C#. They did. C# even has language-specific features just for LINQ, an example of how developing the standard library əffects* the language.

    That's like you saying I shouldn't refer to the JRE as part of Java because Java can also be used on Android Dalvik.

     

    As for JavaScript having real OO, what would the JS equivalent to this be:

    public abstract class Foo
    {
        public virtual void Blarh(){
            Console.WriteLine("Hello, world!");
        }
    }
    public class FriendlyFoo : Foo
    {
        public override void Blarh(){
            Console.Write("Friendly foo says: ");
            base.Blarh();
        }
    }
    

     

    * I don't care whether it's affects or effects. Gramar nazism stunts language evolution.



  • @MiffTheFox said:

    JavaScript was designed by Netscape. DOM was designed by Netscape.

    True.

    @MiffTheFox said:

    JavaScript was designed to interface with DOM and vice versa.

    Not true.

    DOM was designed to interface with *any* programming language that might someday be used in a browser. So far that's consisted of exactly 2 languages: JavaScript and ActiveX. And ActiveX is dead. But the fact remains that DOM is, and always has been, language-agnostic.

    @MiffTheFox said:

    To make your example more apt, it's like saying that the guys who designed ASP.NET or LINQ designed C#. They did. C# even has language-specific features just for LINQ, an example of how developing the standard library əffects* the language.

    LINQ yes, ASP.NET no.

    ASP.NET is just a DLL. Anybody can make a DLL. It's not part of the core C# language. There's no special features in C# written specifically to support ASP.NET.

    C# has special features to support LINQ. True. This demonstrates how the library affects the language. False. Well. Maybe. Let's say "iffy". But either way, this has nothing to do with DOM which is entirely 100% separate from JavaScript.

    @MiffTheFox said:

    That's like you saying I shouldn't refer to the JRE as part of Java because Java can also be used on Android Dalvik.

    That's a difference case, because "Java" is the name of the entire stack, which is confusing as fuck.

    The JRE is part of "Java-the-stack", it's not part of "Java-the-language".

    @MiffTheFox said:

    As for JavaScript having real OO,

    JS has real OO, unless you're redefining the term "object orientation" to something other than the common usage.

    JS does not have inheritance. Inheritance is not required to be OO.



  • Can't DOM be part of "JavaScript-the-stack" which is part of "HTML-the-stack"?! (This is what I've been saying over and over that you don't seem to understand.)

    As for inheritance, then let's say I'd be glad to have a web language that supports inheritance.



  • @MiffTheFox said:

    Can't DOM be part of "JavaScript-the-stack"

    JavaScript-the-stack doesn't exist. There's no such thing.

    JavaScript is just tiny language designed to be embedded as a scripting language in other environments. It also has a tiny library. That's what JavaScript is. That's all it is. That's all it ever has been.

    If you're talking about anything else, you're not talking about JavaScript.

    @MiffTheFox said:

    (This is what I've been saying over and over that you don't seem to understand.)

    That's because it's gibberish, it makes no sense. If you said over and over again, "dog dishwater oxygen sadly" I also would fail to understand what you were trying to communicate.

    @MiffTheFox said:

    As for inheritance, then let's say I'd be glad to have a web language that supports inheritance.

    Fair enough; but JavaScript is an object-oriented language. Let that sink into your tiny little brain so we don't have to have this discussion yet again in another 3 months.



  • Let me try to explain my feeling on Dart then in terms your monolithic brain can understand. Google did not design JavaScript, no, but they designed a good chunk of the DOM, which makes them qualified to develop another language to interface with it. Since most JS development is against the DOM, this makes Dart a direct competitor to JavaScript.

    Now, let me blow up on you for having obviously no idea what ActiveX is. (Hint: it competed with Java, not JavaScript.)



  • @MiffTheFox said:

    As for inheritance, then let's say I'd be glad to have a web language that supports inheritance.

    Technically JS supports inheritance, although it is different than the class-based inheritance that is standard in most other OO languages. JS uses prototypal inheritance, where an object can have a single prototype set (which is itself just an object, and may have its own prototype set, etc..) When you access a function/property in JS, it first looks to see if a property of that name explicitly belongs to that object; if not, it will then it will look up the prototype chain, seeing if any of those objects have a property with that name, until it either finds one, or runs out of prototypes to look at.

    This has some advantages over class-based inheritance, and some disadvantages. Personally, I like it, although I think the entire concept of inheritance should probably be abandoned for better composition support, but shrug



  • @MiffTheFox said:

    Now, let me blow up on you for having obviously no idea what ActiveX is. (Hint: it competed with Java, not JavaScript.)

    And it's definitely not a language. Would be more appropriate to say that it competed with, uh, jars or something.



  • @boomzilla said:

    @MiffTheFox said:
    Now, let me blow up on you for having obviously no idea what ActiveX is. (Hint: it competed with Java, not JavaScript.)

    And it's definitely not a language. Would be more appropriate to say that it competed with, uh, jars or something.

    Java applets.



  • @blakeyrat said:

    DOM is just one of the many libraries JavaScript can access. That's like saying if I download Twitterizer third-party library for C#, the guy who wrote Twitterizer "designed" C#... it's complete nonsense.

    I'm not being a pedantic dickweed, other than pointing out that 1) words have meanings, and 2) if you plug the meanings into the statements Miff is making, it's GIBBERISH.

    And also he's dodging the bit about how he seemed to be implying that JavaScript wasn't object-oriented when it clearly is. Conclusion: Miff is an idiot.

    Brendan Eich designed JavaScript as part of a three-day-long coffee-fueled bender so that Netscape could have some vague sort of scripting language to connect Java applets with HTML content (i.e. the proto-DOM).

    Now, to rephrase Miff yet again, "Google probably designed about 10% of what JavaScript, as the only scripting language used in all of IE, Firefox, Safari, Chrome, and Opera, is most commonly used for today."

    Happy? I am.


  • So I got to reading this and I feel way smarter now.

    @MiffTheFox said:

    * I don't care whether it's affects or effects. Gramar nazism stunts language evolution.

    Using the wrong word is a wonderful misappropriation of language evolution.

    Your code sample would require some extra boilerplate, since JS doesn't have a convenient keyword 'base' or 'super'.

     


  • Winner of the 2016 Presidential Election

    @morbiuswilters said:

    @MiffTheFox said:
    As for inheritance, then let's say I'd be glad to have a web language that supports inheritance.

    Technically JS supports inheritance, although it is different than the class-based inheritance that is standard in most other OO languages. JS uses prototypal inheritance, where an object can have a single prototype set (which is itself just an object, and may have its own prototype set, etc..) When you access a function/property in JS, it first looks to see if a property of that name explicitly belongs to that object; if not, it will then it will look up the prototype chain, seeing if any of those objects have a property with that name, until it either finds one, or runs out of prototypes to look at.

    This has some advantages over class-based inheritance, and some disadvantages. Personally, I like it, although I think the entire concept of inheritance should probably be abandoned for better composition support, but shrug

    This is correct, but you can also tack new properties onto existing instantiations of objects to accomplish what Douglas Crockford calls "parasitic inheritance".

    @Douglas Crockford said:
    Classical inheritance is about the is-a relationship, and parasitic inheritance is about the was-a-but-now's-a relationship.


  • @joe.edwards said:

    This is correct, but you can also tack new properties onto existing instantiations of objects...

    Yeah, I should have clarified: every object can have its properties modified. If you modify a property of an object that is being used as a prototype, then that will be picked up by every sub-object that has that object as a prototype.

    @joe.edwards said:

    ...to accomplish what Douglas Crockford calls "parasitic inheritance".

    Huh. That's an odd name for it.



  • @MiffTheFox said:

    As for JavaScript having real OO, what would the JS equivalent to this be:

    public abstract class Foo
    {
        public virtual void Blarh(){
            Console.WriteLine("Hello, world!");
        }
    }
    public class FriendlyFoo : Foo
    {
        public override void Blarh(){
            Console.Write("Friendly foo says: ");
            base.Blarh();
        }
    }

     

    function Foo(){
    

    }

    Foo.prototype.blarh = function(){
    alert("Foo");
    }

    function FriendlyFoo(){
    }

    FriendlyFoo.prototype = new Foo();

    FriendlyFoo.prototype.blarh = function(){
    alert("Friendly Foo");
    Foo.prototype.blarh.call(this);
    }



  • @MiffTheFox said:

    JavaScript was designed by Netscape. DOM was designed by Netscape. JavaScript was designed to interface with DOM and vice versa.

    Sorry, but Blakey is right here, both on that a) JS and DOM are independent of each other and b) that's important.

    For a), don't forget VBScript which during the time of IE monopoly ran on enough machines that it was actually used for client scripting in some products, I think. It's got full access to the DOM APIs but nevertheless has nothing to do with JS.

    For b), you can observe that when watching the WHATWG mailing lists. When it comes to DOM, they'll happily churn out one horribly convoluted new scripting API after the other, but they generally seem to be careful not to step on ECMA's feet when it comes to new language features for JS.
    (Which is actually pretty surprising as they't don't seem to have any problems stomping on the feet of every other standards body out there)

    But as for Miff's original claim:@MiffTheFox said:
    Keep in mind that Google probably designed about 10% of modern JavaScript JavaScript/DOM "javascript-the-stack" DOM through Google Gears.
    Despite all the "participation", there's still basically only one guy in the WHATWG that decides what gets into the spec in the end and what doesn't. That guy gets a Google paycheck. So I think 10% is a rather polite understatement.


  • @joe.edwards said:

    This is correct, but you can also tack new properties onto existing instantiations of objects to accomplish what Douglas Crockford calls "parasitic inheritance".


    @Douglas Crockford said:
    Classical inheritance is about the is-a relationship, and parasitic inheritance is about the was-a-but-now's-a relationship.

    I've heard about that concept, but I honestly never really got how it's supposed to work in practice and how it relates to the prototype thing. So, while we're at it, question time!

    Example: Suppose you have a "class" of objects that represent some expensive, volatile resources and need to do some heavy processing in the constructor - say a websocket connection with some custom processing and client-side state. Let's calls those type A objects.

    I want some of those objects to have slightly different behavior than the others, let's call them type B. In traditional OO, I'd make a subclass B : A, so each of my new B objects gets its own corresponding A object with its own websocket connection hidden inside. No problems there.

    Now I want to use prototypical inheritance, so I design all the new bells and whistles for my B object and create a new A object as the prototype. Oh, wait, now all my B objects suddenly share the same underlying websocket connection. In fact, I'd have to open a completely useless websocket connection only so I have a prototype instance, long before I'd actually need any of the objects. WTF?

    Ok, prototypical inheritance didn't work, let's try parasitical inheritance. So my "constructor" for B is now just a function that creates a new A object, then manually overwrites all methods that need some changing. (Let's also hope the author of the A objects remembered to call all methods by "this" and not by closure) Beautiful. There is no way to do anything resembling "instanceof" later, but whatever, it works. Only, I've not made any use of prototypes at all.

    So, my question is: What did I do wrong? Is there any non-WTF way to do this via prototypes? And if not, why do we have the prototype mechanism at all and why is everyone so hyped about it?


  • Winner of the 2016 Presidential Election

    Objects have constructors (actually any function can be a constructor, which smells funny but isn't so bad), and you can assign initial values to your instance properties there. This should solve both your "same underlying object" problem and your "dummy websocket" problem.


    function MyFoo() {}

    function MyBar() {
    this.baz = new Baz(); // each instance gets its own freshly constructed Baz (defined elsewhere)
    }

    MyBar.prototype = new MyFoo();

    var myBar = new MyBar();

    myBar instanceof MyBar; // true
    myBar instanceof MyFoo; // true


Log in to reply
 

Looks like your connection to What the Daily WTF? was lost, please wait while we try to reconnect.