Comment On Self Documenting

"A little while back, someone introduced the concept of 'self-documenting' code to our team," writes Ryan L. "It was certainly a step forward, but it's somehow taken us two steps backwards. Consider, for example, the following code from an MVC controller." [expand full text]
« PrevPage 1 | Page 2 | Page 3 | Page 4Next »

Re: Self Documenting

2012-05-01 09:35 • by Matt Westwood
380186 in reply to 380110
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?

Re: Self Documenting

2012-05-01 09:43 • by Matt Westwood
380187 in reply to 380184
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."

Re: Self Documenting

2012-05-01 09:47 • by Matt Westwood
380188 in reply to 380132
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.

Re: Self Documenting

2012-05-01 09:58 • by TheSi (unregistered)
380189 in reply to 380186
It wasn't a troll, it was a wind-up, although I was a bit drunk and bored when I said it.

Re: Self Documenting

2012-05-01 10:06 • by Rootbeer
380190 in reply to 380094
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.

Re: Self Documenting

2012-05-01 10:16 • by clive (unregistered)
380191 in reply to 380175
[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)

Re: Self Documenting

2012-05-01 10:18 • by Anon (unregistered)
380192 in reply to 380158
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.

Re: Self Documenting

2012-05-01 10:31 • by KattMan
380193 in reply to 380188
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.

Re: Self Documenting

2012-05-01 11:35 • by Rodd (unregistered)
380194 in reply to 380188
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 • by Re: Self Documenting (unregistered)
380195 in reply to 380194
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.

Re: Self Documenting

2012-05-01 12:29 • by Matt Westwood
380196 in reply to 380191
[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

Re: Self Documenting

2012-05-01 12:35 • by Gibbon1 (unregistered)
380198 in reply to 380193
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.

Re: Self Documenting

2012-05-01 12:43 • by AGray (unregistered)
380199 in reply to 380100
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...

Re: Self Documenting

2012-05-01 12:47 • by It's a Cock! It's a Fist! It's Zoonerman! (unregistered)
380201 in reply to 380198
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...

Re: Self Documenting

2012-05-01 13:09 • by caper (unregistered)
> return ModelState.IsValid == false;

Argggg. Stop comparing booleans to booleans for simple answers.

Re: Self Documenting

2012-05-01 13:25 • by dkf
380203 in reply to 380192
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…

Re: Self Documenting

2012-05-01 13:54 • by Nickster (unregistered)
380204 in reply to 380203
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!

Re: Self Documenting

2012-05-01 14:16 • by AN AMAZING CODER (unregistered)
380205 in reply to 380133
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.

Re: Self Documenting

2012-05-01 14:39 • by 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;
}

Re: Self Documenting

2012-05-01 15:42 • by Darkstar (unregistered)
380207 in reply to 380104
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 • by Re: Self Documenting (unregistered)
380208 in reply to 380198
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).

Re: Self Documenting

2012-05-01 16:33 • by Coyne
Probably the ultimate slam that can be made: "It looks like COBOL."

Re: Self Documenting

2012-05-01 19:02 • by oheso
380213 in reply to 380184
radarbob:
I understand 'zactly what that calculation is about!!


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

Re: Self Documenting

2012-05-01 20:03 • by mmmmmH (unregistered)
380214 in reply to 380093
>Please don't feed the trolls.

>Trolling.

Go away creep.

Re: Self Documenting

2012-05-01 20:52 • by gratuitous_arp (unregistered)
380216 in reply to 380133
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?

Re: Self Documenting

2012-05-02 00:56 • by 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.

Rong Twiec

2012-05-02 01:19 • by Robert White (unregistered)
380218 in reply to 380112
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...

Re: Self Documenting

2012-05-02 02:07 • by L. (unregistered)
380219 in reply to 380115
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.

Re: Self Documenting

2012-05-02 02:14 • by L. (unregistered)
380220 in reply to 380120
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.

Re: Self Documenting

2012-05-02 02:20 • by L. (unregistered)
380222 in reply to 380147
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.

Re: Self Documenting

2012-05-02 02:35 • by L. (unregistered)
380223 in reply to 380190
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.

Re: Self Documenting

2012-05-02 06:29 • by me (unregistered)
380227 in reply to 380094
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.

Re: Self Documenting

2012-05-02 06:33 • by Neil (unregistered)
380228 in reply to 380095
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).

Re: Self Documenting

2012-05-02 08:39 • by 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.

Re: Self Documenting

2012-05-02 10:05 • by Matt Westwood
380239 in reply to 380147
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."

Re: Self Documenting

2012-05-02 10:07 • by caper (unregistered)
> if (!activityTypes.Any()) return true;

Argggg. The Any already returns a boolean.

Re: Self Documenting

2012-05-02 10:30 • by RyanL (unregistered)
380242 in reply to 380240
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.

Re: Self Documenting

2012-05-02 10:37 • by 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.

Re: Self Documenting

2012-05-02 11:18 • by Some Damn Yank (unregistered)
380244 in reply to 380159
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.

Re: Self Documenting

2012-05-02 11:32 • by Some Damn Yank (unregistered)
380245 in reply to 380194
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.

Re: Self Documenting

2012-05-02 12:10 • by ILackedAles (unregistered)
380246 in reply to 380162
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!

Re: Self Documenting

2012-05-02 12:23 • by Your Name (unregistered)
380247 in reply to 380216
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?

Re: Self Documenting

2012-05-02 12:27 • by Your Name (unregistered)
380248 in reply to 380247
ugh, I put the arguments to property() in the wrong order there. *facepalm* Whatever, you get the idea.

Re: Self Documenting

2012-05-02 12:52 • by KattMan
380249 in reply to 380248
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.

Re: Self Documenting

2012-05-02 13:36 • by Jay (unregistered)
380250 in reply to 380164
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.

Re: Self Documenting

2012-05-02 13:40 • by Jay (unregistered)
380251 in reply to 380195
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.

Re: Self Documenting

2012-05-02 13:44 • by Your Name (unregistered)
380252 in reply to 380249
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?

Re: Self Documenting

2012-05-02 13:47 • by Jay (unregistered)
I sure hope Alex posts something new soon, or we'll be stuck adding comments to this same thread indefinitely.

Re: Self Documenting

2012-05-02 14:05 • by KattMan
380254 in reply to 380252
[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.

Re: Self Documenting

2012-05-02 14:07 • by Alex Papadimoulis (unregistered)
380255 in reply to 380092
Alex Papadumbass:
Self Commenting


That's American English. It is called Papadimoulis in British English.
« PrevPage 1 | Page 2 | Page 3 | Page 4Next »

Add Comment