PDA

View Full Version : Coding practices...


Vladdy
12-11-2002, 04:46 PM
I was working on something today that aroused my curiosity...

say you have an array of two elements and there is no way you will have more than two elements in this array:

foo = new Array('element1','element2');

When performing an operation on this array, would you use loop as usual:

for(i=0; i<foo.length; i++)
foo[i] = foo[i] + ' changed';

or, since it's about the same amount of code, do straight:

foo[0] = foo[0] + ' changed';
foo[1] = foo[1] + ' changed';

... just a little survey ...

MrDoubtFire
12-11-2002, 04:55 PM
I think you could even shorten it more:

foo[0] = foo[0] + ' changed';
foo[1] = foo[1] + ' changed';

to:

foo[0] += ' changed';
foo[1] += ' changed';


Either way I'd use the second method.

MrDoubtFire

brothercake
12-11-2002, 05:18 PM
I'd use the first method - you may still want to change it in the future.


btw - you shouldn't query obj.length in a for loop - it's inefficient. A better way would be

var fooLen = foo.length;
for(i=0; i<fooLen; i++)

RadarBob
12-16-2002, 03:52 AM
say you have an array of two elements and there is no way you will have more than two elements in this array:

In programming, never say never. The only constant is change. I've made changes to code that wasn't touched in 10+ years. Something, somewhere will changes sooner or later.

The act of delivering software changes the users' requirements.

If you hard code that array I'll give odds that someday another programmer will be cussing out the idiot WHO DID THIS!??

Code for flexibility. The for loop is a construct basic to modular software construction.

Some seem to be assuming shorter must be better. WRONG! In the long run it is always better to code for the "abilities".. That is readability, flexiability, maintainability, etc. Too often looking for the shortest solution makes the code inflexible and harder to understand.

By the way "unrolling" (as it's called) a FOR loop is more efficient in C/C++, so I've read... but ....

In general it is a mistake to explicity code for (presumed) performance first - unless performance is an explicit issue. OTHO I think little things such as explained by BrotherCake are OK.

whammy
12-16-2002, 04:50 AM
Hmm, thanks for that tip, brothercake.

That makes total sense to me, since it seems the script would have to check the length of "foo" at each iteration instead of "knowing" the variable's value. I'll have to start using that method, on principle. :)

Using some of the things you guys have shown me, then, this should be pretty correct?:


<script type="text/javascript">
<!--
function checkanswer(radios) {
var checkflag = false;
var i = 0;
var radlen = radios.length;
while (i < radlen && !checkflag) {
if (radios[i].checked) checkflag = true;
i++;
}
checkflag == true ? void 0 : alert('Please choose an answer!');
return checkflag == true;
}
// -->
</script>

Skyzyx
12-16-2002, 06:46 AM
RadarBob, your points are very good, but I think perhaps that the point of which Vladdy was speaking might have been missed.

Instead of saying that the code will probably change, because that's just what happens, I understand Vladdy to mean that assuming is won't change, which would you do?

Of course, on second thought, I would most likely use the former method, rather than the latter, simply because typically an array would have more than just two values, and I would probably code it that way out of habit more than anything.

Vladdy, I'd vote for the former. However, I would probably make MrDoubtFire's modifications to the second line.

joh6nn
12-16-2002, 07:44 AM
i agree with brothercake; the assumption that the code won't change, is usually a bad assumption.

Vladdy
12-16-2002, 01:22 PM
Good points about code efficiency, MrDoubtFire and brothercake. I just threw some code togeter to illustrate the question, which was IF ARRAY COULD ONLY HAVE TWO ELEMENTS EVER...
I'm well aware of good coding practices and code maintanence issues and I can rephrase the question: would you still do it the right way if there were only two elements in an array.
As far as practicality of such assumption goes... say, array represents a binary condition. For example:
prompts = new Array ('Login successful','Login failed');
You can be pretty sure there won't be 'Hmm... So you were trying to log in, huh?' ;) in the future.

Roelf
12-16-2002, 01:28 PM
whats the point in having an array, when its absolutely sure there wont be more than 2 entries ever, why not use two variables then :confused:

