Outliving The Great Variable Shortage 41

Posted by tottinger Tue, 27 Feb 2007 05:07:00 GMT

One of the more annoying problems in code, confounding readability and maintainability, frustrating test-writing, is that of the multidomain variable.

I suppose somebody forgot to clue me in to the Great Variable Shortage that is coming. I have seen people recycling variables to mean different things at different times in the program or different states of the containing object. I’ve witnessed magic negative values in variables that normally would contain a count (sometimes as indicators that there is no count, much as a NULL/nil/None would). I might be willing to tolerate this in programming languages where a null value is not present.

Yet I have seen some code spring from multidomain variables that made the code rather less than obvious. I think that it can be a much worse problem than tuple madness.

I have a rule that I stand by in OO and in database design, and that is that a variable should have a single, reasonable domain. It is either a flag or a counter. It is either an indicator or a measurement. It is never both, depending on the state of something else.

It is sort of like applying Curly’s law (Single Responsibility Principle) to variables. A variable should mean one thing, and one thing only. It should not mean one thing in one circumstance, and carry a different value from a different domain some other time. It should not mean two things at once. It must not be both a floor polish and a dessert topping. It should mean One Thing, and should mean it all of the time.

Surely I’ll take a shot from someone citing the value of a reduced footprint, and I won’t argue very long about the value of usinge only as much memory as you must. In C++ I was a happy advocate of bitfields. I haven’t been overly vocal about using various data-packing schemes, but I think that it can be a reasonable choice for compressing many values into a smaller space, but I will maintain that multipurpose variables are a bad idea, and will damage the readability of any body of code.

I suggest, in the case of constrained footprint where there truly is a Great Variable Shortage (GVS) that if (and that’s a big if) the author absolutely MUST repurpose variables on the fly that it is the lot of that programmer to make sure that users of the class/struct never have to know that it is being done. Never. Including those writing unit tests. The class will have to keep data-packing and variable-repurposing as a dirty secret.

Perhaps a strong statement or two in rule-form should be made here:

  1. A variable should have a SINGLE DOMAIN.
  2. One must NEVER GET CAUGHT repurposing a variable.

We don’t have to make do with the smallest number of variable names possible. Try to learn to live in plenty: use all the variables you want. For the sake of readability, consider having a single purpose for every variable not only at a given point in time, but for the entire program you’re writing.

Trackbacks

Use the following link to trackback from your own site:
http://blog.objectmentor.com/articles/trackback/275

Comments

