Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I'm looking at a function that that has several statements like this:

n = returnDifferentVersionOf(n);

I.e., the value of the same variable n changes progressively several times during the course of a subroutine -- rather than a newly named variable being assigned at each change.

What is the generic name of this technique (if there is one)?


A more full example might be (in Ruby):

# reuse same var
def cromulentize(str="")
   str = "wowza" if str.empty?
   str += " adios!"
   str = str * 3
   str.gsub!('a', 'X')
   str = str[0..-3]
   str.upcase
end

What is that technique called, as opposed to this one:

# uses diff vars
def cromulentize(str="")
   non_empty_str = str.empty? ? "wowza" : str
   adios_str = non_empty_str += " adios!"
   multiplied_str = adios_str * 3
   gsubbed_str = multiplied_str.gsub!('a', 'X')
   spliced_str = gsubbed_str[0..-3]
   upcased_str = spliced_str.upcase
end

(Note that in Ruby the value of a method's last expression is the return value.)

share|improve this question
3  
Why does it need a name at all? I do this all the time, and if there is a name for it, I don't know it. –  Servy Aug 28 '13 at 20:46
15  
... programming? –  Matt S Aug 28 '13 at 20:51
6  
destructive updates? –  jk. Aug 28 '13 at 21:03
4  
I really don't get where this tendency to assign everything a programmer does to a 'pattern' suddenly came from –  James Aug 29 '13 at 9:10
5  
@James Maybe to save a lot of precious time and minimize misunderstandings in the communication between developers. Not to mention learning what the possible solutions are without having to reinvent them each time. –  lortabac Aug 29 '13 at 9:23
show 3 more comments

5 Answers

up vote 5 down vote accepted

In some cases, n might be called an accumulator, or you might say that you're accumulating the result in n. That's especially true if n is used to gather the result of a number of similar calculations, like adding up a list:

n = 0;
n += foo.price;
n += bar.price;
n += baz.price;
n += qux.price;
print("The total is: %f", n);

accumulator is an old computing term for a variable (or in hardware, a register) that stores results for further use. You can see how the name applies when the operations are all the same, as above... the value in n piles up the way falling leaves accumulate on the ground. But I think you can still use the term accumulator even if the operations are not all the same, as in your example.

share|improve this answer
1  
In neither of his examples were all of the operators adding something to n. The first was replacing n with something entirely new, and the second was doing all sorts of things, some adding, some mutating, etc. If there is a name for what the OP is referring to (again, I know of none) then what you're describing would just be a subset of that. –  Servy Aug 28 '13 at 20:59
    
@Servy Read the question again -- the whole first section refers to n used in this capacity: "...the same variable n changes progressively..." In the next example str is used to accumulate the results, contrasted with the final example in which there isn't a single variable used as an accumulator but a series of variables each store a single intermediate result. –  Caleb Aug 28 '13 at 21:06
1  
+1, but I would include that even in a CPU the use of an accumulator is not restricted to adding values. And it should be clear that this is just an analogy. –  Doc Brown Aug 29 '13 at 6:15
1  
I'd say accumulation hits the concept pretty close to the bulls-eye, so I'm going to accept this as the answer. Although classically/historically the word seems to have been used when referring to an accumulator for numerical values, various languages today seem to use the concept more flexibly with respect to values of any type. (See reduce/inject (as implemented in Ruby) a.k.a. fold.) –  GladstoneKeep Aug 29 '13 at 15:01
    
The CPU concept of accumulator may be the appropriate metaphor for this technique. But I suggest to you that the number one cause of bugs in CPU language programs ( assembly ) programs, is the unintended, inadvertent reuse of the accumulator and as such, this is really an anti-technique. –  Andyz Smith Aug 29 '13 at 15:28
show 4 more comments

Unless I'm missing something here, the word you're looking for is one you already have: variable.

In mathematics, a variable is a value that may change within the scope of a given problem or set of operations.

With this technique:

# uses diff vars
def cromulentize(str="")
    non_empty_str = str.empty? ? "wowza" : str
    adios_str = non_empty_str += " adios!"
    multiplied_str = adios_str * 3
    gsubbed_str = multiplied_str.gsub!('a', 'X')
    spliced_str = gsubbed_str[0..-3]
    upcased_str = spliced_str.upcase
end

What you actually have there is a bunch of constants since their value is assigned once and never changed after that.

share|improve this answer
1  
The point in adding variables every step of the way would be to improve readability for future maintainers. In many cases this is a good enough reason. –  Mike Partridge Aug 29 '13 at 13:46
    
I removed the comment in my answer about whether or not the practice is a good idea because it's not relevant to the question of simply asking what to use for terminology. –  17 of 26 Aug 29 '13 at 13:58
2  
Careful! Variables in mathematics are different concepts than in most (imperative) programming languages. For example, str = str * 3 from the original example is an equation in Maths! It doesn't mean "mutate str by multiplying it by 3", which would make no sense in Maths. In many ways, its "variables" are closer to immutable variables in programming languages. –  Andres F. Aug 29 '13 at 14:42
    
This answer actually has a pretty valid point re: my question. Variables by definition can (and in practice do) vary. Still, the style one uses when employing variables is a choice that affects program readability and clarity. I.e., if it's clear my method is just going to mess with the string n, then reusing n might be okay (an easier to type). But in some cases it would help future maintainers if I assigned a new named variable for each and every adjusted version of the original value. –  GladstoneKeep Aug 29 '13 at 15:13
add comment

The closest name you could really give this is "'threading' (not in the concurrent programming sense) or 'compose' in an imperative language". This is exactly the sort of thing that (eg) Clojure solves with its -> macro.

http://blog.fogus.me/2009/09/04/understanding-the-clojure-macro/

It takes a series of functions that should be executed in a particular order and feeds the result of each function to the next function in the sequence. You could achieve the same effect by simply nesting function calls but that gets ugly fast.

share|improve this answer
    
would you mind explaining more on what it does and why do you recommend it as answering the question asked? "Link-only answers" are not quite welcome at Stack Exchange –  gnat Aug 29 '13 at 16:36
    
So this technique is actually 'threading', but using a global variable for each nested function to returns it's results into? –  Andyz Smith Aug 29 '13 at 18:00
    
Yeah it's basically just using a placeholder variable instead of passing the function's return value directly to the next function. The two examples given in the question are equivalent, they just differ in how they deal with that intermediate variable. I don't think there's a single overall term for this micro-pattern the original question is asking about. The overall technique of calling a sequence of functions in order is what I was answering. The specific method of overwriting a single variable over and over again is called "destructive update" as @jk mentioned. –  Evicatos Aug 29 '13 at 18:16
    
So, to your knowledge, have functional languages such as the one you mentioned been maligned repeatedly for having 'readability problems'? –  Andyz Smith Aug 29 '13 at 18:36
    
Clojure's a variant of Lisp which is basically the poster child for functional languages that are maligned repeatedly for having readability problems ;) –  Evicatos Aug 29 '13 at 21:15
show 1 more comment

ok, in response to downvotes on my reasoning, I submit.

this is called using a Temp variable

And

it is bad


I definitely like the second snippet better. With new variable names I know what is supposed to happening instead of having to guess about the intention of the original coder. This makes it a thousands times easier to refactor code, to simply add two lines in between two existing lines, or to create a whole function for what was a simple assignment or manipulation by a accumulation or something.

Managing complexity is critical to success of any non trivial program, and this 'technique' of using the same variable name is not helping manage complexity. In fact, it is making it worse, as the code reader has to deal with a kind of multipurpose, polymorphic variable.

The only case I can see this being somewhat helpful is when

  1. The scope of this variable is very short and adding verbose names would only complicate things more. But beware, what seems simple and of short scope now, can easily be expanded over time, and programmers won't rename anything and eventually you end up with a mess.

  2. Sometimes, when you know the expected output format of a variable at the end of a function, you MAY use that variable as it's own temporary holding area for some manipulations that are relatively incidental and the whole scope of the variable remains small. But even this, SO, SO, SO many times, when trying to redesign and refactor code like this, I'd would have rather the original coder spent twice as many lines and twice as many variables, just to show me exactly, in explaining to 6-year old level of detail, what is supposed to be going on. Nonbelievers, flame on.

share|improve this answer
3  
That's not the question about style. There is concrete question regarding name of specific technic. Whether it's good or bad technique it's a different discussion. –  nirth Aug 29 '13 at 13:00
    
Negative. If the variable is being manipulated by some 'magic number' or some canonical string manipulation, it is then almost universallly a different thing. –  Andyz Smith Aug 29 '13 at 13:04
    
EG. float Bank = 100.60; bank = Bank * EuroExchangeRate; return Bank; –  Andyz Smith Aug 29 '13 at 13:06
    
float BankInDollars = 95.5; Float BankInEuros = BankInDollars. * EuroExchangeRate; –  Andyz Smith Aug 29 '13 at 13:07
1  
I would actually say that the second example is using temp variables. The variables are used to temporarily store intermediate results and are not relevant after that. –  17 of 26 Aug 29 '13 at 14:05
show 5 more comments

I would call it a mess. None of those changes are related, either in cause or in effect. Making all those checks and changes in one place in your code is pointless. If this string is a significant property of a domain object, there should be meaningful, distinct methods which change it, each change being separate. Unless you can provide some better evidence to show otherwise.

That is garbage code.

Edit: as I hope is clear from the discussion in the comments, this isn't a dig at mtoast.

share|improve this answer
    
I don't see anything wrong with it as long as it is clear why each line is changing n. –  Brandon Aug 28 '13 at 23:13
    
@Brandon The examples given are so disparate that they do not belong together. If mtoast was simply choosing random examples to create a big enough set, fair enough, but that doesn't change the fact that this is not coherent code. If mtoast really would group these kinds of statments together, that is not good practice. Changes should be composable and easily reversible; that can't be the case when such disparate changes are lumped in one method. Would you really create a single toUpper/checkBounds/trim/sort/defaultifnull method? Contrast with Caleb's code, which is much more consistent. –  itsbruce Aug 28 '13 at 23:21
5  
@itsbruce You're giving the content of the statements too much weight. The very fact that the actual statements are nonsensical emphasizes the important difference between the two examples: a series of changes to a single variable vs. separate variables for each step. The actual steps don't mean anything -- it's a Ruby-ish lorem ipsum. –  Caleb Aug 29 '13 at 7:25
1  
@Caleb almost certainly, but I'm willing to take the rep hit just to make the point. I know from long experience that the naive and inexperienced actually pay attention (even if unconsciously) to what are not intended to be significant parts of an example. I used to know a CS lecturer who taught Pascal. The procedures in his code examples always had the same names as the global variables they operated on. 90% of his students left with the impression that this was actually a requirement. –  itsbruce Aug 29 '13 at 9:01
    
@itsbruce - I personally agree with you so I upvoted your question. –  Ramhound Aug 29 '13 at 11:16
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.