Self Documenting

  • Hmmmm 2012-04-30 11:18
    This comment is self commenting (and frist)...

    No, it isn't spam either
  • mott555 2012-04-30 11:18
    public string TextToDisplayWhenThisCommentIsFrist()
    {
    return "Frist";
    }
  • ObiWayneKenobi 2012-04-30 11:19
    Actually, writing code like that (correctly though, since the method shouid be "TheFormIsValid") is a good thing. The Ruby community in particular is fond of creating little wrapper functions around calls simply to make them read better.

    This developer had his priorities backwards, however.
  • !IsSelfCommenting() 2012-04-30 11:25
    Other than the rather long method and variable names in the 2nd example, this is not really WTF code. It's readable and understandable. The names in the 2nd example could have been written better to make them shorter, and still understandable i.e ActivityNotRegistered(Activity) instead of ThisActivityIsNotRegisteredForThisEvent, but that's not a huge issue. I'd rather put up with that than XMeth(Y) and somevar anyday.
  • Re: Self Documenting 2012-04-30 11:26

    static public bool TrueIfNotReallyAWTFBecauseCodeLikeThisIsOutstandingAndAnExcellenetDocumentationTechnique()
    {
    return true;
    }
  • Hmmmm 2012-04-30 11:28
    IME everyone that has ever written "self documenting code" to that sort of ridiculous extent was deliberately taking the piss out of someone (usually the idiot managers who decided to impose ridiculous coding standard rules on the developers).
  • Bleat 2012-04-30 11:35
    It isn't spelled right either.
  • TheSi 2012-04-30 11:55
    You mean 'spelt'
  • Danno 2012-04-30 11:59
    Why not just

    public const bool TrueBecauseItsTrueAndItsNotFalse;


    I can understand good naming of methods and variables, but creating wrapper methods to create self-documentation is indefensible. Use good naming to begin with and you won't need wrapper classes.






  • a 2012-04-30 12:00
    !IsSelfCommenting():
    Other than the rather long method and variable names in the 2nd example, this is not really WTF code. It's readable and understandable. The names in the 2nd example could have been written better to make them shorter, and still understandable i.e ActivityNotRegistered(Activity) instead of ThisActivityIsNotRegisteredForThisEvent, but that's not a huge issue. I'd rather put up with that than XMeth(Y) and somevar anyday.


    I'd hardly call it readable. CamelCase becomes nearly totally unreadable after the 4th word, and underscores are better even before that.
  • Lockwood 2012-04-30 12:06
    TrueBecauseThisEventDoesNotRegistrictBasedUponActivityType

    ThisEventDoesNotRestrictRegistrantsBasedUponActivityType

    Nice to see RestrictRegistrant being shortened down.
  • mjfgates 2012-04-30 12:09
    If the developer had made one of his TrueBecauseIHateJustSaying"True"() functions return 1 instead, they could have had a real problem.
  • Alex Papadumbass 2012-04-30 12:09
    Self Commenting
  • Hmmmm 2012-04-30 12:14
    TheSi:
    You mean 'spelt'


    Please don't feed the trolls.

    Neither spelling of "spelled" or "spelt" is "incorrect". Yes, in the US, "spelt" is almost solely used for a type of wheat mainly grown in Europe but everyone with half a brain knows that the language used in the US only bears a passing resemblance to English.

    In "real" English, either form is acceptable and commonly used.
  • Geoffrey T. Buchanan 2012-04-30 12:17
    That 50 character length function name is surely a sign of the times. I learned my craft back in the day when software engineering was a serious discipline, before the kids turned up with their IPad/Facebook/Web2.0 bullshit.

    Back then 16kb was considered a LUXURY and we had to learn to write highly efficient and compact code so that it would PERFORM. Well I am sure you've all heard this before and I don't want to bang on about some "golden age" - it wasn't perfect I am not saying that. It's just that an engineer who wasted programme memory so frivolously creating a 50 character identifier back then would have been fired on the spot.

    I suppose modern businesses tolerate the complete waste of resources today because computers have got more powerful and the customer rarely complains. But you have to wonder how much faster typical software would run if it was written as per the old ways. There's also a slippery slope in play - out there now are a load of upstart "programmers" who are making all the software we use but they have no idea about how computers work let alone basic compiler theory. And people wonder why there are so many security holes and viruses in software these days...

    /rant
  • Geoffrey T. Buchanan 2012-04-30 12:21
    Hmmmm:
    TheSi:
    You mean 'spelt'


    Please don't feed the trolls.

    Neither spelling of "spelled" or "spelt" is "incorrect". Yes, in the US, "spelt" is almost solely used for a type of wheat mainly grown in Europe but everyone with half a brain knows that the language used in the US only bears a passing resemblance to English.

    In "real" English, either form is acceptable and commonly used.


    Indeed and the same is true of the word learned/learnt, something I just had to look up for my previous comment.
  • Vlad Patryshev 2012-04-30 12:28
    I find the last one beautiful.
  • Botia 2012-04-30 12:28
    I remember when methods were verbs.
  • Your Name 2012-04-30 12:33
    Botia:
    I remember when methods were verbs.

    I remember when programmers were engineers.
  • hey 2012-04-30 12:34
    minifiers and obfuscation /endrant
  • Mikerad 2012-04-30 12:42
    TGFI

    Thank Goodness For Intellisense
  • iToad 2012-04-30 12:45
    IFailToSeeAProblemWithThis. SelfDocumentingCodeIsCompletelyUnderstandableByAnyoneUsingIt. ItAlsoEliminatesTheNeedForThosePeskyComments. EveryJavaEnterpriseShopShouldConsiderDoingThis.
  • Hmmmm 2012-04-30 12:45
    Mikerad:
    TGFIAWD

    Thank Goodness For Intellisense And Widescreen Displays

    FTFY
  • Darkstar 2012-04-30 12:46
    Perfect technique for developers with an attention span that is less than 10 seconds.
  • Nickster 2012-04-30 12:46
    "this is not really WTF code. It's readable and understandable"


    So is this:

    return true; // because this event does not restrict registrant based upon activity type
  • PhilT 2012-04-30 12:48
    Not only does this code style hurt my eyes, but it does an effective job of hiding potential bugs. There may not be bugs in the example code fragment but it is so completely hidden by the overgrowth that it takes more than a second glance just trying figure out what is actually going on -- assuming the self documenting method name is correct.

    Ten years down the line, out dated comments in the code can still be useful as a guide to what the developer was thinking rather than what was implemented. This is a tremendous help when trying to maintain the code when all other documentation is also out of date or missing.

    In this new world of self documenting code, I happily remain an unconverted Luddite (for now).
  • Clueless Guy 2012-04-30 12:49
    So I've been reading this site for a couple of years now and I can't seem to place the 'frist' meme... Can anyone provide the link to the story that started that this terrible thing?

    Much Appreciated
  • Anon 2012-04-30 12:53
    Hmmmm:
    IME everyone that has ever written "self documenting code" to that sort of ridiculous extent was deliberately taking the piss out of someone (usually the idiot managers who decided to impose ridiculous coding standard rules on the developers).


    ThatWasMyInitialThoughtToo. ClearlyTheyAreBeingPassiveAggresiveWithHoweverImposedThisStyleInTheFirstPlace.
  • Anon 2012-04-30 12:55
    Mikerad:
    TGFI

    Thank Goodness For Intellisense


    Except it's still a pain the ass when the only difference between two (or more) 50+ character variable names is in the last 5 characters!
  • clive 2012-04-30 12:56
    If you're not taking the mickey in your second paragraph, how about using your VCS to see the code history and hence outdated comments rather than keeping them live?

    Of course if you are taking the mickey, I'll just mumble to myself quietly :-)
  • Anon 2012-04-30 12:58
    Geoffrey T. Buchanan:
    Hmmmm:
    TheSi:
    You mean 'spelt'


    Please don't feed the trolls.

    Neither spelling of "spelled" or "spelt" is "incorrect". Yes, in the US, "spelt" is almost solely used for a type of wheat mainly grown in Europe but everyone with half a brain knows that the language used in the US only bears a passing resemblance to English.

    In "real" English, either form is acceptable and commonly used.


    Indeed and the same is true of the word learned/learnt, something I just had to look up for my previous comment.


    And smelled/smelt, spilled/spilt, etc.

    Americans just don't like that "lt" ending. But they are usually okay with dealt rather than dealed.
  • Tasty 2012-04-30 12:59
    Geoffrey T. Buchanan:
    That 50 character length function name is surely a sign of the times. I learned my craft back in the day when software engineering was a serious discipline, before the kids turned up with their IPad/Facebook/Web2.0 bullshit.

    Back then 16kb was considered a LUXURY and we had to learn to write highly efficient and compact code so that it would PERFORM. Well I am sure you've all heard this before and I don't want to bang on about some "golden age" - it wasn't perfect I am not saying that. It's just that an engineer who wasted programme memory so frivolously creating a 50 character identifier back then would have been fired on the spot.

    I suppose modern businesses tolerate the complete waste of resources today because computers have got more powerful and the customer rarely complains. But you have to wonder how much faster typical software would run if it was written as per the old ways. There's also a slippery slope in play - out there now are a load of upstart "programmers" who are making all the software we use but they have no idea about how computers work let alone basic compiler theory. And people wonder why there are so many security holes and viruses in software these days...

    /rant


    That's why we told the British that FORTRAN spelled the short PROGRAM. The French spelling wastes two bytes.
  • CAPTCHA:sino 2012-04-30 13:07
    Botia:
    I remember when methods were verbs.

    This.

    When you start learning programming they tell you "there are variables, which can hold a value, functions, which are like actions and classes, which are like a type of object". Lies!

    Then you try to get an MD5 hash in Python and you have to do this:


    m = hashlib.md5()
    m.update("mahstring")
    hash = m.hexdigest();


    Hey! Since MD5 is a function (string -> hash), why not make it, you know, a function! (yes you can do it in one line but that's not the point)

    Sorry that was an offtopic rant. Also I hate setter and getter functions that only consist of "this.value = value" or "return this.value". Anyone who creates a language where they are necessary is a dickweed arsehole.
  • amis 2012-04-30 13:10
    What is so wrong with comments? I see this kind of crap and wonder what anybody has against comments. I agree, self documenting is good, to a point. Naming variables accurately is good, but method names don't need to say everything that happens. That's what javadoc comments are for, and they're good to have anyway in case you want to, you know, actually produce javadocs.
  • KattMan 2012-04-30 13:15
    CAPTCHA:sino:

    Sorry that was an offtopic rant. Also I hate setter and getter functions that only consist of "this.value = value" or "return this.value". Anyone who creates a language where they are necessary is a dickweed arsehole.


    Look into encapsulation and the "law" of demeter and you will know why these simple get/set methiods exist. It's not the language that requires them, you can make your variables public, but then the thing that owns them has no control over when and how they are updated.

    With that said, when the methods are this simple, where the hell are your business rules on validating the values that go into them? Are they being processed elsewhere? If so, why not in the setters to prevent bad values from even entering the picture. I don't blame the language for this one, but the "programmer".
  • mrfr0g 2012-04-30 13:16
    Most of the code I write today is passed through some sort of minify/compiler process. This allows us to use long method names, with a relatively small memory foot print.

    Psuedo Code example:
    function DoesTheDailyWTFPublishNewsArticlesEveryDay() {
    return false;
    }

    Becomes in production:
    function a() {
    return false;
    }
  • adiener 2012-04-30 13:18
    Controller talking directly to (or instantiating?) the view? Not the most ideal application of MVC either.
  • Nickster 2012-04-30 13:20
    When you start learning programming they tell you "there are variables, which can hold a value, functions, which are like actions and classes, which are like a type of object". Lies!


    Indeed. One of my pet peeves is object-oriented frameworks that create objects for actions. Actions are methods, kids.

    Also I hate setter and getter functions that only consist of "this.value = value" or "return this.value". Anyone who creates a language where they are necessary is a dickweed arsehole.


    Ah, but if you just use a data member (variable) then you lose the benefit of calling other methods from your getter/setter to produce unpredictable side effects!
  • Rob C. 2012-04-30 13:23
    Geoffrey T. Buchanan:
    It's just that an engineer who wasted programme memory so frivolously creating a 50 character identifier back then would have been fired on the spot.

    I'm sorry, but if debug symbols aren't on, do any compiled languages even keep track of the function names? My understanding was the cryptically illegible nature of function names in older code was primarily due to compiler limitations, not performance reasons.
  • Rob C. 2012-04-30 13:28
    amis:
    What is so wrong with comments? I see this kind of crap and wonder what anybody has against comments. I agree, self documenting is good, to a point. Naming variables accurately is good, but method names don't need to say everything that happens. That's what javadoc comments are for, and they're good to have anyway in case you want to, you know, actually produce javadocs.

    Depends on the consumer of the code. For someone who is likely to be modifying the code itself, comments as documentation tend to become stale and eventually misleading. Lazy coders will modify the code without touching the comments, and the next thing you know the comment is talking about something dozens of lines away, and is inaccurate due to implementation changes.

    Comments on "finished" code, however, are potentially far more useful, especially if the consumer just wants the functionality and doesn't expect to dive into the code themselves.
  • tundog 2012-04-30 13:29
    I suppose modern businesses tolerate the complete waste of resources today because computers have got more powerful and the customer rarely complains.


    Oh boy, sounds like you used to walk to school barefoot, uphill, both ways...

    Have you heard of Moore's Law? The tremendous gains in processing power and storage mean that we can develop software more quickly and leverage higher-level design constructs without getting bogged down in the muntia of shift registers. 16kb is, in fact, no longer a luxury...
  • Aargle Zymurgy 2012-04-30 13:31
    Nickster:
    "this is not really WTF code. It's readable and understandable"


    So is this:

    return true; // because this event does not restrict registrant based upon activity type


    Agreed. Look at the "return true" and absorb. If you need to know in detail "why" then you read the comment. One of the nicest manuals I ever read was in the early days of "microcomputers" (pre-PC days) that was printed using 3 typefaces and indents. The first was big and bold and simple. The second had details. The 3rd was small and deeply indented and contained all the gruesome technical details that mostly you didn't need except in problem-solving situations.

    Get the detail you want at the point you need it; it's a mindset you don't encounter often.
  • lolwtf 2012-04-30 13:39
    "Registrict."

    Re: Self Documenting:

    static public bool TrueIfNotReallyAWTFBecauseCodeLikeThisIsOutstandingAndAnExcellenetDocumentationTechnique()
    {
    return FILE_NOT_FOUND;
    }
    Fixed that for you.
  • tabana 2012-04-30 13:43
    Maybe they should use Doxygen instead.
  • Nagesh 2012-04-30 13:45
    This is definitely more acceptable alternative than production code where all variables are like
    int i; int j, string str; etc.

    That kind of code become very confusing for developer, yet we see severe examples of such coding practice in project.

    Was code review not held to consider the horrorofying effect it will have on future programmers who have to work from offshore development centers in US time-zones?
  • clive 2012-04-30 13:46
    amis:
    What is so wrong with comments? I see this kind of crap and wonder what anybody has against comments.


    I'm guessing you've not been doing dev for long enough to learn from experience. Comments in theory are great. In real life they're often wrong or useless.

    Comments are code, and if they are there should be treated to the same quality control process. Unfortunately they're invisible to much of that process - the computer ignores them so there's no compile or test failure, so you're left with stuff like peer review, and too many people simply don't understand the problem.

    If you're one of the few % who maintains your comments as well as your code, I'll congratulate you. The rest get me grumbling at them.
  • Rajendra Kumar 2012-04-30 13:50
    amis:
    What is so wrong with comments? I see this kind of crap and wonder what anybody has against comments. I agree, self documenting is good, to a point. Naming variables accurately is good, but method names don't need to say everything that happens. That's what javadoc comments are for, and they're good to have anyway in case you want to, you know, actually produce javadocs.

    Dearest Amis,
    Can you plz provide me with the codes for producing javadoc from C#? It's requirement from my hungry client. It's URGENT!!!
    Thx,
    Raj Kumar
    Executive Team Lead
  • me 2012-04-30 13:57
    I remember when Engineers had to have degrees and built tangible things.
  • It's a Cock! It's a Fist! It's Zoonerman! 2012-04-30 14:01
    KattMan:
    CAPTCHA:sino:
    Sorry that was an offtopic rant. Also I hate setter and getter functions that only consist of "this.value = value" or "return this.value". Anyone who creates a language where they are necessary is a dickweed arsehole.
    Look into encapsulation and the "law" of demeter and you will know why these simple get/set methiods exist. It's not the language that requires them, you can make your variables public, but then the thing that owns them has no control over when and how they are updated.

    With that said, when the methods are this simple, where the hell are your business rules on validating the values that go into them? Are they being processed elsewhere? If so, why not in the setters to prevent bad values from even entering the picture. I don't blame the language for this one, but the "programmer".
    Fields in Fantom

    Jesus fucking himself with a huge horse dildo! Why did it take so long to get properties right?
  • F 2012-04-30 14:03
    Geoffrey T. Buchanan:


    ... I don't want to bang on about some "golden age" ...

    /rant


    Who do you think you're kidding?
  • Anon Y Mouse 2012-04-30 14:03
    Look at the output running nm on a library or executable on a linux system. You'll see all your classes, methods, enums and so much more!
  • KattMan 2012-04-30 14:07
    It's a Cock! It's a Fist! It's Zoonerman!:
    Fields in Fantom

    Why did it take so long to get properties right?


    What do you mean by right? Fantom only generates the basic setters and getters for you if you don't write them yourself, so it still follows the same idea. They do this "So if you add one later you won't have to recomoile everything" whuich is why a lot of us provide the setter and getter even though it isn't really doing much.

    I will still stand on my previous words though, if all you have is that in a business object where are your rules for proper values? A phone number setter should at least check for proper formatting, a quantity should at least check for proper range limits, etc.
  • Your Name 2012-04-30 14:17
    KattMan:
    CAPTCHA:sino:

    Sorry that was an offtopic rant. Also I hate setter and getter functions that only consist of "this.value = value" or "return this.value". Anyone who creates a language where they are necessary is a dickweed arsehole.


    Look into encapsulation and the "law" of demeter and you will know why these simple get/set methiods exist. It's not the language that requires them, you can make your variables public, but then the thing that owns them has no control over when and how they are updated.


    No, this is an artifact of the languages you use, and you're so used to it that you can't imagine it any other way. Look at the way Python, for instance, implements "properties". You have a public variable, and then later, if you need access to that public variable to go through a method, you can change it to do that transparently to the code that uses that class doesn't need to change. Only in C++ and the languages derived from it (e.g. Java) do you see everyone "defensively" creating getters and setters for everything right off the bat.
  • It's a Cock! It's a Fist! It's Zoonerman! 2012-04-30 14:19
    KattMan:
    It's a Cock! It's a Fist! It's Zoonerman!:
    Fields in Fantom

    Why did it take so long to get properties right?


    What do you mean by right? Fantom only generates the basic setters and getters for you if you don't write them yourself, so it still follows the same idea. They do this "So if you add one later you won't have to recomoile everything" whuich is why a lot of us provide the setter and getter even though it isn't really doing much.

    I will still stand on my previous words though, if all you have is that in a business object where are your rules for proper values? A phone number setter should at least check for proper formatting, a quantity should at least check for proper range limits, etc.
    By "right", I mean you're not required to right any more code than is necessary, whether you want to validation/calculation code at first or not.

    C# disappointed me with their attempt at auto-implemented properties which often still require you to declare a separate, private field.
  • Stan Rogers 2012-04-30 14:22
    Oh, my $_DEITY, they're Greenspunning COBOL (the language in which a short novel about the program is the program)!
  • Jay 2012-04-30 14:32
    Rob C.:
    Depends on the consumer of the code. For someone who is likely to be modifying the code itself, comments as documentation tend to become stale and eventually misleading. Lazy coders will modify the code without touching the comments, and the next thing you know the comment is talking about something dozens of lines away, and is inaccurate due to implementation changes.


    True, but it's not clear how that is an argument in favor of code like the example here. It is true that a programmer may change what a function does and forget or not bother to change the comment. But it is surely even more true that a programmer would be unlikely to change function or variable names. That would require finding all the references and updating them.

    I have fond memories of a function I once wrote that I called "validateStockNumber". It accepted a stock number as a parameter, looked it up on the database, and returned true if it was found and active, false otherwise. Than another programmer came along and changed this function to also do a bunch of additional work and update the database. I really disliked the fact that a function whose name implied it just did a validation in fact also did database updates. Later someone made another change that removed the validation. But he left the function name unchanged. It was now totally misleading. Some time later another programmer had to build a VB interface to the Java code, mostly consisting of pass-thru functions. He called the pass thru on this one, "ValidateStockNumberButReallyUpdateShippingManifest".
  • Lee 2012-04-30 14:40
    Correct me if I'm wrong, but (in the case of .NET) doesn't compiling to CLR make it so this doesn't make it take extra memory?
  • bjolling 2012-04-30 14:48
    adiener:
    Controller talking directly to (or instantiating?) the view? Not the most ideal application of MVC either.
    In ASP.NET the Controller does not talk to the view, it returns an ActionResult to the ASP.NET MVC framework. So the line "return View("Index", form);" just means: "After processing my Action, I want the framework to open the "Index" view and pass in this 'form' ViewModel object."

    You can easily write a unit test against this Controller Action. After calling an Action, you can test if the ActionResult is typeof(View) with the ViewName ("Index") and ViewModel ('form') you were expecting
  • Jay 2012-04-30 14:50
    This embodies the highly questionable idea that longer names are always better. Who says?

    I agree that extremely short names, like "x" or "i1", are likely to be uninformative.

    But extremely long names mean that figuring out whether two names are the same is now a chore. If I have a variable called "AmountBilledToTheCustomerForShippingChargesOnPackagesSentOverseas" and another called "AmountBilledToTheClientForShippingChargesOnPackagesSentOverseas" and another called "AmountBilledToTheCustomerForShippingChargesOnMailersSentOverseas", etc, it is very easy to get confused when trying to make sense of the program.

    No name you give is going to tell the reader exactly what the function does unless the name repeats all of the code contained in that function. At which point, why bother to write a function at all? Just write the code in-line. At best, a name gives the reader a clue what the function is for. At a minimum, it should be meaningful enough that once the reader has figured out what it does, when he sees the name again he can recognize it.

    Sure, suppose I create a function to calculate sales tax and I call it "f32". Then I have a function to calculate shipping charges that I call "f33", a function to apply discounts that I call "f34", etc. When I come back to this program in a few months it's unlikely I'll remember which was which. Even after I figure it out again, it will be easy to get confused working my way through the code.

    At the other extreme, if I call them "FunctionToCalculateTheSalesOnASaleMadeToACustomerFromOneOfOurStoresOrOverTheInternet", "FunctionToCalculateTheShippingCharesOnASaleMadeToACustomerFromOneOfOurStoresOrOverTheinternet", etc, that will be almost as painful to read and comprehend.

    But if I call them "calcSaleTax", "calcShipping", and "applyDiscount", the names are reasonably descriptive, easy to remember, and easy to read.

    Let me add that if two functions are similar, the name should tell me how they are similar and how they are different. Like "calcDomesticShipping" and "calcInternationalShipping". Then I can clearly see that both have to do with shipping but one is about domestic and the other is about international. It drives me nuts when programmers give two functions similar names with no clue about how they are different. Like just adding a digit, so we have calcShipping and calcShipping1. Or deliberately mis-spelling a word, like calcShipping and calcShppng. Then I have to guess how they're different.

    Okay, I'm off on a tangent of at least somewhat serious discussion rather than the simple ridicule and meme-repetition. Sorry.
  • big picture thinker 2012-04-30 14:56
    Geoffrey T. Buchanan:
    I suppose modern businesses tolerate the complete waste of resources today because computers have got more powerful and the customer rarely complains. But you have to wonder how much faster typical software would run if it was written as per the old ways. There's also a slippery slope in play - out there now are a load of upstart "programmers" who are making all the software we use but they have no idea about how computers work let alone basic compiler theory. And people wonder why there are so many security holes and viruses in software these days...

    /rant


    It's written for the .NET framework so it will have terrible performance anyway compared to an unmanaged natively compiled executable. Any further performance penalty caused by terrible coding practices will probably come out in the wash.
  • Anon 2012-04-30 15:04
    Jay:

    Okay, I'm off on a tangent of at least somewhat serious discussion rather than the simple ridicule and meme-repetition.


    Frist! Irish Girl! Bring back MFD! Oh....sorry.
  • Anon 2012-04-30 15:09
    Jay:

    Let me add that if two functions are similar, the name should tell me how they are similar and how they are different. Like "calcDomesticShipping" and "calcInternationalShipping".


    Or better yet, have a DomesticOrder class and a InternationalOrder class that both inherit from an abstract base Order class and implement their own CalcShipping functions.

    That way the code becomes self-documenting without adding blot to function names. One is DomesticOrder.CalcShipping and the other is InternationalOrder.CalcShipping. If you're looking at CalcShipping inside the InternationOrder class, it should be obvious that it's calculating international shipping! And you don't have to mess around with lots of:

    if (isDomesticOrder)
    order.CalcDomesticShipping();
    else
    order.CalcInternationShipping();

    Now it's just

    order.CalcShipping();
  • Anon 2012-04-30 15:10
    big picture thinker:
    Geoffrey T. Buchanan:
    I suppose modern businesses tolerate the complete waste of resources today because computers have got more powerful and the customer rarely complains. But you have to wonder how much faster typical software would run if it was written as per the old ways. There's also a slippery slope in play - out there now are a load of upstart "programmers" who are making all the software we use but they have no idea about how computers work let alone basic compiler theory. And people wonder why there are so many security holes and viruses in software these days...

    /rant


    It's written for the .NET framework so it will have terrible performance anyway compared to an unmanaged natively compiled executable. Any further performance penalty caused by terrible coding practices will probably come out in the wash.


    Obvious troll is obvious.
  • KattMan 2012-04-30 15:11
    Anon:

    Or better yet, have a DomesticOrder class and a InternationalOrder class that both inherit from an abstract base Order class and implement their own CalcShipping functions.


    Not been here long have you. NEVER assume someone might actually do the sane thing.
  • LANMind 2012-04-30 15:13
    Say what you will about long object names. I'm working with a database designed by a guy who grew up in an era when every fucking byte was precious. If he could still pack his number fields, he would. I've spent (not spended) a week trying to follow his cryptic mess, and I'm ready to kill someone.
  • Rob C. 2012-04-30 17:00
    Jay:
    Rob C.:
    Depends on the consumer of the code. For someone who is likely to be modifying the code itself, comments as documentation tend to become stale and eventually misleading. Lazy coders will modify the code without touching the comments, and the next thing you know the comment is talking about something dozens of lines away, and is inaccurate due to implementation changes.


    True, but it's not clear how that is an argument in favor of code like the example here. It is true that a programmer may change what a function does and forget or not bother to change the comment. But it is surely even more true that a programmer would be unlikely to change function or variable names. That would require finding all the references and updating them.

    That's an interesting conundrum. Personally I'm pretty anal about changing things like this everywhere, but in part that's because the barrier to doing so is pretty small with an IDE. Maybe one isn't inherently better than the other, I'm just so accustomed to one approach it seems intuitively easier.

    Jay:
    I have fond memories of a function I once wrote that I called "validateStockNumber". It accepted a stock number as a parameter, looked it up on the database, and returned true if it was found and active, false otherwise. Than another programmer came along and changed this function to also do a bunch of additional work and update the database. I really disliked the fact that a function whose name implied it just did a validation in fact also did database updates. Later someone made another change that removed the validation. But he left the function name unchanged. It was now totally misleading. Some time later another programmer had to build a VB interface to the Java code, mostly consisting of pass-thru functions. He called the pass thru on this one, "ValidateStockNumberButReallyUpdateShippingManifest".

    Someone in that chain of failure deserved a slap. Probably the dev who added side effects to a setter.
  • YF 2012-04-30 17:06
    My eyes hurt.
  • Lurch 2012-04-30 17:28
    Not a WTF at all.

    Actually, the code IS self-documenting. A "manager" can read it, and determine the business cases that the code implements. A modern COBOL!

    About the only thing I would change (in a code review) would be
    "ThereIsAtLeastOneSharedActivityTypeBetweenTheEventAndCurrentUser"

    That function is not a declaration, but a predicate, and should be named

    "IsThereAtLeastOneSharedActivityTypeBetweenTheEventAndCurrentUser"

    Now, personally, I would prefer underscore separators for readability, but that is secondary. (I would also like the ability to use ? in names if this sort of thing is being done).

    ("Is_there_at_least_one_shared_activity_type_between_the_event_and_current_user?" would be better, because it wouldn't slow down reading as much)

    The wrapping of "true" and "false" is pure syntactic sugar. The compiler should be capable of optimizing these completely away, anyway.

    The logic is approachable by a reader who is not capable of abstract thought. It embodies the business cases. It is maintainable (by use of IDE tools). There are no comments to get out of date. The path of least resistance is to properly update the code, and the "manager" will be able to tell if it hasn't been done correctly.

    Really, for most business logic, this is almost perfect. If this style could have been conceived when COBOL was designed, it would have been.
  • Friedrice the Great 2012-04-30 17:38
    Lurch:
    Not a WTF at all.

    Actually, the code IS self-documenting. A "manager" can read it, and determine the business cases that the code implements. A modern COBOL!

    About the only thing I would change (in a code review) would be
    "ThereIsAtLeastOneSharedActivityTypeBetweenTheEventAndCurrentUser"

    That function is not a declaration, but a predicate, and should be named

    "IsThereAtLeastOneSharedActivityTypeBetweenTheEventAndCurrentUser"

    Now, personally, I would prefer underscore separators for readability, but that is secondary. (I would also like the ability to use ? in names if this sort of thing is being done).

    ("Is_there_at_least_one_shared_activity_type_between_the_event_and_current_user?" would be better, because it wouldn't slow down reading as much)

    The wrapping of "true" and "false" is pure syntactic sugar. The compiler should be capable of optimizing these completely away, anyway.

    The logic is approachable by a reader who is not capable of abstract thought. It embodies the business cases. It is maintainable (by use of IDE tools). There are no comments to get out of date. The path of least resistance is to properly update the code, and the "manager" will be able to tell if it hasn't been done correctly.

    Really, for most business logic, this is almost perfect. If this style could have been conceived when COBOL was designed, it would have been.

    A person who is not capable of abstract thought should not be allowed anywhere near code.
  • Paul Neumann 2012-04-30 17:51
    Jay:
    This embodies the highly questionable idea that longer names are always better. Who says?

    I agree that extremely short names, like "x" or "i1", are likely to be uninformative.

    But extremely long names mean that figuring out whether two names are the same is now a chore. If I have a variable called "AmountBilledToTheCustomerForShippingChargesOnPackagesSentOverseas" and another called "AmountBilledToTheClientForShippingChargesOnPackagesSentOverseas" and another called "AmountBilledToTheCustomerForShippingChargesOnMailersSentOverseas", etc, it is very easy to get confused when trying to make sense of the program. [...]
    In .NET, it's called Namespace. In Java, it's called Package. In English, it's called context.

    Truly, such long method names are not necessary iff* the path and class are named properly as well. Architecting properly encapsulated features will lead to extremely easy to read, modify, and maintain code bases.

    Example: CustomerOperations.Sales.ShippingCalculator()
    If I am already within the Sales package/namespace, then it is obvious I what the ShippingCalculator refers to. If I am in the MerchandiseOperations.Inventory.Warehouse package/namespace, then a call to such a distant package/namespace should raise a code smell.

    * as in if and only if, not merely a typo
  • Paul Neumann 2012-04-30 17:53
    LANMind:
    Say what you will about long object names. I'm working with a database designed by a guy who grew up in an era when every fucking byte was precious. If he could still pack his number fields, he would. I've spent (not spended) a week trying to follow his cryptic mess, and I'm ready to kill someone.
    I've kilt (not killded) many ones for far less.
  • stew 2012-04-30 17:56
    Anyone else read:
    private bool TheFormIsInvalid()
    
    {
    return ModelState.IsValid == false;
    }
    as:
    private bool TheFormIsValid()
    
    {
    return ModelState.IsValid == false;
    }
    the first time they saw it? Because obviously that's much more semantically clear and "documenting" than a negative boolean test:
    if (!ModelState.IsValid)
    But now I'm just regurgitating the original article.

    Only two reasons exist to move logic into a separate method/function:
    1) It's used in multiple places.
    2) It needs to be invoked separately from the code block it's being removed from (which is really just #1 in reverse).

    Otherwise all you're doing is wasting your time and, more importantly, the time of any poor soul having to look at your code abortion after you've moved on.

    If you're not capable of processing more than one logical operation per line of code, then you should really go back to creating refrigerator art with your crayons.
  • Lost in Code 2012-04-30 18:03
    I remember when software guys were not good enough for the engineer title and double E's would rant when ever someone used software and engineer in the same sentence. LOL
  • Some Damn Yank 2012-04-30 19:06
    TheSi:
    You mean 'spelt'
    No, he means 'spelled', as in casting a spell.
  • Some Damn Yank 2012-04-30 19:11
    Lost in Code:
    I remember when software guys were not good enough for the engineer title and double E's would rant when ever someone used software and engineer in the same sentence. LOL
    As a Mechanical Engineer who finds himself in the software business because Boeing found it easier to teach programming to Engineers than to teach engineering to CS grads, I have to say it's not just the EE's who feel that way. IMHO software guys may never be good enough for the Engineer title. Engineering is a discipline few CS grads follow.
  • Some Damn Yank 2012-04-30 19:15
    me:
    I remember when Engineers had to have degrees and built tangible things.
    We still do. CS grads are NOT engineers any more than working at McDonalds makes you a chief.
  • Nickster 2012-04-30 20:45
    Engineering is a discipline few CS grads follow.


    So, in your opinion, could the principles of engineering be applied to the construction of software if they were taught and practiced?
  • geoffrey, MCP, PMP 2012-04-30 21:03
    mott555:
    public string TextToDisplayWhenThisCommentIsFrist()
    {
    return "FAIL";
    }


    FTFY.
  • The Great Neckbeardio 2012-04-30 21:08
    Geoffrey T. Buchanan:
    Back then 16kb was considered a LUXURY and we had to learn to write highly efficient and compact code so that it would PERFORM.


    You got to *write* your code? LUXURY! LUXURY! Back in MY day we had to chisel our code into stone tablets! Without our bare hands!
  • minitech 2012-04-30 21:54
    The Great Neckbeardio:
    Geoffrey T. Buchanan:
    Back then 16kb was considered a LUXURY and we had to learn to write highly efficient and compact code so that it would PERFORM.


    You got to *write* your code? LUXURY! LUXURY! Back in MY day we had to chisel our code into stone tablets! Without our bare hands!


    You got to chisel your code? Paradise! Back in MY day, we had to erode our code out of the stone with precisely-placed water - when we had even that! I kilt many a developer to get the necessary blood when water was scarce.
  • clive 2012-04-30 22:04
    Nickster:
    Engineering is a discipline few CS grads follow.


    So, in your opinion, could the principles of engineering be applied to the construction of software if they were taught and practiced?


    There are people out there doing precisely that. They're the decent end of our industry, and should be encouraged.

    There is discussion in the more professional end of our industry about certification/chartership, and there's a common feeling that it's more "when" than "if".
  • clive 2012-04-30 22:11
    Rob C.:
    Jay:
    Rob C.:
    Depends on the consumer of the code. For someone who is likely to be modifying the code itself, comments as documentation tend to become stale and eventually misleading. Lazy coders will modify the code without touching the comments, and the next thing you know the comment is talking about something dozens of lines away, and is inaccurate due to implementation changes.


    True, but it's not clear how that is an argument in favor of code like the example here. It is true that a programmer may change what a function does and forget or not bother to change the comment. But it is surely even more true that a programmer would be unlikely to change function or variable names. That would require finding all the references and updating them.

    That's an interesting conundrum. Personally I'm pretty anal about changing things like this everywhere, but in part that's because the barrier to doing so is pretty small with an IDE. Maybe one isn't inherently better than the other, I'm just so accustomed to one approach it seems intuitively easier.


    It's not an argument in favour of code like in the article - there's a huge difference between that insanity and naming functions/variables to make it clear what's going on while using a minimum of comments.

    Yes, when you change what a function does, you have to rename it. Refactoring is normal - that's what you've got your test suite for, to allow you to do it safely.

    If you can't rename your function when you change what it does, you've got serious problems with your codebase or processes anyway.
  • Son Of Thor 2012-04-30 23:18
    A bit like Coco !
  • dkf 2012-05-01 00:10
    minitech:
    I kilt many a developer to get the necessary blood when water was scarce.
    Why would putting those developers in skirts help? Well, assuming they're not simultaneously Mel Gibson.
  • oheso 2012-05-01 00:32
    Some Damn Yank:
    CS grads are NOT engineers any more than working at McDonalds makes you a chief.


    Of course not. One becomes a chief by proving oneself brave and victorious in battle, repeatedly. Also by poisoning one's predecessor's bear claw soup.
  • emurphy 2012-05-01 00:41
    stew:
    Only two reasons exist to move logic into a separate method/function:
    1) It's used in multiple places.
    2) It needs to be invoked separately from the code block it's being removed from (which is really just #1 in reverse).


    3) It's long and/or complex enough to be worth black-boxing, e.g.


    PerformMainTask() {
    if (GuardCondition()) return;
    DoSomethingWithHeaderRecord(header);
    for each detail in details {
    DoSomethingWithDetailRecord(detail);
    }
    }


    where each of the three functions is, say, about 50 lines long.
  • TheRider 2012-05-01 02:05
    Paul Neumann:
    I've kilt (not killded) many ones for far less.
    Oh, so, "wearing a kilt" actually means showing off your prey?
  • Dima 2012-05-01 02:10
    I am really surprised some of the commenters think that this is not a WTF. However, it explains where the WTFs like this come from.
  • Celtic Hacker 2012-05-01 02:22
    dkf:
    minitech:
    I kilt many a developer to get the necessary blood when water was scarce.
    Why would putting those developers in skirts help? Well, assuming they're not simultaneously Mel Gibson.


    It's not a skirt, ye bloody Sasunnach!
  • Gibbon1 2012-05-01 04:16
    Nickster:
    Engineering is a discipline few CS grads follow.


    So, in your opinion, could the principles of engineering be applied to the construction of software if they were taught and practiced?


    I think of it kind of like plumbing. One one hand you have physicists designing piping in a liquid fuel rocket, on the other someone is gluing PVC pipe fittings together. In traditional engineering there is also a lot of beating on things until they work.

    It really depends. In aircraft design, every excess ounce comes out of the payload. So you pay to carry it around. Which means management is motivated to pay to get rid of it. Other fields extra weight is a one time cost that may not justify the NRE to get rid of it.
  • Claxon 2012-05-01 05:16
    clive:
    amis:
    What is so wrong with comments? I see this kind of crap and wonder what anybody has against comments.


    I'm guessing you've not been doing dev for long enough to learn from experience. Comments in theory are great. In real life they're often wrong or useless.

    Comments are code, and if they are there should be treated to the same quality control process. Unfortunately they're invisible to much of that process - the computer ignores them so there's no compile or test failure, so you're left with stuff like peer review, and too many people simply don't understand the problem.

    If you're one of the few % who maintains your comments as well as your code, I'll congratulate you. The rest get me grumbling at them.


    That's one problem with comments, but often they still give you an idea of what was going on. Even better is if you check the file history to see the comment & code at the time it was inserted.

    However I see a greater issue with this particular alternative. If one of the Self Documenting functions changes, so that the name is no longer accurate, the developer would have to rename the function and all calls to it (sometimes that's easy, but other times it can be a nightmare). Or more likely they'll just leave it with the same name and you'll get a similar issue to obsolete comments, only with it being an obsolete function name (which personally I'd find far more misleading).
  • Cockknuckles 2012-05-01 05:18
    private static bool NoActivityTypesAreAttachedToThisEvent(IEnumerable<ActivityType> activityTypes)
    {
    return activityTypes.Any() == false;
    }

    or

    private static bool NoActivityTypesAreAttachedToThisEvent(IEnumerable<ActivityType> activityTypes)
    {
    return !activityTypes.Any();
    }
  • PhilT 2012-05-01 05:41
    Exactly my point - I'm so happy not to be the only one with this experience.

    Picking up ten year old code with no change history or source repository means that you benefit from every bit of information you can glean whether code or comment.

    Where is my deer stalker hat, Watson?
  • TheRider 2012-05-01 07:14
    When reading existing code, I tend to completely ignore any comments. Mainly because comments are mostly wrong because they have been correct only at the exact moment when they were written (maybe not even then), and they almost never get updated, so much of the time, they are incorrect if not misleading.

    I prefer well-named identifiers (at all levels, be they function names, variable names, class names or whatever) at any time. But the identifiers shown in this daily-WTF take the cake. These names are less than helpful.
  • Bartholomew Taps 2012-05-01 07:20
    The identifier names in this code are a little wordy, but worse things happen in code... much worse!

    I would take issue however with the TrueBecause... and FalseBecause... methods, whose names appear to expose their implementation. What if I wanted to subclass, and change the return value from true to false? That would generate a real WTF.

    Good program design is about preventing future WTFs, and therefore saving the cost of refactoring them away (refactoring works, but it is expensive).

    In review, one might suggest toning down the wordiness a little, but one should not let that distract attention from more substantial isses.
  • Nickster 2012-05-01 08:07
    If one of the Self Documenting functions changes, so that the name is no longer accurate, the developer would have to rename the function and all calls to it


    Seems to me this would be an occasion to take a step back, and ask "why are we breaking this function?" If it no longer does what it says, perhaps the structure of the program has changed enough to warrant refactoring.

    It may also be possible to divide the new functionality between 1) a new function with a helpful name and 2) a subfunction called by the now "incorrectly" named function.
  • Al 2012-05-01 08:55
    Shouldn't self documenting code be about what it does rather than why?
    Knowing what a method does by the method name is a great but the "TrueBecauseThisEventDoesNotRegistrictBasedUponActivityType()" being a a ramble over why you return a true value.

    Maybe AddCommentToArticleBecauseItIsMyLunchTimeAndAContributionMayBeHelpful()
    is the new Article.Comments.Add()?


  • radarbob 2012-05-01 09:10
    ObiWayneKenobi:
    Actually, writing code like that (correctly though, since the method shouid be "TheFormIsValid") is a good thing. The Ruby community in particular is fond of creating little wrapper functions around calls simply to make them read better.

    This developer had his priorities backwards, however.

    "... simply to make them read better." : I used to work in a military bureaucracy. That means a two line letter (not counting salutation, etc.) took 3 weeks to "make it read better." (a true fact! (pun intended)) At some point someone has to say "the goal is understanding, not the Pulitzer for literature."
  • radarbob 2012-05-01 09:19
    If Marie Antoinette were a programmer, she would say "Let them code COBOL". If one want's to read code as if proper English, then I suggest COBOL which has the concepts of "paragraphs" and sentences"; and COBOL-68 in particular where operators had to be spelled out: "COMPUTE X EQUALS Y MULTIPLY X PLUS A." (Don't forget the period!! There. That will make those morons happy. I understand 'zactly what that calculation is about!!
  • bridget99 2012-05-01 09:35
    Isn't this just how most average programmers write their code? When I look at other people's code, it usually looks about like this to me: abusively camel-cased, with everything wrapped in stupid little functions.

    I feel quite certain that this code conforms to the misguided standards of the group tbat produced it.
  • Matt Westwood 2012-05-01 09:35
    Anon:
    Geoffrey T. Buchanan:
    Hmmmm:
    TheSi:
    You mean 'spelt'


    Please don't feed the trolls.

    Neither spelling of "spelled" or "spelt" is "incorrect". Yes, in the US, "spelt" is almost solely used for a type of wheat mainly grown in Europe but everyone with half a brain knows that the language used in the US only bears a passing resemblance to English.

    In "real" English, either form is acceptable and commonly used.


    Indeed and the same is true of the word learned/learnt, something I just had to look up for my previous comment.


    And smelled/smelt, spilled/spilt, etc.

    Americans just don't like that "lt" ending. But they are usually okay with dealt rather than dealed.


    So how come The Simpsons riffed on the old saw: "smelt it dealt it" - surely that would have been "smelled it delled it" in order to get it to rhyme?
  • Matt Westwood 2012-05-01 09:43
    radarbob:
    If Marie Antoinette were a programmer, she would say "Let them code COBOL". If one want's to read code as if proper English, then I suggest COBOL which has the concepts of "paragraphs" and sentences"; and COBOL-68 in particular where operators had to be spelled out: "COMPUTE X EQUALS Y MULTIPLY X PLUS A." (Don't forget the period!! There. That will make those morons happy. I understand 'zactly what that calculation is about!!


    In my fresh-faced early teens, having spent a happy decade or so during which I had played with flow diagrams and invented a rudimentary form of entity-relationship diagrams, I was convinced I wanted to go into a career in computing.

    "You wouldn't like computing," said the school's careers master glumly. "It's horribly tedious." How so? "This is the language you need to use to tell computers what to do." And he showed me some COBOL in the same style as above. Surely not, replied I, having had some gleeful fun programming a Texas TI-59 and a similarly-concepted HP machine to do cool stuff. "Afraid so," continued the careers master, injecting a note of sternness to modulate the Mr. Glum motif. "Hand-held calculators like that are just a silly toy that will never take off."
  • Matt Westwood 2012-05-01 09:47
    KattMan:
    It's a Cock! It's a Fist! It's Zoonerman!:
    Fields in Fantom

    Why did it take so long to get properties right?


    What do you mean by right? Fantom only generates the basic setters and getters for you if you don't write them yourself, so it still follows the same idea. They do this "So if you add one later you won't have to recomoile everything" whuich is why a lot of us provide the setter and getter even though it isn't really doing much.

    I will still stand on my previous words though, if all you have is that in a business object where are your rules for proper values? A phone number setter should at least check for proper formatting, a quantity should at least check for proper range limits, etc.

    You're doing it wrong. A phone number should be defined by a class in its own right with its own internal validation. If you're holding it as a string and banking on the class you're holding it in validating it, you've got it backarsewards.
  • TheSi 2012-05-01 09:58
    It wasn't a troll, it was a wind-up, although I was a bit drunk and bored when I said it.
  • Rootbeer 2012-05-01 10:06
    Geoffrey T. Buchanan:
    I learned my craft back in the day when software engineering was a serious discipline, before the kids turned up with their IPad/Facebook/Web2.0 bullshit.


    AKA never. The soul of computer programming has always been 'the hack', going back to the days of Ada Lovelace.

    you have to wonder how much faster typical software would run if it was written as per the old ways.


    You could test it. Take some software product and have it developed by two teams in parallel -- one using the old ways of precision and heavy optimization, the other using the new ways of lazy high-level coding.

    Then you could compare the amounts of time it took the development teams to complete the product using each approach -- and the amount of money spend on finding and retaining the superstar coders needed to write well-optimized software -- and come to the conclusion that the modern ways aren't so bad.

    The length of a variable name is a particularly silly thing to criticize on the basis of performance, as it will be tokenized almost immediately by the compiler or interpreter. The only machine resource it wastes is developers' disk space.

    And people wonder why there are so many security holes and viruses in software these days...


    Probably overflowing string buffers in the tokenizer with excessively long variable names.
  • clive 2012-05-01 10:16
    [quote user="ClaxonHowever I see a greater issue with this particular alternative. If one of the Self Documenting functions changes, so that the name is no longer accurate, the developer would have to rename the function and all calls to it (sometimes that's easy, but other times it can be a nightmare). Or more likely they'll just leave it with the same name and you'll get a similar issue to obsolete comments, only with it being an obsolete function name (which personally I'd find far more misleading).[/quote]

    Already answered : if you change the function so the name is no longer accurate, you have to change the name. If it's a nightmare, your codebase has other stinking problems.

    If the name describes in detail every aspect of what the function does, obviously you're going to be screwed if you make even the slightest change - that's why you use sensible names, not ones like in the article.

    Here if I see code has inappropriate function names or out of date/inaccurate comments, it's going back for rework unless you've got a _really_ good excuse. (technical debt can be appropriate at times)
  • Anon 2012-05-01 10:18
    Some Damn Yank:
    me:
    I remember when Engineers had to have degrees and built tangible things.
    We still do. CS grads are NOT engineers any more than working at McDonalds makes you a chief.


    CS grads aren't scientists either. As anybody who tried to read a CS paper (and has previously read real science papers) will attest.
  • KattMan 2012-05-01 10:31
    Matt Westwood:

    You're doing it wrong. A phone number should be defined by a class in its own right with its own internal validation. If you're holding it as a string and banking on the class you're holding it in validating it, you've got it backarsewards.


    Wow, did you even read what I said then read what you said? Can you even get the concept in your head without forgetting some other rudimentary thought?
    Let's hope you don't forget how to wipe your own nose when I say it this way.
    Yes you have a phone number class, but you need to set the value in it somewhere, and that is where you validate. You essentially just said what I did, because the setter you use to get your phone number into your phone number class is where you should have your validation call, not someplace later in the class, this is part of what setters are for! Validate when it comes in, not sit on it and maybe validate later.
  • Rodd 2012-05-01 11:35
    Matt Westwood:
    You're doing it wrong. A phone number should be defined by a class in its own right with its own internal validation. If you're holding it as a string and banking on the class you're holding it in validating it, you've got it backarsewards.


    Obviously. And inside that class, you store a PhoneNumberDigitArray class containing 9 instances of the PhoneNumberDigit class.
  • Re: Self Documenting 2012-05-01 11:46
    Rodd:
    Matt Westwood:
    You're doing it wrong. A phone number should be defined by a class in its own right with its own internal validation. If you're holding it as a string and banking on the class you're holding it in validating it, you've got it backarsewards.


    Obviously. And inside that class, you store a PhoneNumberDigitArray class containing 9 instances of the PhoneNumberDigit class.


    For north american phone numbers, ten instances would be more effective - but good point anyway.
  • Matt Westwood 2012-05-01 12:29
    [quote user="clive"][quote user="ClaxonHowever I see a greater issue with this particular alternative. If one of the Self Documenting functions changes, so that the name is no longer accurate, the developer would have to rename the function and all calls to it (sometimes that's easy, but other times it can be a nightmare). Or more likely they'll just leave it with the same name and you'll get a similar issue to obsolete comments, only with it being an obsolete function name (which personally I'd find far more misleading).[/quote]

    Already answered : if you change the function so the name is no longer accurate, you have to change the name. If it's a nightmare, your codebase has other stinking problems.

    If the name describes in detail every aspect of what the function does, obviously you're going to be screwed if you make even the slightest change - that's why you use sensible names, not ones like in the article.

    Here if I see code has inappropriate function names or out of date/inaccurate comments, it's going back for rework unless you've got a _really_ good excuse. (technical debt can be appropriate at times)[/quote]

    +1
  • Gibbon1 2012-05-01 12:35
    KattMan:
    Yes you have a phone number class, but you need to set the value in it somewhere, and that is where you validate.


    If you going to bother to validate a phone number, you should use a globally available service for that. And if it fails to validate, you should just warn the user, and store it anyways.

    If the user enters
    ph:91-40-2301-5223 *213
    ext: डेली पर नागेश के लिए पूछना.

    Then you should just eat it.
  • AGray 2012-05-01 12:43
    Thank goodness for tools that allow refactoring; when said programmers either go away, or learn the error of their ways, a project-wide rename will make this particular problem (mostly) go away...

    ...I hope...
  • It's a Cock! It's a Fist! It's Zoonerman! 2012-05-01 12:47
    Gibbon1:
    KattMan:
    It's a Cock! It's a Fist! It's Zoonerman!:
    <dick waving/>
    Ewwww!
    Eat it!
    Eat it, bitch!

    Mmmmm... that's right, you're a good little bitch, sucking daddy's cock... yeah...
  • caper 2012-05-01 13:09
    > return ModelState.IsValid == false;

    Argggg. Stop comparing booleans to booleans for simple answers.
  • dkf 2012-05-01 13:25
    Anon:
    CS grads aren't scientists either. As anybody who tried to read a CS paper (and has previously read real science papers) will attest.
    You should try reading more widely. Some scientific disciplines are even worse than computing for failing to cite things (and computing's main problem is mostly amnesia — a total lack of awareness of what went before) and others let you virtually leave the content out of the paper (bioscience, I'm looking at you!) The worst of the lot though is almost anything coming out of NASA's engineering teams; some of the decisions for why some satellites were built a particular way remain wholly mysterious, and I've read more than a few of the relevant reports.

    Real CS isn't too bad though; tends to cite heavily. Not that it's got much to do with Software Engineering though; at that end, it's really a branch of Mathematical Logic…
  • Nickster 2012-05-01 13:54
    Real CS isn't too bad though; tends to cite heavily. Not that it's got much to do with Software Engineering though; at that end, it's really a branch of Mathematical Logic...


    I always thought of CS as the study of the mathematical properties of computing devices, which is of course useful to computer & software engineering, but a different pursuit than engineering.

    As far as "software engineering" goes, programs are true machines, and it takes extensive knowledge and discipline to build them well. The difference is they don't live in a vacuum, they completely depend on the execution environment to perform their jobs correctly.

    Imagine how difficult it would be to build cars if you had to build one type to run on asphalt, another type to run on concrete, and yet another type to run on gravel. In some ways this is like reality - e.g. special all-terrain and off-road vehicles - but imagine if the off-road vehicle immediately halted and wouldn't restart upon hitting asphalt. Or worse, if you had to make sure the off-road vehicle was built *only* with "off-road" parts, or it would fail. What a nightmare!
  • AN AMAZING CODER 2012-05-01 14:16
    Your Name:
    KattMan:
    CAPTCHA:sino:

    Sorry that was an offtopic rant. Also I hate setter and getter functions that only consist of "this.value = value" or "return this.value". Anyone who creates a language where they are necessary is a dickweed arsehole.


    Look into encapsulation and the "law" of demeter and you will know why these simple get/set methiods exist. It's not the language that requires them, you can make your variables public, but then the thing that owns them has no control over when and how they are updated.


    No, this is an artifact of the languages you use, and you're so used to it that you can't imagine it any other way. Look at the way Python, for instance, implements "properties". You have a public variable, and then later, if you need access to that public variable to go through a method, you can change it to do that transparently to the code that uses that class doesn't need to change. Only in C++ and the languages derived from it (e.g. Java) do you see everyone "defensively" creating getters and setters for everything right off the bat.



    Agree. Groovy does this transparently as well.
  • Weaselator 2012-05-01 14:39
    Self-documenting code with overloading is even more fun.

    public bool KeepProcessingDueToDatabaseBeingUpdated()
    {
    return (this.DatabaseUpdated() || this.DataBaseNotUpdatedDueToFailure());
    }

    public bool KeepProcessingDueToDatabaseBeingUpdated(string sValue)
    {
    if (this.DatabaseUpdated()) return false;
    object oMysteryVar = null;
    this.ConvertFieldToCustomerNumber(sValue, oMysteryVar);
    this.Eviscerate(oMysteryVar);
    if (this.DataBaseNotUpdatedDueToFailure()) return false;
    return true;
    }
  • Darkstar 2012-05-01 15:42
    Nickster:
    "this is not really WTF code. It's readable and understandable"


    So is this:

    return true; // because this event does not restrict registrant based upon activity type


    Moreover - you don't have to maintain and debug trivial code that doesn't serve any purpose apart from reminding the developers what the code does. The technique in this article is error prone and doesn't contribute anything that can't be done with plain comments.
  • Re: Self Documenting 2012-05-01 15:44
    Gibbon1:
    KattMan:
    Yes you have a phone number class, but you need to set the value in it somewhere, and that is where you validate.


    If you going to bother to validate a phone number, you should use a globally available service for that. And if it fails to validate, you should just warn the user, and store it anyways.

    If the user enters
    ph:91-40-2301-5223 *213
    ext: डेली पर नागेश के लिए पूछना.

    Then you should just eat it.


    As someone who has written telephony software, yes, this is ideal, but it depends on what the number will be used for. Back to the original point of the comment, storing phone numbers as strings can miss some useful functionality, but you may not care for your application. If you do care, create a phone number class. Also, as a free tip, if you ever have to store phone numbers in a database, create two fields - one for the phone number as entered, and one for the digits only - stripped of punctuation (and converted from vanity numbers, i.e. 2 for abc, 3 for def, etc).
  • Coyne 2012-05-01 16:33
    Probably the ultimate slam that can be made: "It looks like COBOL."
  • oheso 2012-05-01 19:02
    radarbob:
    I understand 'zactly what that calculation is about!!


    Actually, you're assuming the reader knows the COBOL rules of operator precedence there.
  • mmmmmH 2012-05-01 20:03
    >Please don't feed the trolls.

    >Trolling.

    Go away creep.
  • gratuitous_arp 2012-05-01 20:52
    Your Name:
    KattMan:
    CAPTCHA:sino:

    Sorry that was an offtopic rant. Also I hate setter and getter functions that only consist of "this.value = value" or "return this.value". Anyone who creates a language where they are necessary is a dickweed arsehole.


    Look into encapsulation and the "law" of demeter and you will know why these simple get/set methiods exist. It's not the language that requires them, you can make your variables public, but then the thing that owns them has no control over when and how they are updated.


    No, this is an artifact of the languages you use, and you're so used to it that you can't imagine it any other way. Look at the way Python, for instance, implements "properties". You have a public variable, and then later, if you need access to that public variable to go through a method, you can change it to do that transparently to the code that uses that class doesn't need to change.


    As KattMan said, you can do the same thing in C++ using a public variable and later writing a get function for it if desired. People don't do this because it's bad design -- in any language -- for both of the reasons given by KattMan. As you know, in Python, there is an idiom to denote properties that should not be accessed directly by adding a leading underscore to the property's name. This access control "suggestion" is used to provide the private membership given by C++ (though not enforcing it) while retaining the language's flexibility. In PEP-8, Guido gives further examples of why this is a good idea. See: http://www.python.org/dev/peps/pep-0008/#designing-for-inheritance

    If you're writing small Python scripts it doesn't really matter (as long as you *know* they'll stay small). If you're writing large programs, it does matter.

    Only in C++ and the languages derived from it (e.g. Java) do you see everyone "defensively" creating getters and setters for everything right off the bat.


    You're talking about defensive programming, something that is hopefully common in code written in any language. Setters are just as important in Python as they are in C++ if you want any kind of assurance that anything valid is getting passed to your object. Getters hide implementation details. Other than taking some extra time to write, what specifically do you find undesirable about get/set functions?
  • Andrew 2012-05-02 00:56
    TRWTF is that nobody point these TRWTF out.

    1.) Duplication!

    ThisEventDoesNotRestrictRegistrantsBasedUponActivityType
    =>
    TrueBecauseThisEventDoesNotRegistrictBasedUponActivityType

    NoActivityTypesAreAttachedToThisEvent
    TrueBecauseThereAreNoActivityTypesToFilterOnThisEvent

    Duplication is EVIL in software.

    2.) Delayed the check of TheUserIsNotLoggedIn

    Not logged in user can DoS your system now.

    The problem with this code is that it is not succinct enough, and this can be fixed by using language that programmer understand well (assuming the readability is not meant for non-programmers)

    ThisEventDoesNotRestrictRegistrantsBasedUponActivityType
    => !event.RestrictRegistrants(ActivityType t)

    The TrueBecause* pattern is actually a good idea.
    Think if you can add log statements to those methods, you could trace the program logic with debugging.
  • Robert White 2012-05-02 01:19
    replace "m" and such with something self commenting. Then the style makes sense.

    TargetHash = hashlib.md5()
    TargetHash.update("text I want to hash")
    TargetHash.update("more text to hash as well")
    Result = TargetHash.hexdigest()

    The general case of the hash is something you build out of something that -just- -might- be in more than one string... that's why you do it in more than one call. You might not want to have all of war and peace hanging around in ram all at once.

    Stylistically the code can also read well if you don't shoot it in the knee by using variable names like "m" and "hash" for the stateful hashing engine instance and result respectively.

    ===

    Getters and Setters are not necessary, though they can be useful in several cases. It's the idiot policy makers and the cookbook programmers that have turned them into what they are today.

    If you pollute your code with them where exposing the atoms is just as good, then that's your fault.

    If you use them to be able to "verb your class" in sub classes then they make sense.

    In particular using a getter/setters is good if you expect/intend to want to invoke actions in a class or sub-class to allow things like lazy evaluation or cache clearing. The "always use" people are fattening their interfaces "just in case" someone wants to do this some day.

    The other use is to be able to make a value read-only or write-only.

    I worked at a company that had a code weasel analyzer that would flag whenever I made a variable public and skipped a getter/setter pair. It similarly required than all methods be defined outside the class (C++) in the implementation file.

    I opened a bug that said "Turning an integer assign into a cross-module (far) call has a negative impact on performance". I opened a second bug that said "Turning an integer fetch into a cross-module (far) call has a negative impact on performance". I flagged every complaint on my code with one or both of the bugs.

    I was "lightly fired". But a friend told me that they ended up using my code and fixing the standard when mine was the only code that didn't go over its time budget in the design.

    Applying rules without thought it dumb.

    ===

    The subject line is deliberate...
  • L. 2012-05-02 02:07
    mrfr0g:
    Most of the code I write today is passed through some sort of minify/compiler process. This allows us to use long method names, with a relatively small memory foot print.

    Psuedo Code example:
    function DoesTheDailyWTFPublishNewsArticlesEveryDay() {
    return false;
    }

    Becomes in production:
    function a() {
    return false;
    }


    The bad part imho is requiring those names in the first place.

    You don't need them and they obscure the real meaning of the code, thus preventing you from seeing the obvious logical duplicates in your codebase as well as possible optimizations.

    This general practice of making it easier to read for non techies and stuff only serves to hide the truth, you're speaking to a machine and it'll only ever read the compiled code, so if you want to understand it, cut the human friendly bullcrap.
  • L. 2012-05-02 02:14
    tundog:
    I suppose modern businesses tolerate the complete waste of resources today because computers have got more powerful and the customer rarely complains.


    Oh boy, sounds like you used to walk to school barefoot, uphill, both ways...


    When I was your age, we used to rocket jump all the way to school, both ways, in boiling lava !

    And fuck you. today with virtualization we can finally say that saving processing power could cause dramatic savings.

    And whoever started that trend of "moar crappy software" lied to you all. The fastest way to develop software is to develop everything only once, not to create several million copies, of which most are far from the optimal implementation and will be trashed because of that.
  • L. 2012-05-02 02:20
    LANMind:
    Say what you will about long object names. I'm working with a database designed by a guy who grew up in an era when every fucking byte was precious. If he could still pack his number fields, he would. I've spent (not spended) a week trying to follow his cryptic mess, and I'm ready to kill someone.

    Many people have used oracle, most avoid trying to read the source code though.

    Point being, fuck his datastore, use postgres.
  • L. 2012-05-02 02:35
    Rootbeer:
    Geoffrey T. Buchanan:
    I learned my craft back in the day when software engineering was a serious discipline, before the kids turned up with their IPad/Facebook/Web2.0 bullshit.


    AKA never. The soul of computer programming has always been 'the hack', going back to the days of Ada Lovelace.

    you have to wonder how much faster typical software would run if it was written as per the old ways.


    You could test it. Take some software product and have it developed by two teams in parallel -- one using the old ways of precision and heavy optimization, the other using the new ways of lazy high-level coding.

    Then you could compare the amounts of time it took the development teams to complete the product using each approach -- and the amount of money spend on finding and retaining the superstar coders needed to write well-optimized software -- and come to the conclusion that the modern ways aren't so bad.

    The length of a variable name is a particularly silly thing to criticize on the basis of performance, as it will be tokenized almost immediately by the compiler or interpreter. The only machine resource it wastes is developers' disk space.

    And people wonder why there are so many security holes and viruses in software these days...


    Probably overflowing string buffers in the tokenizer with excessively long variable names.

    I beg to differ, it makes the code less synthetic, and prevents the programmer from seeing what he is doing. I'd have a much harder time understanding what a method does if vars have longer names, as that crap takes up memory in your brain too.
  • me 2012-05-02 06:29
    I agree, when I were a lad we had to make our own '1's and '0's and we looked down on software developers who always broke the hardware and then cried when they couldn't use HUGE libraries.
  • Neil 2012-05-02 06:33
    Geoffrey T. Buchanan:
    Hmmmm:
    TheSi:
    You mean 'spelt'
    Please don't feed the trolls.

    Neither spelling of "spelled" or "spelt" is "incorrect". Yes, in the US, "spelt" is almost solely used for a type of wheat mainly grown in Europe but everyone with half a brain knows that the language used in the US only bears a passing resemblance to English.

    In "real" English, either form is acceptable and commonly used.
    Indeed and the same is true of the word learned/learnt, something I just had to look up for my previous comment.
    It's not the same.

    The spelled/spelt is mainly a geographical distinction, as spelt is traditionally the British spelling of the past tenses of spelled while spelled is traditionally the U.S. spelling.

    On the other hand learned/learnt is a grammatical distinction, as learned is traditionally the past participle while learnt is traditionally the simple past tense.

    Not to be confused with the word learnèd (here spelled poetically to indicate the adjective to avoid confusion).
  • RyanL 2012-05-02 08:39
    I am actually a big proponent for self-documenting code. I almost never use comments, and I will often have 2-3 line functions. However, this example takes it to the extreme, extracting out fully understandable code for no apparent reason.

    Example, the following code is more understandable to me in the later version.. which obviously states "If there are no activity types, return true":

    if (NoActivityTypesAreAttachedToThisEvent(activityTypes))
    return TrueBecauseThereAreNoActivityTypesToFilterOnThisEvent();

    if (!activityTypes.Any()) return true;

    By the way, refactoring this class took it from something like 170 lines of code to 40 lines of code. Which version do you think will be easier for a developer to digest? Extracting code is fine when it helps describe the intent. The code as written did little to help with my understanding and just created a huge wall of text in a class that should have been simple in the first place.
  • Matt Westwood 2012-05-02 10:05
    LANMind:
    Say what you will about long object names. I'm working with a database designed by a guy who grew up in an era when every fucking byte was precious. If he could still pack his number fields, he would. I've spent (not spended) a week trying to follow his cryptic mess, and I'm ready to kill someone.


    Du-uh.

    Long names are bad. Short names are bad. Therefore...? Yes, Ralph? "Please Missis Krabappel, that means ALL names are bad. I've wet my pants."
  • caper 2012-05-02 10:07
    > if (!activityTypes.Any()) return true;

    Argggg. The Any already returns a boolean.
  • RyanL 2012-05-02 10:30
    caper:
    > if (!activityTypes.Any()) return true;

    Argggg. The Any already returns a boolean.


    Yes but if it is false you want it to continue in the execution of the method, not return false.
  • Remy Martin 2012-05-02 10:37
    Bad news guys. It appears that Alex passed a couple of days ago. That's the only assumption I can make, since I know he's not so bone-ass lazy that he violates the name of the site (daily). I would contact his widow, but there's no way he could get laid let alone start a family.

    Sorry.
  • Some Damn Yank 2012-05-02 11:18
    Nickster:
    Engineering is a discipline few CS grads follow.


    So, in your opinion, could the principles of engineering be applied to the construction of software if they were taught and practiced?
    Yes.
  • Some Damn Yank 2012-05-02 11:32
    Rodd:
    Matt Westwood:
    You're doing it wrong. A phone number should be defined by a class in its own right with its own internal validation. If you're holding it as a string and banking on the class you're holding it in validating it, you've got it backarsewards.


    Obviously. And inside that class, you store a PhoneNumberDigitArray class containing 9 instances of the PhoneNumberDigit class.
    You're' all wrong. Assuming the US telephone system developed by TPC (The Phone Company, for those of you who somehow missed "The President's Analyst"), what the public refers to as a "phone number" is actually a concatenation of three numbers: the Area Code (3 digits), the Central Office (exchange) code (3 digits), and the Subscriber Number (four digits).

    So you need an AreaCode class, a CentralOffice class, and a SubscriberNumber class to go along with your PhoneNumberDigit class.
  • ILackedAles 2012-05-02 12:10
    minitech:
    The Great Neckbeardio:
    Geoffrey T. Buchanan:
    Back then 16kb was considered a LUXURY and we had to learn to write highly efficient and compact code so that it would PERFORM.


    You got to *write* your code? LUXURY! LUXURY! Back in MY day we had to chisel our code into stone tablets! Without our bare hands!


    You got to chisel your code? Paradise! Back in MY day, we had to erode our code out of the stone with precisely-placed water - when we had even that! I kilt many a developer to get the necessary blood when water was scarce.


    You were lucky. We worked for three months in a septic tank, making our own stones and water out of whatever we could find. We'd work 14 hours straight, and our manager used to thrash us to sleep with his belt when we wrote buggy code!
  • Your Name 2012-05-02 12:23
    gratuitous_arp:
    Your Name:
    KattMan:
    CAPTCHA:sino:

    Sorry that was an offtopic rant. Also I hate setter and getter functions that only consist of "this.value = value" or "return this.value". Anyone who creates a language where they are necessary is a dickweed arsehole.


    Look into encapsulation and the "law" of demeter and you will know why these simple get/set methiods exist. It's not the language that requires them, you can make your variables public, but then the thing that owns them has no control over when and how they are updated.


    No, this is an artifact of the languages you use, and you're so used to it that you can't imagine it any other way. Look at the way Python, for instance, implements "properties". You have a public variable, and then later, if you need access to that public variable to go through a method, you can change it to do that transparently to the code that uses that class doesn't need to change.


    As KattMan said, you can do the same thing in C++ using a public variable and later writing a get function for it if desired. People don't do this because it's bad design -- in any language -- for both of the reasons given by KattMan. As you know, in Python, there is an idiom to denote properties that should not be accessed directly by adding a leading underscore to the property's name. This access control "suggestion" is used to provide the private membership given by C++ (though not enforcing it) while retaining the language's flexibility. In PEP-8, Guido gives further examples of why this is a good idea. See: http://www.python.org/dev/peps/pep-0008/#designing-for-inheritance

    If you're writing small Python scripts it doesn't really matter (as long as you *know* they'll stay small). If you're writing large programs, it does matter.

    Only in C++ and the languages derived from it (e.g. Java) do you see everyone "defensively" creating getters and setters for everything right off the bat.


    You're talking about defensive programming, something that is hopefully common in code written in any language. Setters are just as important in Python as they are in C++ if you want any kind of assurance that anything valid is getting passed to your object. Getters hide implementation details. Other than taking some extra time to write, what specifically do you find undesirable about get/set functions?


    No, you're still not getting it.

    Look, in C++ or Java, you have a class and some information encapsulated in it.

    class foo
    {
    //...
    public:
    int bar;
    }

    Now, code uses this objects of this class and accesses the variable foo.bar directly. It's all good until you decide that accesses to foo.bar need to do something else -- maybe there's some internal counter you want to increment or you want to validate or log or you want to calculate bar on the fly or whatever. Now all the code that USES class foo needs to be rewritten to call foo.getBar() and foo.setBar(int newBar). After getting bitten by this once, from then on you always make all member variables private and waste time (both writing and compiling) and code size (both source and, if your optimizing compiler isn't sufficiently good, binary size) on getters and setters that might not actually be necessary (e.g. if in the lifespan of your project they never do anything but act as passthroughs for the private member variable, you did that work for nothing).

    In a language with properties (or whatever the feature ends up getting called), this changeover is transparent to the code using class foo. So, you start with a class, as before, with a public member variable.

    class foo:
    def __init__(self):
    self.bar = 0


    Other code accesses bar directly.


    obj = foo()
    obj.bar = 10


    Later, you change your mind and want foo.bar to go through a getter or whatever. So you implement it as a property in the foo class definition.


    class foo:
    def __init__(self):
    self._private_bar = 0
    def set_bar(self,bar):
    self._private_bar = 0
    #insert side effects here
    def get_bar(self):
    #insert side effects here
    return self._private_bar

    bar = property(set_bar, get_bar)


    That last line there is key. Now, the code USING the foo class, the stuff you already wrote, doesn't need to change. You don't even need to recompile it if all you have is the compiled bytecode! All those calls to directly access foo.bar are transparently converted into function calls to the property. (The syntax is ugly by Python standards but that still puts it head and shoulders above C++.) Because of this, you can have publicly accessible member variables and only write getters and setters when you actually need them, rather than write a bunch of pointless ones right off the bat just in case they become necessary later. (As a useful bonus, you can tell at a glance if some Python code you're looking at was written by someone who doesn't really know the language, because it will have trivial getters and setters everywhere.)

    Do you get it yet?
  • Your Name 2012-05-02 12:27
    ugh, I put the arguments to property() in the wrong order there. *facepalm* Whatever, you get the idea.
  • KattMan 2012-05-02 12:52
    Yes I get it, honestly I do, but you are makign an assumption I presum from the fact you have never written in DotNet.

    Properties in DotNet can be simply named Foo. VB.Net and C# allow properties to be named simply.

    public class Class1
    {
    private int _Foo;

    public int Foo
    {
    get
    {
    return _Foo;
    }
    set
    {
    }
    }

    If you started out with Foo as the variable you could refactor easily to _Foo and make the property simply Foo. This once again keeps the rest of your code safe. Yes this is derived from C++ but deviates far enough to make things sane.

    I still say that havign the setter is better in most cases, once again since _Foo is owned by class1, you should allow class1 to control access to it and be aware of when it changes. Essentially property setters are not automatically changing a variable, but rather requesting it to be changed, class 1 will allow it or not based off of business rules called from the setter.

    If this doesn't matter and they are just pass throughs, then sure, leave them off and make the variable public, but if you later need to validate the value before saving or processing, that is when you know you did it wrong, you should have used a setter and validated it when the change was requested.
  • Jay 2012-05-02 13:36
    clive:
    If you can't rename your function when you change what it does, you've got serious problems with your codebase or processes anyway.


    Well, if the function is only used within one project, and only used in standard ways, then at least some IDEs -- Eclipse, for example -- can make renaming it pretty easy. I've only used a handful of IDEs so I can't say if this is a common feature.

    In any case, if a function is used across many projects, e.g. it's part of library, then this might not be quite so simple: You'd have to identify every project that uses it and update all of them.

    If you use reflection to access functions, renaming it may not be trivial. Where does the system get the name from? A simple hard-coded string? An XML file? A database record? You'd have to investigate all these possibilities and more. Even if this particular function is never accessed via reflection, you would have to know that or be able to prove that.

    If it's part of a published API used by many people outside your organization, then changing a function name should be a step taken with extreme caution if you don't want to have lots of unhappy clients.
  • Jay 2012-05-02 13:40
    Re: Self Documenting:
    Rodd:
    Matt Westwood:
    You're doing it wrong. A phone number should be defined by a class in its own right with its own internal validation. If you're holding it as a string and banking on the class you're holding it in validating it, you've got it backarsewards.


    Obviously. And inside that class, you store a PhoneNumberDigitArray class containing 9 instances of the PhoneNumberDigit class.


    For north american phone numbers, ten instances would be more effective - but good point anyway.


    That's why the PhoneNumber class needs to be subclassed into AmericanPhoneNumber, BritishPhoneNumber, RussianPhoneNumber, etc.
  • Your Name 2012-05-02 13:44
    Look, if your setter function is nothing but "this.privatevar = argument;", it's not "controlling access". There's no checking, there's no validation and exception throwing and whatever. It's just pointless indirection. The only difference between that function and setting the variable directly is that if the compiler isn't smart enough, you end up with two jump instructions and maybe some register push/pop.

    As for your last paragraph there, that really doesn't make any sense. "If you need to change it later that's when you know you did it wrong"?. Well, by that logic any code you write, ever, means that you did something wrong previously.

    Look, write a getter/setter function when you actually need one. A language that requires trivial ones from the get-go just in case so you don't screw yourself over later is broken. And if the language doesn't require them, why the holy hell would you do it anyway?
  • Jay 2012-05-02 13:47
    I sure hope Alex posts something new soon, or we'll be stuck adding comments to this same thread indefinitely.
  • KattMan 2012-05-02 14:05
    [quote user="Your Name"]Look, if your setter function is nothing but "this.privatevar = argument;", it's not "controlling access". There's no checking, there's no validation and exception throwing and whatever. It's just pointless indirection. The only difference between that function and setting the variable directly is that if the compiler isn't smart enough, you end up with two jump instructions and maybe some register push/pop.

    As for your last paragraph there, that really doesn't make any sense. "If you need to change it later that's when you know you did it wrong"?. Well, by that logic any code you write, ever, means that you did something wrong previously.
    [quote]

    Wow, the idiots here really are showign thier face. If you are going to quote me get it right or shut the hell up.

    "If this doesn't matter and they are just pass throughs, then sure, leave them off and make the variable public, but if you later need to validate the value before saving or processing, that is when you know you did it wrong, you should have used a setter and validated it when the change was requested."

    It was sample code, and just like you said, I state right fuckign there that if the getter and setter is just a pass through then leave them off.
    Then I did NOT say if you have to change it later, I said if your code later needs to validate THAT is when you know you did it wrong, if you need to validate the value do so when it is set by USING A SETTER! Not sometime later when you already have a bad value, but at the time you pass it in, don't even let the bad value get there.

    The sample was also an argument for not always having a setter and getter, as it is trivial to rename your property access to the name of the variable, you don't need class1.setvar or class1.getvar, you just have class1.var, and that var can be either the variable itself or if later changed can be referencing the property setter and getter transparently.

    Jeesh, makes me wonder why I even post here any more, Fucking idiots.



    Addendum (2012-05-02 15:16):
    And yes, I was channeling my good adversay Morbs for this post. He taught me well it seems.
  • Alex Papadimoulis 2012-05-02 14:07
    Alex Papadumbass:
    Self Commenting


    That's American English. It is called Papadimoulis in British English.
  • Matt Westwood 2012-05-02 15:20
    Some Damn Yank:
    Rodd:
    Matt Westwood:
    You're doing it wrong. A phone number should be defined by a class in its own right with its own internal validation. If you're holding it as a string and banking on the class you're holding it in validating it, you've got it backarsewards.


    Obviously. And inside that class, you store a PhoneNumberDigitArray class containing 9 instances of the PhoneNumberDigit class.
    You're' all wrong. Assuming the US telephone system developed by TPC (The Phone Company, for those of you who somehow missed "The President's Analyst"), what the public refers to as a "phone number" is actually a concatenation of three numbers: the Area Code (3 digits), the Central Office (exchange) code (3 digits), and the Subscriber Number (four digits).

    So you need an AreaCode class, a CentralOffice class, and a SubscriberNumber class to go along with your PhoneNumberDigit class.


    Only if you've allowed a subclass of the PhoneNumber class to be AmericanPhoneNumber ... hang on, that can't be the correct approach - where's me gang-of-four, I feel a Pattern coming on ...
  • Some Damn Yank 2012-05-02 15:30
    Some Damn Yank:
    So you need an AreaCode class, a CentralOffice class, and a SubscriberNumber class to go along with your PhoneNumberDigit class.
    From a practical standpoint this actually isn't a bad idea. For example, no value in the AreaCode and CentralOffice classes should be of the form N11 as those are reserved for 411, 911, etc. Also, the allowable values in the AreaCode class are well-known, as new area codes are introduced in a controlled fashion by a central authority, much like state/province codes and zip/postal codes, so ideally you'd make the user select from a list, or at least validate what they type. Then there's the whole country code business, too, which is also a well-known fixed set, so if you're doing international phone numbers you need a CountryCode class.

    There's no reason for the PhoneNumber class to know how to validate all these parts. When you're looking at the PhoneNumber class you can easily see what it does without getting into the details of validating an area code, and if you want to see that you just look at the AreaCode class.
  • Some Damn Yank 2012-05-02 15:36
    Matt Westwood:
    Only if you've allowed a subclass of the PhoneNumber class to be AmericanPhoneNumber
    That's NorthAmericanPhoneNumber - per Wikipedia, the United States and its territories, Canada, Bermuda, and 17 nations of the Caribbean use that format.
  • Ello 2012-05-02 15:42
    ThisFunctionReturnsTrueIfInputParameterArgumentIsOneAndFalseIfInputParameterArgumentIsZero(int InputParameterArgument)
    {}
  • The Mr. T. Experience 2012-05-02 16:38
    Your mom had to call Maury because she was quite the gang-of-four whore. The worst thing is you still don't know who's your daddy, and you got to see four dudes dance a celebratory jig.
  • gratuitous_arp 2012-05-02 18:12
    Your Name:
    gratuitous_arp:
    Your Name:
    KattMan:
    CAPTCHA:sino:

    Sorry that was an offtopic rant. Also I hate setter and getter functions that only consist of "this.value = value" or "return this.value". Anyone who creates a language where they are necessary is a dickweed arsehole.


    Look into encapsulation and the "law" of demeter and you will know why these simple get/set methiods exist. It's not the language that requires them, you can make your variables public, but then the thing that owns them has no control over when and how they are updated.


    No, this is an artifact of the languages you use, and you're so used to it that you can't imagine it any other way. Look at the way Python, for instance, implements "properties". You have a public variable, and then later, if you need access to that public variable to go through a method, you can change it to do that transparently to the code that uses that class doesn't need to change.


    As KattMan said, you can do the same thing in C++ using a public variable and later writing a get function for it if desired. People don't do this because it's bad design -- in any language -- for both of the reasons given by KattMan. As you know, in Python, there is an idiom to denote properties that should not be accessed directly by adding a leading underscore to the property's name. This access control "suggestion" is used to provide the private membership given by C++ (though not enforcing it) while retaining the language's flexibility. In PEP-8, Guido gives further examples of why this is a good idea. See: http://www.python.org/dev/peps/pep-0008/#designing-for-inheritance

    If you're writing small Python scripts it doesn't really matter (as long as you *know* they'll stay small). If you're writing large programs, it does matter.

    Only in C++ and the languages derived from it (e.g. Java) do you see everyone "defensively" creating getters and setters for everything right off the bat.


    You're talking about defensive programming, something that is hopefully common in code written in any language. Setters are just as important in Python as they are in C++ if you want any kind of assurance that anything valid is getting passed to your object. Getters hide implementation details. Other than taking some extra time to write, what specifically do you find undesirable about get/set functions?


    No, you're still not getting it.

    Look, in C++ or Java, you have a class and some information encapsulated in it.

    class foo
    {
    //...
    public:
    int bar;
    }

    Now, code uses this objects of this class and accesses the variable foo.bar directly. It's all good until you decide that accesses to foo.bar need to do something else -- maybe there's some internal counter you want to increment or you want to validate or log or you want to calculate bar on the fly or whatever. Now all the code that USES class foo needs to be rewritten to call foo.getBar() and foo.setBar(int newBar). After getting bitten by this once, from then on you always make all member variables private and waste time (both writing and compiling) and code size (both source and, if your optimizing compiler isn't sufficiently good, binary size) on getters and setters that might not actually be necessary (e.g. if in the lifespan of your project they never do anything but act as passthroughs for the private member variable, you did that work for nothing).

    In a language with properties (or whatever the feature ends up getting called), this changeover is transparent to the code using class foo. So, you start with a class, as before, with a public member variable.

    class foo:
    def __init__(self):
    self.bar = 0


    Other code accesses bar directly.


    obj = foo()
    obj.bar = 10


    Later, you change your mind and want foo.bar to go through a getter or whatever. So you implement it as a property in the foo class definition.


    class foo:
    def __init__(self):
    self._private_bar = 0
    def set_bar(self,bar):
    self._private_bar = 0
    #insert side effects here
    def get_bar(self):
    #insert side effects here
    return self._private_bar

    bar = property(set_bar, get_bar)


    That last line there is key. Now, the code USING the foo class, the stuff you already wrote, doesn't need to change. You don't even need to recompile it if all you have is the compiled bytecode! All those calls to directly access foo.bar are transparently converted into function calls to the property. (The syntax is ugly by Python standards but that still puts it head and shoulders above C++.) Because of this, you can have publicly accessible member variables and only write getters and setters when you actually need them, rather than write a bunch of pointless ones right off the bat just in case they become necessary later. (As a useful bonus, you can tell at a glance if some Python code you're looking at was written by someone who doesn't really know the language, because it will have trivial getters and setters everywhere.)

    Do you get it yet?


    Ah, I thought you were using "properties" as a general description for class attributes -- I wasn't aware that Python had a property keyword. I still have a hard time understanding the disagreement expressed at having some unneeded but trivial get/set functions, and how this is worse than having code use multiple ways of accessing a member variable in the same way. The difference between obj.setVar() and obj.var isn't clear without looking through the class file. The "property" keyword seems like a get out of jail free card -- it shouldn't be part of the plan, but it's very handy when you need it.

    Maybe as I think about it more, I'll see the light that you see. In any case, thank you for taking the time to explain.
  • me 2012-05-03 04:02
    What is "frist", and which purpose did your post serve?
  • Sam 2012-05-03 05:25
    It scares me that I had to get half way down page two of the comments before reading a comment by someone with a brain.
  • eric 2012-05-03 06:46
    Perhaps he expected validation checking to be more complicated, but it didn't end up that way.
  • Hmmmm 2012-05-03 08:07
    eric:
    Perhaps he expected validation checking to be more complicated, but it didn't end up that way.

    I'm not sure if you meant to reply to my comment as I don't see the connection and I assume you haven't read all the comments yet but if you have then can you explain how the complexity of the required validation checking has any bearing on why he felt it necessary to write the bool wrapper functions when they are only used after an explicit, fairly well named, test, e.g.

    if (NoActivityTypesAreAttachedToThisEvent(activityTypes))
    return TrueBecauseThereAreNoActivityTypesToFilterOnThisEvent();

    The Because... stuff is implicit in the fact that it is being done as a result of the test.

    The only thing that could possibly induce me to change my opinion about this code is if the original author gave a different reason (and I would still find it very hard to believe).
  • clive 2012-05-03 08:30
    Jay:
    clive:
    If you can't rename your function when you change what it does, you've got serious problems with your codebase or processes anyway.


    Well, if the function is only used within one project, and only used in standard ways, then at least some IDEs -- Eclipse, for example -- can make renaming it pretty easy. I've only used a handful of IDEs so I can't say if this is a common feature.

    In any case, if a function is used across many projects, e.g. it's part of library, then this might not be quite so simple: You'd have to identify every project that uses it and update all of them.

    If you use reflection to access functions, renaming it may not be trivial. Where does the system get the name from? A simple hard-coded string? An XML file? A database record? You'd have to investigate all these possibilities and more. Even if this particular function is never accessed via reflection, you would have to know that or be able to prove that.

    If it's part of a published API used by many people outside your organization, then changing a function name should be a step taken with extreme caution if you don't want to have lots of unhappy clients.


    And in that case, changing what the function does so it no longer agrees with the name should also be done with a similar amount of caution.

    Adding some logging code to a "GetTransaction" method is fine, adding some validation is probably fine, and neither require a name change. If you're adding something which requires a name change, you're back in 'serious problems' territory.
  • Lurch 2012-05-03 12:24
    Re: Self Documenting
    2012-05-02 13:40 • by Jay

    Re: Self Documenting:

    Rodd:

    Matt Westwood:
    You're doing it wrong. A phone number should be defined by a class in its own right with its own internal validation. If you're holding it as a string and banking on the class you're holding it in validating it, you've got it backarsewards.



    Obviously. And inside that class, you store a PhoneNumberDigitArray class containing 9 instances of the PhoneNumberDigit class.



    For north american phone numbers, ten instances would be more effective - but good point anyway.



    That's why the PhoneNumber class needs to be subclassed into AmericanPhoneNumber, BritishPhoneNumber, RussianPhoneNumber, etc.


    ===========================

    NO NO NO

    What about Skype?

    You need a VoiceCommunicationsFactoryFactoryFactory returning an InternationalPhoneNumberFactoryFactory returning a PhoneNumberFactory, returning a PhoneNumber object.

    Yeah, that's a good start.
  • BillClintonIsTheMan 2012-05-03 13:02
    Three things could be at play here

    1) idiocy
    2) The developer thought the evaluations would need to be more than they actually turned out to be (Kind of YAGNI - see #1)
    3) There is some injected tracing/diagnostic code that gets put into the product at a later state. AOP or something like that.

    But its probably #1.
  • AY 2012-05-03 13:03
    What does a 50 characters identifier has to do with memory? Much less performance?

    Compiler theory indeed....
  • Joe 2012-05-03 18:26
    I believe it originated on Slashdot. At least, that's the first place *I* saw it, although there may have evolved elsewhere, or evolved multiple times in parallel.

    Whenever a new article would go up, some lamer would try to claim "First post!" in the comments section, without adding anything to the conversation. On Slashdot, I believe they started moving such comments randomly down the page, so the next step naturally was to mis-spell it, leading to "frist post" or "frost pist" or any other tortured locutions.

    On FARK, the phrase "first post" gets turned into "boobies", and "last post" gets turned into "wieners", if I recall correctly. Its filter was inspired by similar problems.
  • Joe 2012-05-03 18:30
    What does a 50 characters identifier has to do with memory? Much less performance?

    Compiler theory indeed....


    For interpreted code (remember BASIC?), it ate up your variable store. Depending on your flavor of BASIC, it could also lead to lower program speeds for variable lookup.

    For compiled languages, shorter variables and terser comments lead to smaller source files and therefore faster floppy disk access. (Remember those?) I'm always surprised how large my source files are, and then I remember I use spaces instead of tabs, have full-paragraph comments when needed, and write things out long-hand when it helps clarity.

    When I look at a floppy's worth of source code from 30 years ago, I think to myself "wow, that's terse." And then I realize "But if it were less terse, the source probably wouldn't have fit on that floppy alongside the executable."
  • Joe 2012-05-03 18:38
    The length of a variable name is a particularly silly thing to criticize on the basis of performance, as it will be tokenized almost immediately by the compiler or interpreter. The only machine resource it wastes is developers' disk space.


    That's true these days. There was a time not that long ago when such a loquacious program might not fit cleanly in the system memory, though, or would fill your floppy prematurely. I have written compiled programs on an Apple ][, where the computer had 128K and the floppy was only 140K.

    One valid criticism against such verbosity is that my ability to read and discriminate between strings falls off quickly with length. If faced with two long identifiers that differ only in one word in the middle, it's sometimes difficult to keep them straight.
  • Luiz Felipe 2012-05-03 21:19
    me:
    I remember when Engineers had to have degrees and built tangible things.

    But we build intagible things, that is the problem.
  • Kuba 2012-05-04 02:18
    Some Damn Yank:
    Some Damn Yank:
    So you need an AreaCode class, a CentralOffice class, and a SubscriberNumber class to go along with your PhoneNumberDigit class.
    From a practical standpoint this actually isn't a bad idea.
    And hey, it's a built-in time bomb, too. If the customer doesn't update, and new area codes get introduced: poof -- they can't handle customer phones in those.
  • Kuba 2012-05-04 02:45
    gratuitous_arp:
    Your Name:
    [...]
    Later, you change your mind and want foo.bar to go through a getter or whatever. So you implement it as a property in the foo class definition.


    class foo:
    def __init__(self):
    self._private_bar = 0
    def set_bar(self,bar):
    self._private_bar = 0
    #insert side effects here
    def get_bar(self):
    #insert side effects here
    return self._private_bar

    bar = property(set_bar, get_bar)


    That last line there is key. Now, the code USING the foo class, the stuff you already wrote, doesn't need to change. You don't even need to recompile it if all you have is the compiled bytecode! All those calls to directly access foo.bar are transparently converted into function calls to the property. (The syntax is ugly by Python standards but that still puts it head and shoulders above C++.) Because of this, you can have publicly accessible member variables and only write getters and setters when you actually need them, rather than write a bunch of pointless ones right off the bat just in case they become necessary later. (As a useful bonus, you can tell at a glance if some Python code you're looking at was written by someone who doesn't really know the language, because it will have trivial getters and setters everywhere.)

    Do you get it yet?
    Ah, I thought you were using "properties" as a general description for class attributes -- I wasn't aware that Python had a property keyword.
    I think you still don't get it, though! Python properties are completely generic attributes of a class, so you thought right and it doesn't make the property system somehow impossible, not at all. All that is special about the properties is that they are bound to an interesting object. The property "keyword" is a plain old built-in library function. It returns a customized property object, that's all. Said object has getter, setter and deleter methods that invoke the relevant functions passed as arguments in the property() call. AFAIK you can write your own reimplementation of the built-in property(), there's nothing magic about it.

    Python has a few fairly powerful mechanisms like that. Another interesting one is the decorator system. A decoration is just you telling the compiler to pass the decorated function as an argument to a decorator, and binding the return value of such a call to the decorated name. A decorator is just a function, only that it expects a callable object (say, a function) as an argument, and should return a yet another callable object. The latter can wrap the invocation of the former in some clever way -- say, by building up a property object. This is why property getters/setters/deleters can be just as well declared by using decorators.

    Here's a pretty example from StackOverflow:
    def makebold(fn):
    
    def wrapped():
    return "<b>" + fn() + "</b>"
    return wrapped

    def makeitalic(fn):
    def wrapped():
    return "<i>" + fn() + "</i>"
    return wrapped

    @makebold
    @makeitalic
    def hello():
    return "hello world"

    print hello() ## returns <b><i>hello world</i></b>

  • Watson 2012-05-04 06:17
    Kuba:
    A decorator is just a function, only that it expects a callable object (say, a function) as an argument, and should return a yet another callable object.

    Callable objects? Passing functions as arguments and return values?! WHAT MANNER OF SORCERY IS THIS?!!
  • tox 2012-05-04 07:30
    Geoffrey T. Buchanan:
    That 50 character length function name is surely a sign of the times. I learned my craft back in the day when software engineering was a serious discipline, before the kids turned up with their IPad/Facebook/Web2.0 bullshit.

    Back then 16kb was considered a LUXURY and we had to learn to write highly efficient and compact code so that it would PERFORM. Well I am sure you've all heard this before and I don't want to bang on about some "golden age" - it wasn't perfect I am not saying that. It's just that an engineer who wasted programme memory so frivolously creating a 50 character identifier back then would have been fired on the spot.

    I suppose modern businesses tolerate the complete waste of resources today because computers have got more powerful and the customer rarely complains. But you have to wonder how much faster typical software would run if it was written as per the old ways. There's also a slippery slope in play - out there now are a load of upstart "programmers" who are making all the software we use but they have no idea about how computers work let alone basic compiler theory. And people wonder why there are so many security holes and viruses in software these days...

    /rant



    What have identifiers to do with performance.
  • tox 2012-05-04 07:32
    tox:
    Geoffrey T. Buchanan:
    That 50 character length function name is surely a sign of the times. I learned my craft back in the day when software engineering was a serious discipline, before the kids turned up with their IPad/Facebook/Web2.0 bullshit.

    Back then 16kb was considered a LUXURY and we had to learn to write highly efficient and compact code so that it would PERFORM. Well I am sure you've all heard this before and I don't want to bang on about some "golden age" - it wasn't perfect I am not saying that. It's just that an engineer who wasted programme memory so frivolously creating a 50 character identifier back then would have been fired on the spot.

    I suppose modern businesses tolerate the complete waste of resources today because computers have got more powerful and the customer rarely complains. But you have to wonder how much faster typical software would run if it was written as per the old ways. There's also a slippery slope in play - out there now are a load of upstart "programmers" who are making all the software we use but they have no idea about how computers work let alone basic compiler theory. And people wonder why there are so many security holes and viruses in software these days...

    /rant



    What have identifiers to do with performance.



    Don't feed the trolls. He's a Web 2.0/Facebook/iPad kid imposing a Real Programmer who uses Real Compilers.
  • no laughing matter 2012-05-04 09:14
    Joe:
    What does a 50 characters identifier has to do with memory? Much less performance?

    Compiler theory indeed....

    For compiled languages, shorter variables and terser comments lead to smaller source files and therefore faster floppy disk access.

    Actually quite a lot of the modern compiled languages (Java, C#, to name the most popular) provide a feature called Reflection that allows to access attributes and methods of an object by name.

    To be able to do this, the names of the attributes and methods must be present in the runtime environment - the compiler will not erase them!

    You can use byte code obfuscators to replace your long identifiers with shorter ones, but reflection will not work for the obfuscated code.
  • Jack 2012-05-04 16:30
    bling blong blang, this isn't spam...

    TheOnlyProblemWithThisIsThatAfterThreeToFourWordsTheReadabilityOfAMethodIsCompletelyDestroyedOhAndReturnTrue();
  • me 2012-05-04 23:50
    Looks like COBOL to me!!
  • pressureman 2012-05-05 04:10
    CAPTCHA:sino:
    Then you try to get an MD5 hash in Python and you have to do this:


    m = hashlib.md5()
    m.update("mahstring")
    hash = m.hexdigest();


    Hey! Since MD5 is a function (string -> hash), why not make it, you know, a function! (yes you can do it in one line but that's not the point)


    Most languages implement message digests (and crypto functions) like this, because they're designed to be fed input in chunks. Consider generating a hash of a 4.7GB DVD ISO. Do you want to feed all 4.7GB at once to your hash function?
  • LeChuck 2012-05-11 06:55
    return "Fail";
  • Andrew 2012-05-13 21:14
    The rule to always encapsulate your field is there because there is a need to change without propagating to client, and the rule is there unchanged.

    In C++, if you exposed a field, and then some client depended on it, there is no way you can change that to a property without touching client code. So you better write the accessor methods.

    In C#, with the property keyword, make life easier. When code is changed from a field to a property, client code does not need to change, but they need to be re-compiled. To make life easier, it is better to expose as property to begin with.

    In Python, it is possible now. No code change, no recompile.

    Still, the rule doesn't quite change. We should always encapsulate the field to make it possible to change, it is just that the authoring needed to accomplish this changed.

    The key is to keep the capability to add logic at field access.
  • A. Nonymous Coward 2012-05-15 14:51
    KattMan:
    Matt Westwood:

    You're doing it wrong. A phone number should be defined by a class in its own right with its own internal validation. If you're holding it as a string and banking on the class you're holding it in validating it, you've got it backarsewards.


    Wow, did you even read what I said then read what you said? Can you even get the concept in your head without forgetting some other rudimentary thought?
    Let's hope you don't forget how to wipe your own nose when I say it this way.
    Yes you have a phone number class, but you need to set the value in it somewhere, and that is where you validate. You essentially just said what I did, because the setter you use to get your phone number into your phone number class is where you should have your validation call, not someplace later in the class, this is part of what setters are for! Validate when it comes in, not sit on it and maybe validate later.


    You're both doing it wrong. Anyone who creates a class for a phone number should stick to astronaut architecting at home, and stay away from production code.
  • Gedhead 2012-05-15 19:26
    Your Name:
    Botia:
    I remember when methods were verbs.

    I remember when programmers were engineers.


    I remember when engineers built bridges, and programmers wrote code.
  • comment'appelle tu 2012-06-20 13:16
    I was always told not to rely on remembering, but to use comments.
    "I'm going to get some tea now."