Adept Software Development

Adept: (A)pplication (D)evelopment (E)nterprise to (P)ersonal (T)ransition. It is a system I am developing to leverage Enterprise developer skills to produce stand-alone software for other market segments. This is a general software development blog discussing issues about project, architecture, design and development. The emphasis will be in Java, but many of the issues will be more general. Almost all will be technical.

http://marringtons.com

Tuesday, January 25, 2005

Using Scope

I recently read an article proposing that where possible a countdown for(;;) loop would improve efficiency without introducing variables that have a scope more large than needed. The proposal was that:
for (i = list.size() - 1; i >= 0; i--)

 

is more efficient than:
for (int i = 0; i < list.size(); i++)

 

It is more efficient, but at the cost of being more obscure, easier to misinterpret. One reader suggested using the extended for initialiser:
for (int i = 0, end=list.size(); i < end; i++)

 

This certainly returns the loop to a more understandable structure, but it is still complex and hence rather difficult to read. All this is because of a fear of cluttering the local scope with variables:
int end = list.size();
for (int i = 0; i < end; i++)

 

It's not something I'd worried about before now. I guess that is because I started with C where all local variables had to be at the top of the function before the first code. A method should be short enough that variable name confusion should not happen - if it does, your IDE should tell you. If scope concerns you, just place the whole in a scope-limiting block. That is what they are there for, after all:
  {
    int end = list.size();
    for (int i = 0; i < end; i++)
  }

 

On an interesting side note, did you know that i, j, k are still often used as temporary variables for loops because FORTRAN allowed variables starting with i, j or k to be used as integers without being defined?

0 Comments:

Post a Comment

<< Home