I've inherited code written by someone who wrote verbosely. I keep finding myself saying "I could make this so much smaller, so much more efficient".

I don't find that writing easy-to-read/-maintain code makes inefficient code. This reminds me of a conversation from a few years ago at PerlMonks where I kept trying to figure out why someone insisted on making code smaller. It turned out that they assumed that smaller code was more efficient. That isn't the case.

So I object, in general, to "more efficient" and especially to "much more efficient". Other than for quick hacks, I write efficient code that is "verbose".

Now, if somebody is writing for( $i= 0; $i < @list; $i++ ) { ... $list[$i] ... }, then I'd likely refactor to for my $item ( @list ) [or, if $i is actually used besides for $list[$i], then for my $i ( 0..$#list )] when the time comes. But the main reason for that is neither compactness of code nor efficiency. Looping over lists is less bug-prone than other types of looping.

Note that I'm not claiming that your inheritted code has been written efficiently. It is just that the phrasing made me suspect there might be a "verbose code is slow code" bias.

One of the best routes when refactoring code, especially if you didn't originally write it, is to first flesh out your unit test suite so you are more likely to notice if your "improvements" change the behavior of the code. Writing and running more unit tests also helps you understand the code more fully and may even find some long-standing bugs.

- tye        


In reply to Re: Maintenance vs. Programming style (efficiency) by tye
in thread Maintenance vs. Programming style by apl

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.