• (cs) in reply to Anon
    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?

  • (cs) in reply to radarbob
    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."

  • (cs) in reply to KattMan
    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 (unregistered) in reply to Matt Westwood

    It wasn't a troll, it was a wind-up, although I was a bit drunk and bored when I said it.

  • (cs) in reply to Geoffrey T. Buchanan
    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 (unregistered) in reply to Claxon

    [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 (unregistered) in reply to Some Damn Yank
    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.

  • (cs) in reply to Matt Westwood
    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 (unregistered) in reply to Matt Westwood
    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 (unregistered) in reply to Rodd
    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.

  • (cs) in reply to clive

    [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 (unregistered) in reply to KattMan
    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 (unregistered) in reply to Mikerad

    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! (unregistered) in reply to Gibbon1
    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 (unregistered)

    return ModelState.IsValid == false;

    Argggg. Stop comparing booleans to booleans for simple answers.

  • (cs) in reply to Anon
    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 (unregistered) in reply to dkf
    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 (unregistered) in reply to Your Name
    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 (unregistered)

    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 (unregistered) in reply to Nickster
    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 (unregistered) in reply to Gibbon1
    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).

  • (cs)

    Probably the ultimate slam that can be made: "It looks like COBOL."

  • (cs) in reply to radarbob
    radarbob:
    I understand 'zactly what that calculation is about!!

    Actually, you're assuming the reader knows the COBOL rules of operator precedence there.

  • mmmmmH (unregistered) in reply to Hmmmm

    Please don't feed the trolls.

    Trolling.

    Go away creep.

  • gratuitous_arp (unregistered) in reply to Your Name
    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 (unregistered)

    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 (unregistered) in reply to CAPTCHA:sino

    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. (unregistered) in reply to mrfr0g
    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. (unregistered) in reply to tundog
    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. (unregistered) in reply to LANMind
    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. (unregistered) in reply to Rootbeer
    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 (unregistered) in reply to Geoffrey T. Buchanan

    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 (unregistered) in reply to Geoffrey T. Buchanan
    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 (unregistered)

    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.

  • (cs) in reply to LANMind
    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 (unregistered)

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

    Argggg. The Any already returns a boolean.

  • RyanL (unregistered) in reply to caper
    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 (unregistered)

    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 (unregistered) in reply to Nickster
    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 (unregistered) in reply to Rodd
    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 (unregistered) in reply to minitech
    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 (unregistered) in reply to gratuitous_arp
    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 (unregistered) in reply to Your Name

    ugh, I put the arguments to property() in the wrong order there. facepalm Whatever, you get the idea.

  • (cs) in reply to Your Name

    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 (unregistered) in reply to clive
    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 (unregistered) in reply to Re: Self Documenting
    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 (unregistered) in reply to KattMan

    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 (unregistered)

    I sure hope Alex posts something new soon, or we'll be stuck adding comments to this same thread indefinitely.

  • (cs) in reply to Your Name

    [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 (unregistered) in reply to Alex Papadumbass
    Alex Papadumbass:
    Self Commenting

    That's American English. It is called Papadimoulis in British English.

Leave a comment on “Self Documenting”

Log In or post as a guest

Replying to comment #:

« Return to Article