octave-maintainers
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: textscan coding style


From: Rik
Subject: Re: textscan coding style
Date: Sun, 24 Oct 2010 21:58:51 -0700

>>
>> +  if ((! strcmp (class (fid), "double") || fid < 0) && ! ischar (fid))
>> +    error ("textscan: first input argument must be a valid file id, or 
>> string.");
>> +  endif
>> +
>> +  if (! ischar (formatstr) && ! isempty (formatstr))
>> +    error ("textscan: second input must be a format specification.");
>> +  endif
>>
Ben,

You've already sorted this out, but sometimes you can use DeMorgan's Laws
to switch the negation of individual terms and make the whole clause more
readable.  For example, your second test (!A && !B) is equal to ! (A || B).
 This involves only a single negation which can be easier to understand
than strings of negatives or mixed positive and negative assertions.
>> Maybe I'm just slow, but I have a harder time understanding negative
>> conditions like the ones above.  Instead of checking the conditions
>> that lead to errors, I find it simpler to write and easier to
>> understand code later if I test the conditions for success instead.
>> For example, instead of the above, I would write something like
>>
>>  if (isa (fid, "double") && fid > 0 || ischar (fid))
>>    if (ischar (formatstr) || isempty (formatstr))
>>      ## ... code to do the real work here ...
>>    else
>>      error ("textscan: second input must be a format specification");
>>    endif
>>  endif
>>  else
>>    error ("textscan: expecting first argument to be a file id or character 
>> string");
>>  endif
>>
Unlike JWE, my brain finds this style harder to understand because it
separates the tests from their subsequent actions.  Most functions are
designed to avoid Garbage In/Garbage Out so they follow a familiar course
of input validation, processing, and output validation/return value
shaping.  Given that fact, I look for blocks of code which roughly mirror
that template.  However, in the code above the input validation is spread
over the entire function.  If the processing is particularly complicated,
the function can extend well beyond a page and by the time I hit the final
else/error clause I've lost any idea what it was connected to.  I also find
that with several potential variables I end up writing the processing code
at level 3 or 4 indent.  This takes 6-8 characters away from the line and
means that more of them have to wrap to avoid exceeding 80 characters.

My 2 cents,
Rik


reply via email to

[Prev in Thread] Current Thread [Next in Thread]