SPELLBINDERS:

linda o' neil

APHORISMS ON PROGRAMMING

Brief or not so brief observations (or "lessons") on programming and scripting techniques, meant to make you understand, if you're a beginner, scripting issues or procedures, and trying to make you have further thoughts in case you're already somewhat experienced. Chapters can span through more than just programming.
November 2003
{ @ }

The model above is Linda O' Neil - Miss. O'Neil Website
LOADS OF LINDA O' NEIL ON THE NET
Linda O' Neil


UNDERSTANDING COMPARISONS AND RETURNS
Everything returns in a programming language: what it means and its relations with comparisons with a special regard to the syntax:
aVar=some||somethingelse

- Best viewed listening to W.A. Mozart, Piano Sonata in F major KV 332 (300k)

Or to the 2nd movement of Mozart's Piano Sonata KV 570, yet this latter piece can vary so strongly and so dramatically accordingly to interpretations, that every time it may appear as a brand new piece: so impalpable and imponderable it is, that as soon as you hit a key you risk to crush the meant sound by the very same gesture of daring to play. No one has ever interpreted that piece in the way it was surely meant for (perhaps a great interpreter of Bach's Goldberg Variations' Aria could).
Anyway the best pianist at it so far has been Friedrich Gulda: yet it is like playing a thing which cries, and which then whispers "you can't play me, that is my nature! every time you try you necessarily wound me, and this sound is not my melody but my lament because you just did. You can rape me but you can never have me." (which is the true meaning of "virginity": not deliberate abstention but impossibility through the sought for interventions & interpretations; and, undoubtedly: «No one applauds a tenor because he has cleared his throat» [Les Liaisons Dangereuses]) -

«On the whole, what is essential in all these magical and magico-medical rites, is the orientation they give to the power that resides in any kind of binding, in every act of 'tying'. And this orientation may be either positive or negative, accordingly to whether one takes the opposites in the sense of 'benefic' or 'malefic', or in that of 'defence' or 'attack'.
(...) The latin fascinum, 'charm, malefic spell' is related to fascia, 'band, bandage'.»
[Mircea Eliade, The God Who Binds]
Making a comparison is always susceptible to be regarded as rude, yet it can be useful if it is an avenue to further knowledge and not to moral implications; but of course, programming languages have no ethic concerns implied in their engines: only human brains have them, and such concerns can be either a diehard obstacle to self improvement or a blessing as well. You tell the former from the latter because the latter, unlike the former, produces more benefits than those it withholds. A tradition in itself is no good just because it crystallized:
«You cannot change an old mistake: what is there more venerable than an ancient abuse?»
[ Voltaire ]
The paradigm of all comparisons is the balance, and you have to mean both versions of it, as the scale and as the balance with arms. The former weights accordingly to a standard, the latter compares namely weights two items through themselves. Archimedes knew a lot about balances, for what is a balance if not but a lever whose fulcrum is in the sky, and what is a lever if not but a balance whose fulcrum is on the earth - and where one weight is your own strength, you earthly roamer?
And, of course: don't forget it's all 'bout gravity: Archimedes, the antigravitationalist...

You may find interesting a book by Ernst Mach titled "Mechanics in its historic-critic development", whereas you may notice the following slightly unusual observation: with a lever the less your strength the longer the arm you push upon must be, as if what would matter would be the reconstitution of a mathematical average made by the sum weight+its portion of the lever arm's length (the less the weight, the longer the arm; the more the weight the shorter the arm) before the fulcrum (its distance from it, that is).
See, ladies and gentlemen, if space and time are one thing, and distances and weights are the same thing too as a balance seems to imply, and distance is undoubtedly just space, then space and gravity -and time- are all the same one thing: could therefore gravity be a fifth dimension like time is conceived as the fourth? Can you reduce gravity by augmenting space? Indeed, that's what happens as Kepler and Newton stated. Are they the same one thing converted into different funnels? Is gravity compressed space, space sliding upon space? Can space run?
This is why a balance to be equitable must have arms of equal length.
A pretty peculiar type of balance with a peculiar ratio in its arms is the so called Golden Section.

