[Tutor] Re: small program in Python and in C++
alan.gauld@bt.com
alan.gauld@bt.com
Fri, 5 Jul 2002 11:12:26 +0100
First of all apologies to the pythonistas for dragging
things well off topic!
> A few questions for the less-learned (such as myself)....
>
> What exactly is refactoring?
Taking an existing function (or class) and breaking it
into smaller more atomic units.
Noddy example:
def bigun(s):
f = open(s)
str = f.read()
str = string.replace(str,'$','#')
for chr in str:
c = string.toupper(chr)
if c > 'H':
newstr = newstr + c
return newstr
Not very useful but looking at it we could factor out two
functions from that:
def fileAsFixedupString(s):
s = open(s).read()
return string.replace(s,'$','#')
def getHiChars(str):
for chr in str:
c = string.toupper(chr)
if c > 'H':
newstr = newstr + c
return newstr
def bigun:(s)
str = fileAsFixedupString(s)
return getHiChars(str)
Thats refactoring....
> How do NULLs help achieve an informative crash when an uninitialized
> variable wouldn't?
An uninitialised pointer, for example, will point at oome random bit
of memory so if I do:
void f(){
char* sp; // not initialised
char* s2 = "Some crappy string";
strcpy(sp,s2); //<-- tries to copy s2 to wherever sp happens to point!
}
But if sp is set to NULL it will go KABOOM! and segv on the strcpy...
There are literally dozens of C++ standard library calls that will
explode with a NULL input but otherwise return completely
spurious results if fed an unitialised value!
Less predictably for numbers, initialising to zero will often
cause errors like divide by zero failures where using an unitialised
int may give a "valid" but wrong answer... nasty in a nuclear reactor
controller say...
Alan G.
PS The other maintenance programmers favourite is in C/C++
comparisons always put the constant on the left:
if (NULL == sp)
rather than
if (sp == NULL)
that will reliably catch single '=' signs another common C/C++ error.