RadarBob
12-16-2002, 01:36 PM
Skyzyx;
No, I don't think I missed Vladdy's point. Restated, it's "all else being equal, which way do you prefer to code?"

I suggested the 'unrolled' for loop could be more efficient and stated that it has it's place. Nonetheless I vote for the FOR loop; and the implied question was WHY would I do it that way.

I'm trying to say why. Because the premise is invalid. It's a fantasy. Assuming the # of required iterations will never change is like asking "Would the Confederacy have won the Civil War if they had B-52's?" A nonsense question and definitely not a basis for Robert E. Lee to plan the Battle of Gettysburg.

IMNSHO it is a mistake to think this way. A good programmer should not engage in rationalizing arbitrary conditions just so (s)he can code the way (s)he wants (even though we all do it sometimes:o ) I emphasise the point primarily because I've seen the results of this thinking. When a program is rife with this "ignore reality" psychosis results I have seen are weak, buggy, unmaintainable code.

Therefore one should not code an unrolled for loop "just because I can" or "I'm bored with doing it the same way for the umteenth time." Don't get me wrong. It's a technique that a good programmer should have in his bag of tricks. BUT know when, how, and why to use it.

BTW an unrolled loop is discussed in the most excellent book Code Complete by Steve McConnell. Every person who programs for a living should have this book.
:thumbsup:

Vladdy
12-16-2002, 01:50 PM
Originally posted by RadarBob
Because the premise is invalid. It's a fantasy. Assuming the # of required iterations will never change is like asking "Would the Confederacy have won the Civil War if they had B-52's?" A nonsense question and definitely not a basis for Robert E. Lee to plan the Battle of Gettysburg.[/B]
Bob, what is invalid in the example I gave?

RadarBob
12-16-2002, 01:53 PM
As far as practicality of such assumption goes... say, array represents a binary condition. For example:
prompts = new Array ('Login successful','Login failed');
You can be pretty sure there won't be 'Hmm... So you were trying to log in, huh?' in the future.
When the time comes for me to make a program design decision (i.e. what language constructs will i use?) clarity is my guide. I look for language constructs that help convey the problem, underlying intent, real-world data organization/structure, etc. at hand.

For example I love a "switch" statement when I have a set of mutually exclusive options. I love a boolean to hold the state of a condition, such as "login successful?" That's yes or no - boolean.

An array is great for holding a set of like things that must be iterated through. To code an array to act like a boolean makes for unnecessarily extra code, obsfucates the code, and hides the meaning and intent. Now If I had a whole bunch of booleans to manage it might be handy to deal with them as an array of booleans. It Depends.

Vladdy
12-16-2002, 02:10 PM
Bob, I'm not suggesting to hold boolean in an array, but a set of parameters associated with a boolean condition. Expanding on the example I gave:
on a page that shows "Yes/No" result you have a prompt that you want to have different appearance and different text. My code would be:

function prompt(text,cssClass)
{this.text=text;
this.cssClass=cssClass;
}

prompts = new Array(new prompt('Login Failed','loginNo'),
new prompt('Login Successful','loginYes'));

This approach would allow me to easily add more features to a prompt if I need to. Having the two objects in array (compared to separate variables) allows me to avoid if-else statements when choosing one of the two.
The array does hold the set of like things (which I agree it should do), but due to the nature of what these things represent there can be only two of them.

If you can suggest a more efficient code, I would certainly like to see it.

RadarBob
12-16-2002, 03:01 PM
This approach would allow me to easily add more features to a prompt if I need to.
Now that sounds like a sound reason. In which case I vote for writting the FOR loop.

BTW it's sounding suspiciously like you could make a javascript object out of it all. I doubt that it's more efficient "on the back end" but I've found that taking the time and effort to collect everyting together as an object, and writing functions to use it all ... then then amount of code I have to write to use the guts of the object shrinks dramatically.

I've used objects to bundle <input> things that work together, are validated together (i.e. "if this box is checked, then that text must be filled in") etc. I also write "overhead" functions too - like dumping/printing/alerting the object for troubleshooting purposes. I end up with an array of objects - in my case directly corresponding to rows of <input> elements in an HTML table.

It's hard to show here how objectizing made things easier. But try it and I think you'll see. It will feel like you're doing extra work at first, but boy does it pay off!