egyptian balance
The dead is brought at Osiris' tribunal. Anubis checks the accuracy of the balance and Thoth notes down the weighting: the earth of the dead against the feather of justice. If the hearth weighs more, Ammit -an hybryd creature- will devour the dead, and that's called the second death: you live only once but you can die twice.
Shakespeare said:
«I care not; a man can die but once; we owe God a death. I'll ne'er bear a base mind. An't be my destiny, so; an't be not, so. No man's too good to serve's prince; and, let it go which way it will, he that dies this year is quit for the next.»
[Henry IV, part II]
Egyptians would disagree.
egyptian balance
Where will the balance tilt today? It is said that when we'll die, we might all end up partying in the paradise of the egyptians. To enter there, your own soul will be put on a balance, and it will be weighted against a feather called maat (being ma'at also the egyptian symbol for the offering of Justice, its biblical equivalent is the thanksgiving as the only sacrifice that God wants): will the feather outweigh your soul? I hope so, if you don't want to be hurled into the Tartarus.
Yet, nothing is said on the length of the arms: whatever feather on a long enough arm will outweigh you, thus you could soon be among the elects even without deserving it: do they swindle in Heaven?
But I don't think that even the lesser of the spirits in the afterlife would ever have any need or reasons to cajole you who just arrive from the land of the flesh; thus, it is more likely that maat will be on an equal footing or at most on the shorter balance's arm - which latter case would lead us to exclaim: if mortal sins can burden a soul so much (or... so little? isn't this egyptian symbolism incredibly rich if you think it over a little while?) that I need an advantage even to lift a feather and thereby be damned, we are necessarily unworthy of an orderly afterlife exactly as we proved ourselves unworthy of an orderly life: is the test pointless?
If maat is on the longer arm, they are desperately trying to save you. If maat is on the shorter arm, they are desperately trying to damn you. Thus equity in a lever doesn't follow from the necessities of those that lift, but from the necessity of those that get lifted: only those who lift seek different arm lengths - but who's lifiting whom?
So, now play that tune my pianist deftly run headlong on the water do not splash around.

So, in programming languages you know either by weighting or by comparing. It all rolls down from that far away. It carries along all that old baggage.

Indeed, programming can be considered but the endless art of a continuous -as if it were a perpetuum mobile- weighting: it is the art of an interminably perspicuous posology. Like music, it's a matter of weights and (algo)rhythms - gravity, space, time.

Of course, when you compare you compare for the knowledge, for the result. Such a result is called in programming languages the returned value - that is, the outcome of the weighting, for you don't weight in vain: programming weight is called the return[ed value]: it's maat's sentence.
But if programming is all about weighting, and weighting is all about returning, then programming is all about returning.
The keyword return that we usually employ within a block of code named a function is deceptive: it deludes us into the fiction that only by declaring such keyword a return is impelled. It is not: it is always there whatever you do, and it is critical that you understand this: whatever block of codex invariably returns something in the boolean shape either of true or of false. As you'll see in this same file but further on, even a mere assignment aVar=1 returns.

If the traditional symbol to perform an assignment is, logically enough, the equal (=) sign so that:
aVariable="hallo";
the traditional symbol to perform an identity comparison (that is, checking whether two items are holding the same value) is, conversely and illogically enough, a double equal sign (==):
if(var1==var2){/*do something*/}

Now, this double equal sign is perhaps not truly illogic, yet it is unhappy to say the least: would have been a sign like:
?=
or like:
=?
much less counter-intuitive than == is? I think it would.

That such == symbol is unhappy not only in my prolific mind, can be proved by the amount of beginners who, generation after generation, keep being fooled by it and who, generation after generation, invariably keep wrecking against this same old rock: that is, against mistaking = by == at least a few dozen times before grasping what it truly was all about.
Yet you see that a negative comparison (checking whether two items are not equal, that is) is achieved by the symbol !=, so:
if(var1!=var2){/*do something*/};
checks whether var1 is different by var2 and if that is the case, the code held in between the curly brackets by the if statement gets triggered.


Perhaps a negation, even within a question (every if statement is a question in disguise) is more prescriptive than a mere question is, and after all the exclamation of a ! better suits the idea of a radical: no! - yet it is not clear why in this latter case a ! has been found as fit to be included as a syntactical element of a comparison operator whereas including the question mark for the other type of complementary comparison has, apparently, never been taken into consideration. To me, it would have been the most logical, immediate choice - and it would have imported no problem allowing a ?= syntax (or: =! vs =?): no problem as far as instructing the interpreting engine might have been concerned, because a != couple of chars (! and =) meant to be handled as one when met subsequentially imported no problem, so why should two immediately subsequent ?= chars have imported any whereas two == and two != didn't?
Yet a comparison is achieved by a rather illogical ==, so just grin and bear it.

Now, I want you to focus on this element: I told you that every if statement is a question in disguise: isn't in fact a statement that starts downright with a wondering if a patent and obvious question?
Now, within this question, another question resides for the if statement carries a comparison (var1==var2 meaning "is var1 equal to var2 in its value?", or var1!=var2 meaning " is var2 different than var2 in its value?").

Thus I want you to understand this: within there two differentiated processes coexist, first the comparison which yields (returns) a result, then the returning of the result for the if statement, call it the outermost question, as if you were returning twice on the whole: once for the comparison, a second time to fulfill the if statement.

Thus first a comparison is performed, then the outcome is handed over to the previous question (statement), and this last outcome is the eventual return: each set yields in (returns) its own result.
daily bread
The Daily Bread Institute in Bucharest, 1920. The defeat of the Austro-Hungarian Empire at the end of World War I led to widespread chaos and poverty. Consider the faces, the age...
a Robert Doisneau photo
a Robert Doisneau photo: frugal lunch in Montrouge, 1945 (arguably Paris)
Ernest Hemingway
Ernest Hemingway, in a photo either by Roberto Herrera Sotolongo or by Jean Paul Paireault

The result is all codex blocks chain cascade each its own return upward within all the blocks until the eventual result/return is relinquished. Return - return - return - return...: basically, a recursion.

Whenever in a programming language you meet a set of brackets enclosing a set of codex, you can conceive that as a set of elements that will produce one or more returned values (dispatched to address a manifold other questions, like in a neuron the same impulse can split while flashing through the axon) that will be passed to the other sets of brackets that nest them, until the eventual first outermost set of brackets is met and there the last eventual returned outcome of the intermingling of all these returned operations is surrendered: codes are better read from the innermost nested element to the outermost one, or from right to left (Leonardo da Vinci & Bill Gates), for those are the counter intuitive yet in this case true directions of the returns.

Of course, multiple comparative checks are allowed: if all of them must be met (and - and - and - and...) you concatenate with a set of "and" logical operator chars, namely two && signs (which I find now an obvious enough semantic, though perhaps one "&" would have sufficed), otherwise if either of them must be met (or - or - or - or...) you concatenate by the logical "or" operator which is a set of two pipe chars: || (which is rather logical: seems portraying a disjunction. Or perhaps the reason both the & and the | signs are doubled is exactly that, unconsciously, what we brought along was an unaware influence by the symbol of the double arms of a balance):
if(var1==1 || var2==1){/*do something*/}
The above checks whether var1 is equal to number 1 and returns the result, then if that holds false (or: ||) it checks whether var2 is equal to number 1 and returns that. If now either of the comparisons returned true, it performs a last return to fulfill the if conditional statement question and such statement returns on its own turn either true because at least one of the conditions (or/or/or) was met - or it will return false if none of the conditions applied successfully. Accordingly to this eventual return, what is included in the curly brackets associated with the given if, is either executed or not.

I want now to make a few considerations on a specific syntax I already criticized elsewhere, but not for the reasons I report here. This syntax is the following one:
aVariable= var1 || var2;
Now, why I want to criticize this syntax, provided that it works perfectly? Because I find it is misused. First let's say what that expression means in human terms: its meaning should sound: assign to aVariable either the value of var1 or of var2. Now, how does it choose which one, given the fact no if condition has been set in order to decide after what parameters the discrimination should be done?
Let's see.

That syntax, although the presence of a || operand might well induce you into the error of believing it is comparing, compares nothing. Let me insist: be warned it does not compare the variables at all: it merely returns. Let's clarify this cryptic statement.

Remember the two step process as highlighted before, namely the cascading returns whereas we had first the comparison and then the returned outcome for the if statement?
Well, that process is missing here: here you have only an immediate return with no comparison. So such syntax should never be featured as a "fast alternative" to a comparison (as at times it is): its virtues are not in its being fast, and anyway it is not a comparison in the least, it is a return only: so it cannot be an alternative to traditional comparisons, which it performs not.

That expression merely weights (on a scale, not on a balance) whether var1 has some value which is not suitable to be false (values suitable to be false are only: boolean false, number zero, an empty string, or a null or undefined -unassigned, that is- value which - happens when a variable name has been declared but nothing at all has been ever assigned to it as its matching value, or NaN which is what is returned when you attempt to perform a mathematical operation on something which is not a number) and if such a false value is found (if it finds something not suitable to be false, namely which is true or a valid value other then the one just fore mentioned) it immediately returns it, and that's over, and that's all: the second part of the statement is not even weighted.

    Values suitable to return false
[check the relative checkbox to allow editing of a text field]
false
null
0
""
undefined
NaN

But if the first var1 doesn't yield a value suitable to be seen as true, then the expression immediately returns var2 without any further consideration, and assigns its value to aVariable whatever such value held by var2 is, even false! And this definitely warrants its difference from the same expression within an if statement because within such a latter statement the check to verify whether the two variables were returning (at least one of them, as a || implies) a value suitable to be handled as true would have on the whole returned false if both variables were returning false, and thus none of the variables could have been assigned. That's different, indeed! See: if var1 is false, it discards it, yet if var2 is false too it does not discard it. Not only it just returns, but it does it in a funny way.
Check it:


    check to re-enable textarea editing: »

So, would you call this a comparison? I call this as I called it: a bare return.

That its virtue is not its alleged fast nature can be proved by the simple fact that you could put on its sides two functions whose runtime could be long enough to completely vanish whatever hypothetical marginal gain afforded by the usage of such syntax:
aVar= OneMinuteFunc() || threeMinutesFunc();
An example which, actually, enthrones us directly in the heart of the matter.

This syntax was used originally and for the first time for a completely different set of processes than for those we see it employed nowadays - regardless of educational purposes which as such are justified.
If you remember the old times of the GCI (Common Gateway Interface) and Perl (which anyway is still a both valid and widely used server side language) you could find that || expression invariably used when attempting to open a file and to flag the failure of such operation (by a function traditionally named die) in case the file could not be open triggering an alternative function:

open(HANDLE, "myfile.lib") || die("Sorry, an error occurred, file was not found");

This type of syntax still persists, nearly unmodified, in more modern server side scripting languages like the powerful PHP:
$file=fopen("myfile.src") || die("damn it, I can't open the file!");

Or, a cute example by W. J. Gilmore A Programmer's Introduction to PHP 4.0, as recent while I write as © year 2001:
$result=odbc_prepare($connect, $query) || die("Couldn't prepare query!");

It is important then to understand why that syntax's origins show it typically used for those instances whereas functions were involved, and not for others where data structures different from functions could have been: if you understand this you will also grab why you should use it when you have a similar reason and why I am puzzled by seeing this return only syntax used in other contexts; what I mean is that I can support my point with a tradition, so I can be wrong but I cannot be accused of having dreamt just my own dream.
This does not mean there cannot be other traditions, or that you can not use the syntax anyway in different contexts than those it was traditionally conceived for: it only means that my suggestion is not irrational, and that's all.
Using that syntax in other contexts can be a source of unnecessary confusion, and of a confusion which is not the result of not attentive or unlearned readers but of your misinterpretations on what it was properly meant for: examples (try to understand the returned values: you will, but they are not as obvious as other alternative and equivalent syntaxes would be):

    check to re-enable textarea editing: »

Thus the syntax is used with functions.
Why? Because functions either may return too much stuff to let it loiter, or they take (too) much time to be run and thus they should not be lent to an alternative syntax like:

aVariable=(aFunc())?aFunc():anotherFunc();

In fact, the syntax above is a valid syntax, and is actually the alternative more widely used: it checks what is within the round brackets, if they return true it executes what is after the ? sign, if they return false it executes what is after the column :

But, it is obvious that this latter syntax used with functions would risk of executing twice the function whose foo foo name is aFunc: once to verify if it returns true, twice to assign it: and this is a sure waste of time.
But it would be a waste of time no longer if instead than a function what would be checked would have been an already existing variable which as such is not executed on a stack like a function is: and this is why such last syntax used with variables which are not functions should be always preferred, besides being clearer at first sight.

You may think that saving the outcome of a function on a temporary variable and then checking, namely:
var temp=aFunc();
aVariable=(temp)?temp:anotherFunc();

would do the trick; nope, it would be dysfunctional as well, for you're just swapping a waste of time with a potential waste of space: a traditional trade off which yet can be spared for the only trade offs you must submit to, are those that are unavoidable not those you can successfully avoid.
In fact such procedure may be indifferent as long as the function just returns one "innocent" value, but what if the function returns complex data drawn on a complex input argument like it may happen, just for instance, with my arrays report?
Are you to let a chunk of data like say a 500 entries arrays as it gets arranged after the arraysReport has run onto it, linger with impunity in memory for an unnecessary little while - maybe at the risk of just forgetting it there (we have seen worst things than such a nuisance happen, in fact we have seen bridges crumble)?
True, you can isolate only one snippet of that data:
var temp=aFunc()[0][3][0]; //say...!
which proves actually my point: why using then the || syntax? The only difference that rests on its side is that it is useful when your concern is a concern of speed regarding execution of functions: and thus no surprise I found such use a trade off between clarity and space which was not the trade off it was meant for, which ought to be the trade off between space and time.

Also, the argument it is shorter is absurd: how much absurd? As much as this:
x=y||z;
x=(y)?y:z;


It's a mathematical difference of two round brackets and one letter, three bytes.
If you need space that badly saving it this way should be the last of your concerns, unless you have a flair for entertaining the wrong solutions that won't address the problem.
That's a bad excuse, which raises the question: why you're looking for an excuse in the first place? They answer: it is not an excuse at all, it's an explanation!
Yet that is the justification, if we ought not call it the excuse, they present when faced with the objection: but a bad excuse changed into a bad justification/reason, is still the good name to season exactly the same bad excuse.

Therefore the traditional use of the || return only syntax is with functions, not with whatever; and the reason it was devoted to functions since inception (and therefore the shift to other ways to return data other than functions is unwarranted: not illegal, let's be clear) is that it lends itself to save as much time and space as possible when handling functions within comparisons.
Since that syntax doesn't compare but just returns, it can either grab the returned value of a function without executing it again or it can let it vanish instantaneosuly from the memory into thin air (the so called garbage collector of digital interpreters), if the function didn't produce the suitable result. You'd then reserve that syntax for usage with functions.

Yet in all other cases, especially where your code is not for your eyes only, concerns of clarity should not be dismissed so lightheartedly, and you should not be lured into giving up clarity ( as afforded for instance by the ? : syntax) with the official intention of gaining a picosecond (by the || syntax) in a world of processors whose speed doubles each 18 months, and with the hidden agenda of dazzling your audience by the virtuosities of your coding bravura: the official intention is certainly praiseworthy - after all that is precisely why it is the official one: but it's so irretrievably slurred by the fashion the hidden one betrays itself from the bulge under the cover, that if you care of the latter you'd never let seethroughs reveal it; and if you truly care of the former you'd never let the latter determine your choices: that's bad programming practice, indeed...
It's like an italian (or an european, for that matter) woman who wears briefs at all times, and who says that's because the whether's so hot. Briefs are ok, actually: it is the justification what truly shows too much and what enters offensive vulgarity.
Is there a Vanity Fair of the programmer?


VARIOUS PROGRAMMING "APHORISMS"
A few scattered elements


The typeof syntax: when should you check whether a variable exists by:
if(myVar){/*do something*/}
or by:
if( typeof(myVar)!="undefined" ){/*do something*/}
You use the latter expression (whereas obviously myVar is a placeholder for whatever variable existing in your script) when what you want to verify is the existence of the variable and that some value has been assigned to it, even false or zero or an empty string: all these would fail the former check, which would return false and won't execute any further code - yet this may not be what you meant so keep in mind that won't fail the latter check namely the one by typeof.
At times you just want to see whether a value has been assigned, and you'd be all right even if such value is false: to verify if a value whatsoever has been assigned, use typeof. So be aware a mere if might conceal the fact your variable has been actually assigned a value, though maybe a zero.

A curious thing many are not aware of: all loops which work with a for keyword can, as you may know, initialize variables within their round bracket segment:
for(var i=0; i < anArray.length; i++){/*do something*/}
for(var i=anArray.length-1; i>=0; i--){/*do something*/}

whereas you have initialized a variable i within the loops' round brackets.

Yet, it happens with a while loop too: yet this happens and is implied in a much less obvious manner.
In fact all loops either by for or by while traditionally carry within their round brackets a comparison which must be met as long as the loop goes on, and when it fails the loop breaks out (it stops, that is).
Trivial example:

    check to re-enable textarea editing: »

Yet maybe you're not aware that if you include in the round brackets not a comparison but directly an assignment (that is by mere sign =) you can initialize within the while loop a variable which gets reassigned and updated at every iteration.

    check to re-enable textarea editing: »

Yet note that if you change y=1 into y=0 the while loop never starts. Why? Because the assignment is evaluated and returned (see chapter above), and if the returned value is suitable to be interpreted as false, as a zero is, the whole statement evaluates as false and thus is never triggered. This reveals an important and not apparent thing: even a mere operation of assignment involves a return - returns the assigned value, indeed! And this proves it, methinks.

The value NaN, acronym which stands for Not a Number is what is returned when you attempt to perform a mathematical operation on a variable which is not suitable to be handled as a number. Yet be warned, though NaN appears to your eyes like a String, yet it strangely enough still belongs to the data type Number - which is cause of endless pains for many beginners who are (rightly) puzzled: in fact if something is not a number, well my dear why that which tells me it's not a number is a... number?
It just makes your conditional statements trip, I agree. I suppose that's the reason, come on don't pretend you didn't enjoy it when you spent two nights with no sleep before guessing it all on your own: I am not a number, for I don't show up like a 5 but like a string saying NaN, but you'd guess I am not from the fact I am.


    re-enable textarea editing: »

a Robert Doisneau photo
a Robert Doisneau photo: A Sincere Admirer at Concert Mayol, 1952 (Paris). I find the photo moving - I mean it