Leave a response

  1. Avatar
    nullness about 2 hours later:

    “I might be willing to tolerate this in programming languages where a null value is not present.” You seem to imply that using null value is a acceptable thing. How does null differ from your overall conclusion? Namely, null has a different purpose than the value normally bound to the variable name. IMO there should be no null. Use e.g. dataflow variables. (single -store model), or f.ex. tuple (Boolean, A), or even better, a record (isSet: Boolean, value: A).

  2. Avatar
    Nullness about 10 hours later:

    If you squint at null just right. :-) It is acceptable partly because we are in the habit of accepting it. At least “no answer exists” is a fact about the counter.

    But imagine a variable “width” in an “image” class, and that a positive number is really the width of an image, but a negative number is the error code received with a loader routine attempted to read the image from a file. I think that’s a whole new level of “bad”.

    In the pysweeper example (a game I still can’t win, by the way) there is a tuple which has two multi-domain values. One is either the presence of a mine or else the number of adjacent mines, or a value of 2 meaning that it is neither a mine nor has the number of mines been counted. The second half of the two-tuple tells whether the cell has been opened or not also whether it has been flagged. Having a two-tuple acting effectively as a four-tuple is confusing. It took me a while to work out the meanings of the various values from the code. Once I surrounded the two-tuple with named methods (so that the code using the tuples is not comparing to magic numbers) it was easy enough to switch to a four-tuple with distinct facts. Of course, I picked the old Pysweeper program because it is hard to read. :)

    The mixture of a two-tuple (no meaningful names for elements) and multi-domain variables made Pysweeper a tasty puzzle to solve in my spare time. The same kind of thing in a production program would have made me quite angry.

    While I agree with you that the typical null implementation is multi-domained (again, squinting just right) I personally can’t even make a fair comparison between the minor annoyance of a “magic null value” and the horror of repurposed variables.

    Thanks for bringing it up, though. We should sniff at our traditions from time to time, in hopes something much better can be created.

  3. Avatar
    YAChris about 11 hours later:

    We don’t have to make due

    Wearing my “language nazi” hat here, but it’s “make do”. Please, let’s not make this another “lose/loose” flagrant internet misspelling.

  4. Avatar
    John 1 day later:

    A variable should always have a variable from its SINGLE DOMAIN.

    s/have a variable/have a value/?

    By the way – agreed.

  5. Avatar
    Tim 1 day later:

    Correction made. I don’t have anything sem-humorous to add to the mistake. Many eyes make all blogs shallow?

    Thank you for the catch.

  6. Avatar
    djoubert.co.uk 5 days later:

    David,

    Well I totally agree with you, it can become very frustrating in perl to check whether the user has actually given input as ‘0’, 0 and ’ ’ all evaluate to false.

    PHP solves it nicely with a leteral check $value === false will only return true if the $value is explicity been set to false.

  7. Avatar
    Jason 5 days later:

    This page is nearly impossible to read due to the font size.

  8. Avatar
    Tim 5 days later:

    Re: null, zero, false, empty, etc:

    I was raised in C. In C it was considered very poor form to compare anything to “true” (1), because there are so many ‘true’ values, and relatively few ‘false’ values. We would even go so far as to define a macro (if you’ll forgive my reaching into ancient memory):
         #define IS_TRUE(x)   (!(!(x))
    

    In C++ we ultimately got a boolean type that could be compared to true or false, but I was already trained not to compare v. true.

    Does it bother me? Yeah, but I forgot that it bothered me, having not messed with it in a while.

    By the way, Python gives you an unusually wide range of ‘false’ values, and I am always a little iffy about using it. I try to be careful and precise. It’s a funny game. After all, how hard is it (really) to create a boolean type with two possible values? You wouldn’t think it would take years of language evolution to get to this point.

  9. Avatar
    mgsloan 5 days later:

    Take a look at the hindley milner type system. It’s got your requirement of having a specific domain down, yet disagrees with your multiple kinds judgement. I suppose that repurposing and able to take on multiple forms may not be exactly the same thing, yet one type, one variable, may hold entirely different data. And we’re talking about one of the most exactingly defined and implemented type systems.

    Basically every type’s domain is a sum and product of other types. You seem to agree with the product part, yet disagree with the sum part. Then again, this is likely an attack more on dynamically typed languages, in which case functional programming is fairly well behind you.

    One thing that languages often lack is a concise, well specified generics system. In haskell, it’s called type parameters. This allows for constructing new types by composing types together. For example, the Maybe T type-constructor has a domain of Just T and Nothing, basically adding one value to T’s domain to construct Maybe T. This very nicely encapsulates the concept of Null used in other languages.

    Tim writes:Thanks for the H/M type system pointer. I’m digging in. And no, I tend not to attack any dynamically typed languages, as I have a strong preference for strongly, dynamically-typed languages like Python. I should get to know more of them.

  10. Avatar
    nullness 5 days later:

    Agreed with mgsloan. Another language that has those properties is Scala. Maybe is equivalent to Option[T], which is either Some[T](value) or None. You can then use pattern matching to branch based on the value. Scala has also novel component construction mechanism with abstract type members, traits, explicit self-type annotations and mixin composition ;).

  11. Avatar
    JJM 5 days later:

    I’ve recently come to like it when empty arrays, tuples and strings evaluate to false. Most of the times it doesn’t matter whether a function was passed an empty array, an empty tuple or a null/none/nil value.

    This is especially true in horrendous languages like PHP which have functions that can return multiple types of results, like NULL when NULL was passed into the function, False when it can’t handle the inputs and an int if the function was successful….

  12. Avatar
    Tony Morris 6 days later:

    “A variable should have a SINGLE DOMAIN.”—Well, the very notion of a “single domain” is a projected perspective. Nevertheless, the correction is, “A variable should not exist”, since change is an illusion provided by a dimensional axis affectionately referred to as ‘time’.

    Quite a few red herrings in this post (blub?) which begs the question, ever used a pure functional language? No variables there; bring on the Great Variable Shortage!!

    Tim writes:Indeed, I have not tried pure functional languages. Most of my (limited) functional exposure comes from python’s functional features. I am interested in learning to work that way, when it makes it up may “next thing to learn” list. Thanks!

  13. Avatar
    George Dinwiddie 8 days later:

    WRT: “I suggest, in the case of constrained footprint where there truly is a Great Variable Shortage (GVS) that if (and that’s a big if) the author absolutely MUST repurpose variables on the fly that it is the lot of that programmer to make sure that users of the class/struct never have to know that it is being done. Never. Including those writing unit tests. The class will have to keep data-packing and variable-repurposing as a dirty secret.”

    Actually, the compiler should do the repurposing for you, and you shouldn’t worry about the number of names in the symbol table. It’s been a long time since I last looked at compiler output, but compilers (since the late 1980’s, anyway) are very clever about figuring out the lifetimes of variables and re-using the space. I found back then that compilers could optimize much better than I could, and I could luxuriate in readable code.

  14. Avatar
    Tim 8 days later:

    Well, it is convenient in Python that {} and [] are also false values, but hardly satisfactory to me. It lacks a delicious explicitness. Let’s put it to bed, because it was hardly my main point.

    My main point is that the magic values should not change the meaning of the variable. This is the thing I’ve been seeing that lead to the rant, and on that I feel very confident.

    If there are going to be variables, each should be a fact and the semantic of the fact should be stable and reflected in the name. I think that “eitherNameOrDateOfBirthForNonResidents” would make a particularly crappy variable name, and a sign of sloppy thinking.

  15. Avatar
    M2TS File Converter over 3 years later:

    it is really good ,you can have a try

  16. Avatar
    hublot replicas over 4 years later:

    her survival and recovery.”The replica tag heuer carrera recovery.”The fact that the bullet left the breitling bentley motors replica the brain—less tissue damage is breitling crosswind watches is expected.

  17. Avatar
    cold room over 4 years later:

    This article is very usefull for me! I can see that you are putting a lots of efforts into your blog. I will keep watching in your blog, thanks.

  18. Avatar
    Criminal Records over 4 years later:

    One thing that languages often lack is a concise, well specified generics system. In haskell, it’s called type parameters. This allows for constructing new types by composing types together.

  19. Avatar
    Tenant Screening over 4 years later:

    A variable should mean one thing, and one thing only. It should not mean one thing in one circumstance, and carry a different value from a different domain some other time.

  20. Avatar
    okey oyunu oyna over 4 years later:

    it is very useful. Thanks for sharing it

    Tüm dunyadaki okey oyunculari ile ayni platform içerisinde sohbet ederek canli okey oyunu oyna ve ve internette online oyun oynamanin zevkini çikar.

  21. Avatar
    Dessert Recipes over 4 years later:

    A floor polish as a dessert topping does not sound appetising…

    I liked nullness’ pysweeper example. Very apt! It seems when it comes to variables your rules probably make a lot of sense for best practice.

  22. Avatar
    Dessert Recipes over 4 years later:

    Forgot to say Curlys Law is a good principle to follow!!

  23. Avatar
    beats by dre store over 4 years later:

    ’ pysweeper example. Very apt! It seems when it comes to variables your rules probably make a lot of sense for best practice.

  24. Avatar
    beats by dre store over 4 years later:

    ’ pysweeper example. Very apt! It seems when it comes to variables your rules probably make a lot of sense for best practice.high quality headphones new design headphones

  25. Avatar
    Diablo3 over 5 years later:

    it needs a bokmark so i can come back to it later ,nice stuff

  26. Avatar
    Beats By Dre UK over 5 years later:

    Good video based on an awesome article. But why is Robot Framework “wrong” tool for this kind of testing? It even seems to me that FitNesse scenario tables are copied from RF user keyword concept.

  27. Avatar
    Casque beats over 5 years later:

    yeah ratata, the war on bamboo is definitely much more serious business. So keep on fighting on bamboo, yeah!

  28. Avatar
    christian louboutin over 5 years later:

    The professional design make you foot more comfortable. Even more tantalizing,this pattern make your legs look as long as you can,it will make you looked more attractive.Moveover,it has reasonable price.If you are a popular woman,do not miss it.

    Technical details of Christian Louboutin Velours Scrunch Suede Boots Coffee:

    Color: Coffee
    Material: Suede
    4(100mm) heel
    Signature red sole x

    Fashion, delicate, luxurious Christian louboutins shoes on sale, one of its series is Christian Louboutin Tall Boots, is urbanism collocation. This Christian louboutins shoes design makes people new and refreshing. Red soles shoes is personality, your charm will be wonderful performance.

  29. Avatar
    Cheap Beats By Dre over 5 years later:

    A university studentbeats by dr dre caught by the enemy, the enemy tied him at the poles,just beats solo headphones purple and then asked him: say, where are you? You do not say it electrocuted! Scheap dr.dre beats studio headphones balck/yellowtudents back to the enemy a word, the result was electrocuted, he said: I am TVU.Hot sale beats by dr dre pro headphones

  30. Avatar
    sallyerma over 5 years later:

    I am happy to find so many useful information about Boat Speed here in the post, a good player can change the situation using these tips, thanks for sharing layered hairstyles

  31. Avatar
    iPhone contacts backup over 5 years later:

    Make sure that you can have a backup of iPhone and you can restore to it when necessary.

  32. Avatar
    This is excellent post<a href="http://www.cheap-monsterbeatsbydrdre.co.uk/">Cheap Beats By Dre</a> <a href="http://www.cheap-monsterbeatsbydrdre.co.uk/">Dr Dre Headphones</a> <a href="http://www.cheap-monsterbeatsbydrdre.co.uk/">Cheap Monster Beats Headph over 5 years later:

    This is excellent postCheap Beats By Dre Dr Dre Headphones Cheap Monster Beats Headphones Beats By Dr Dre Cheap Monster Dr Dre Beats Headphones Monster Beats Pro Headphones Cheap Monster Beats Solo Monster Dr Dre Beats Solo HD Headphones Justbeats Solo Headphones Monster Beats By Dr Dre In Ear Headphones beats by dre beats by dre australia beats by dre outlet dre beats Beats By Dre Studio Headphones Discount Beats By Dr Dre Pro Discount Beats By Dre Solo Discount Beats By Dre Solo HD Monster Beats By Dre Discount Beats By Dre Beats By Dre Headphones dr dre headphones beats by dre uk Discount Beats by dr dre pro Dicount Beats By Dr Dre Studio Beats By Dr Dre Solo Beats By Dr Dre Solo HD headphones Dr Dre Justbeats headphones beats by dre headphones beats by dre canada beats headphones dr dre canada outlet Monster Beats by Dr Dre headphones Beats By Dr Dre Pro heaphones Beats By Dr Dre Studio headphones Beats By Dr Dre solo headphones Monster Beats By Dr Dre solo HD Monster Beats by Dr Dre headphones Auriculares Beats Beats by Dre Dr Dre Beats Auriculares Monster Beats Monster Beats by Dr Dre Studio Monster Beats by Dr Dre Pro Monster Beats by Dr Dre Solo Monster Beats by Dr Dre Solo HD Beats By Dr Dre Dr Dre Kopfhörer Beats By Dre Kopfhörer Monster Beats Kopfhörer justbeats Kopfhörer beats studio Kopfhörer beats pro Kopfhörer Monster Beats By Dr Dre pro Kopfhörer monster beats solo Monster Beats By Dr Dre solo Kopfhörer monster beats solo hd beats solo hd Kopfhörer Beats By Dre Cheap Monster Beats Beats Headphones Cheap Dre Beats Dr Dre Outlet Monster Beats By Dre Studio Monster Beats By Dre Pro Monster Beats By Dre Solo Monster Beats By Dr Dre Solo HD Beats By Dr Dre Beats By Dre Australia Cheap Beats By Dre Beats By Dre Store Cheap Beats By Dr Dre Studio Cheap Beats By Dr Dre Pro Cheap Beats By Dr Dre Solo Cheap Beats By Dr Dre Solo HD Cheap Dr Dre Justbeats Headphones Beats By Dre Australia Beats By Dr Dre Dr Dre Beats Dr Dre Headphones Beats By Dr Dre Studio Beats By Dr Dre Pro Beats By Dr Dre Sol Beats By Dr Dre Solo HD Beats By Dr Dre Headphones casque beats by dre casque dr dre monster beats by dr dre casque monster beats beats by dre france Casque Beats by dre Studio Casque Beats by dr dre Pro casque beats by dr dre solo Beats by dr dre Solo HD Casque Dr Dre Justbeats Beats By Dr Dre Beats By Dre Canad Cheap Beats By Dre Beats By Dre Headphones Cheap Beats By Dre Stduio Cheap Beats By Dre Pro Cheap Beats By Dre Solo Cheap Beats By Dre Solo HD Auriculares beats by dre Auriculares monster beats by dre Auriculares dr dre beats dre Beats by Dr Dre Pro Beats by Dr Dre Solo Beats by Dr Dre Solo HD Monster Beats Studio beats by dre casque casque dre dre beats sortie casque monster beats casque beats studio dr dre Casque Beats by dre Pro Casque Beats by dre Solo Casque Beats Solo HD Casque Dr Dre Justbeats Casque Beats By Dre Casque Dr Dre écouteurs Beats écouteurs Beats By Dre Beats By Dr Dre beats pro casqus dr dre pro casque beats solo HD casqus dr dre solo HD casqus beats studio casque dr dre studio casque Monster beats Monster beats dre Beats by dre australia beats by dre dr dre headphones Monster beats by dre studio Monster beats by dre pro Monster beats by dre solo headphones Monster beats by dre solo hd Beats By Dre headphones Beats By Dre Australia Beats By Dre Studio dr dre beats headphones beats studio beats pro beats solo hd pro headphones music Official store Monster Beats By Dre Pro Monster Beats By Dre solo Monster Beats By Dre solo HD Justbeats Headphones Signature Monster Beats By Dr Dre Studio

  33. Avatar
    Cute And easy hairstyles over 5 years later:

    it is really good ,you can have a try

  34. Avatar
    mbtshoe over 5 years later:

    Australia Beats By Dre Studio dr dre beats headphones beats studio beats pro beats solo hd pro headphones music Official store Monster Beats By Dre Pro

  35. Avatar
    funny images over 5 years later:

    Thanks for taking this opportunity to converse about this, I have found it extremely useful.

  36. Avatar
    celebrity gossip over 5 years later:

    Please, as you gain facts, please update this blog with more information. I have found it extremely useful.

  37. Avatar
    beats headphons over 5 years later:

    The monster beats headphons are semi-open in design

    However, the headphone industry is greeted with far less unanimity. dr dre headphons targeted toward audiophiles are often considered weak or thin sounding by the general consumer. Despite a price tag worth more than 5 times the amount of the monster beats dre studio headphones they are used to, the consumer may not be inclined to agree with the more expensive headphone’s proclaimed superiority. In order to please both the consumer and audiophile demographics, headphone companies must either exhaust their R&D departments and often come up short, discover some magic voodoo potion, or simply give up! I know for certain that in the case of the Beats By Dr Dre Solo, V-Moda did not subscribe to the latter.The beats headphons headphones themselves are semi-open in design and allow sound to leak into the outside. For this reason, the Beats By Dr Dre may not be the ideal headphone choice for some listening environments.

    Some may inquire as to why Beyerdynamic would choose to create an open-back headphone. The reason as specified by many manufacturers that design open-back New Style Beats By Dr Dre headphones is that it is easie.House of Marley has consistently surprised us with their uniquely designed monster beats dre studio headphones. The House of Marley Trenchtown Rock Destiny is their latest offering, a noise cancelling headphone which competes with many similarly-priced noise cancelling monster beats dre studio headphones and ‘rapper monster beats dre studio headphones’. Overall I felt that the Destiny is a good choice for a listener who likes great style, active noise cancellation and up-front forward bass.The noise-cancelling ability of these cheap beats by dre studio headphones is pretty good, however there may be better options at this price point if Active Noise Cancellation is more important to you than the aesthetics of the cans. I do however have two quibbles with regard to the way the feature is implemented. One is that in order to hear music, you must use the noise cancelling feature.

    This means that your batteries better not run out, or you should be prepared with extra batteries (two triple A). While it is not uncommon for noise cancelling Beats By Dr Dre Pro to require the noise cancelling feature to be activated in order to hear music, several new models are coming out that will still output sound when batteries are dead, or noise cancelling is in passive mode. The second is the louder than average thump sound which one hears when switching the noise cancellation on while the monster beats dre studio headphones are on the head.Listening to Maroon Five’s “Moves Like Jagger” I was very impressed with the immersive quality this headphone had. If you want a headphone that makes you dance, these Destiny monster beats dre studio headphones may very well be your destiny.With regard to accessories, beats dre studio do not offer much. The cable itself is built into the headphone (Y-split style) and is not user replaceable. The cable itself is very sturdy, extra thick and may benefit from a Beats By Dr Dre Solo headphone extension cable if one is going to be more than 4 feet from their source.
    dr dre headphons,beats headphons,New Style Beats By Dr Dre,cheap beats by dre studio,Beats By Dr Dre Pro,Beats By Dr Dre Solo

  38. Avatar
    iPod Manager over 5 years later:

    Good tips,this blog is very educative and have answered almost all the questions i had in mind, thanks for the good work and keep it up.., transfer ipod to computer and computer to ipod, between ipod iphone ipad without itunes

  39. Avatar
    Wedding Hairstyles 2011 over 5 years later:

    A very clever idea, will impliment it as soon as possible. Keep up the good work

  40. Avatar
    louboutin sales over 5 years later:

    Outliving The Great Variable Shortage 39 hoo,good article!!I like the post!14

  41. Avatar
    dre beats outlet over 5 years later:

    I think although bel canto, sex, delicious are different things, and touch is also different sense organs, but having a bit is with. cheap dr dre beats, beats by dre outlet.
    Can bring cheerful, good psychological feeling and enjoy. beats outlet. In some cases, the aesthetic feeling of strong impact, dr dre beats outlet,can even make the person produces excited, thriller, climax…... Of course,dre beats outlet, most of the time, we just need the quietly enjoy that brings the aesthetic feeling heart cheerful. monster beats outlet.This mind the sense of joy and satisfaction, I think is that the bel canto, sex, delicious this series of several things up. beats outlet, dr dre beats cheap.
    For example, now I am through Italy CC Admonitor horn appreciate a beautiful art trio of performance Clara schumann’s piano trio works monster beats outlet(schumann wife works, hardly one to hear). dr dre beats outlet,Wonderful piano, violin, cello acoustic sound, so that I vaguely recall today enjoy lunch-the "top" near wujiaochang Thai restaurant food. beats by dre outlet, beats outlet.Delicious and bel canto, also bring me a cheerful, enjoy, beats for cheap,satisfaction, although only meet different sense organs. dre beats for cheap, cheap beats, cheap beats by dre.

Comments