Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

IYHO, what do you consider good code?

by stonecolddevin (Parson)
on Jun 13, 2003 at 02:30 UTC ( [id://265561]=perlquestion: print w/replies, xml ) Need Help??

stonecolddevin has asked for the wisdom of the Perl Monks concerning the following question:

Hello good monks, Today I ask you, my fellow monks, to call upon you for advice. I have reached a point where I need to find out what people would consider good coding style (as far as method choices, etc.) in order to start coding "well". In reading simon.proctor's response to my code snippet submission (265232), I feel it is time to kick it up a notch, and I am looking to my fellow monks for help, not only for myself, but to new monks, looking for guidance. Lend a hand if you could, I'll take whatever advice you could give a young monk.
Hi, my name is Dhoss, I like to play Quake 3 arena, I drink Vanilla Coke, and I like long walks on the beach while the sun goes down.

20030613 Edit by Corion: Made link local so that cookies don't get lost

Replies are listed 'Best First'.
Re: IYHO, what do you consider good code?
by theorbtwo (Prior) on Jun 13, 2003 at 03:21 UTC

    Some things that I consider "best pratices":

    • Always use strict; and use warnings; (or -w if you're using perl <5.6). If you do somthing that breaks a warning or stricture, use a no that lets you brake just that one, and in the tightest scope possible.
    • Write your code to be reusable.
    • Write your code to handle at least twice the biggest dataset you expect to ever be handed to it.
    • Expect the project to become more complicated as you are working on it.
    • If you think of somthing while writing that you could do better, but don't have time to do it that way, comment.
    • Comment on input and output of subs at the top of the sub. If the input is a file containing data in a format, comment on it.
    • If you write somthing one way, and then have to go back to it to fix a subtle problem, comment on it, because otherwise you may be tempted to go back later, and end up changeing it back to exactly what it was before.

    Note that best pratices are different when you're writing code for different purposes. I generaly exepect to be the only one who needs to follow my code; that's the environment I work in. Similarly, most of my code is throwaway. That doesn't mean I don't code in reusable subs -- I often find that also makes my code easier to change later when I have to make it do more later. To answer the question posed in the subject, though, which is different: I consider good code to be code that is produced that does what it needs to do, was produced within schedule and budget, and is readable and work-with-able by the people who need to work with it. Note that I say "what it needs to do", not "what it was spec'd to have to do".


    Warning: Unless otherwise stated, code is untested. Do not use without understanding. Code is posted in the hopes it is useful, but without warranty. All copyrights are relinquished into the public domain unless otherwise stated. I am not an angel. I am capable of error, and err on a fairly regular basis. If I made a mistake, please let me know (such as by replying to this node).

      A couple of my tips on style, regardless of language.

      Strategy in comments, tactics in code. Don't explain every statement or operator, but explain the goal of the following few statements or chunk of code. Another suggestion is to write the comments first as you're thinking about what you want to get done, then "translate" the intent into implementation. Don't write clever code which needs explaining-- just accomplish the tactics simply and directly.

      There are only three numbers in Computer Science. Zero, One and N. Zero refers to the complete lack of something: no variable, no method, no capability, no support. One refers to a sole solution: one variable, one method, my way or the highway. N represents an arbitrary scalability, an array which can grow, a method reference, a parameterized technique with room to expand. If you find a need for two, structure your code so it can handle three, four or more. That goes for allocations, methods, strategies, resources, resource types, everything.

      --
      [ e d @ h a l l e y . c c ]

        There are only three numbers in Computer Science. Zero, One and N

        Someone suggested on the london.pm mailing list some time ago that if you ever use a constant other than 0 or 1 you should comment why. I can see his point, although I make exceptions for well-known scaling factors like 7, 24, 60, 3600 and 86400 when mangling times and so on. I also don't bother documenting the constants when I do something like:

        $foo = ($foo & 112) >> 4;
        although that gets wrapped up in a little subroutine whose function is documented, including a pointer to the relevant standard. But just about every other constant I do inded comment. eg, from my current project ...
        $price /= 100; # convert from pence to pounds ... $time += 23 * 3600 # because we're changing timezone

      I agree with most of this, and do my best to follow it in my own code. Lately, though, I have been softening up on the use strict dogma. It's a great idea for you and me, but it might make some more unusual constructions more difficult. Good testing support provides a lot of the same usefulness as strict, but without the compiler errors :-). If your code changes an assumption, then the tests that rely on that assumption will scream bloody murder.

      So here is my slightly modified version of the first point:

      • Always use strict and use warnings unless you know exactly why you aren't using them, and comment on exactly why you don't.

      Update: theorbtwo's qualifier made perfect sense to me. Can't imagine why I forgot it. Whatever, the qualifier is now applied :-)

        I'd say always use strict and warnings. Only turn it off for the sections of code where you need to. If you do think that you need to, consider whether there's a better way of doing the job - there almost always is. You generally only need to turn them off when you're expecting something magical to happen or are doing something Just Plain Weird. Magic and Weirdness are hard to read and so hard to maintain. Even with sufficient comments, someone who has to maintain your code later might just have to rip it out and start again if you try to be too clever. And, as well as commenting the input and output of your subroutines, COMMENT YOUR ALGORITHMS. (added shouty bit later)

        I could agree with that, if you put a ..."and comment on exactly why you don't". However, note that I specificly didn't say that every line of code must comply with every stricture and warning.


        Warning: Unless otherwise stated, code is untested. Do not use without understanding. Code is posted in the hopes it is useful, but without warranty. All copyrights are relinquished into the public domain unless otherwise stated. I am not an angel. I am capable of error, and err on a fairly regular basis. If I made a mistake, please let me know (such as by replying to this node).

Re: IYHO, what do you consider good code?
by Ovid (Cardinal) on Jun 13, 2003 at 03:48 UTC

    A good programmer is akin to a good writer: he or she knows the rules and thus knows when to break them. A bad programmer breaks those rules without knowing why and thus has no good reason for it.

    In other words, good code is a very contextual things. As a result, good code itself is hard to define but for a start on some guidelines you can check out 'use strict' is not Perl. (though I confess that it's a bit dated and I should fix some minor booboos in it -- particularly the part about orthogonal code).

    Cheers,
    Ovid

    New address of my CGI Course.
    Silence is Evil (feel free to copy and distribute widely - note copyright text)

Re: IYHO, what do you consider good code?
by logan (Curate) on Jun 13, 2003 at 04:31 UTC
    I have a unique problem as a coder. I have a lousy memory. Terrible. For some reason, I can remember the names of singles by obscure punk rock bands, but the proper placement of the comma in an open statement refuses to settle into my brain.

    Frequently, I have to revisit code I wrote a year or more ago, and figure out what it does and why it isn't doing it anymore. Ergo, I'm comment guy. Each subroutine I write has a profile at the top something like this:

    #--- # sub get_build_from_server # Takes: server_name, password, path_to_build # Returns: 0 for pass, 1 for fail # Called by: main # Calls: &parse_build_name #---

    The essential concept is to insure that I won't have to spend a lot of time figuring out what a sub does. If I do something "clever", I put in comments explaining why. A few times, I've gone so far as to include the chapter in The Camel Book/Perl Cookbook where the concept was discussed. Also, if the main chunk of code is a loop, it helps to list the exit condition at the top.

    You might also find the Perl Programming guidelines/rules thread instructive.

    -Logan
    "What do I want? I'm an American. I want more."

      Yes, but with proper naming conventions, most of this comment is redundant.

      If your subroutine were something like this:

      sub get_build_from_server { my ($server_name,$password,$path_to_build) = @_; # do stuff here my $success = parse_build_name($path_to_build); if ($success) {return 0;} else { return 1; } }

      --
      Regards,
      Helgi Briem
      helgi DOT briem AT decode DOT is
        Sure, for a simple sub like the one I used as an example. But that's like saying we wouldn't need a big table of contents if only people wouldn't write long books or if people wrote clearly we wouldn't need synopsis or abstracts. Sure, it probably isn't necessary to have a 6 line header for a 6 line sub, but if the sub runs to 20-30 lines, I'd rather have the header.

        The idea is that I'm trying to make it easy to follow program flow. Two years later I want to be able to look at it and instantly see what it does and how it should be called.

        -Logan
        "What do I want? I'm an American. I want more."

      A couple of years ago I wrote a little script to tell me what called what and so on. It grew and mutated and is a crufty mess (not good for code which is meant to help with making other code more maintainable!) but you might want to take a look. It's on my website. Patches welcome, especially any which make it play nicely with the guts of perltidy. I've spoken at some length with the author about using his code, but lack of tuits has meant I've done nothing about it.
      If everyone used these kind of comments it would make the world a better place. I can't think of how many times I tried to reuse a sub that someone else wrote, and had to "dig deep" into the code to figure out what arguments the sub used.
Re: IYHO, what do you consider good code?
by rozallin (Curate) on Jun 13, 2003 at 04:02 UTC
    I’m not sure, being a young monk myself, if I possess much experience and wisdom to give, so you’ll have to forgive me if what I am about to say was not the advice you were looking for.

    Good code to me is code that uses warnings and uses strict, so that you can be warned about problems with your code and prevent your program from accidentally doing something very "silly". I always write my code so that if someone else were to read it, they would understand what I have done and why I have done it by using internal commentary, and using whitespace to make it readable. (Or, if you have as bad a memory as I do, be able to come back to the code 3 weeks afterwards and still be able to see without much contemplation and frustration why you wrote it that way in the first place). My mind is split on the subject of modules; on the one hand I would encourage their use, especially when you are starting to learn Perl, but I think it does make a good programming exercise to see what way you would do it, and compare that with the module and see what could be improved. You never know, you may invent a better wheel.

    As far as learning to code "well" is concerned, the only advice I can give, which would I feel would be more useful to you than myself or others setting down restricting guidelines to follow (and sometimes, as Ovid points out, it is better sometimes to break them if you know why you're breaking them), is to read code and write code. The Perl Monastery has many able programmers who are quite happy to offer criticism for code (your scratchpad is very useful for this), and will be more than willing to help and give you feedback on programs or snippets. It will take time and perseverance (you cannot become a good Perl programmer in 24 hours, or 21 days, or however long the books claim nowadays), and I know that it can be hard at first to accept criticism, however well-intended and constructive the advice may be, for code that you have worked for hours upon and were quite happy with until five minutes ago when $monk pointed out that it could be improved here, here, here and here, but in the end you will be better coder for it. Keep a directory of all the code you have written somewhere, and as you learn new things come back to them, ask yourself what ways they can be improved, what are the other ways you could use to solve this problem?

    I hope this has answered some of your questions, and I hope to see you around.

    --
    rozallin j. thompson
    The Webmistress who doesn't hesitate to use strict;

Re: IYHO, what do you consider good code?
by tachyon (Chancellor) on Jun 13, 2003 at 03:24 UTC

    Good code

    1. By definition anything that works is better than anything that does not
    2. Anything that only works most of the time is a nightmare (but see 1)
    3. Some coding styles predispose to 1) whereas some predispose you to 2)

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Software Qualities
by jeffa (Bishop) on Jun 13, 2003 at 12:58 UTC
    I can't remember who created this list, but this is what i was taught in college. This is a very generic list of qualities, but one that should be reflected upon often:
    correctness
    does the software behave as specified?
    reliability
    can we depend upon this software?
    robustness
    how well does software behave beyond what it is required to do?
    performance
    is the software efficient? scalable?
    user friendliness
    human-computer interaction
    verifiability
    test test test!!
    maintainability
    be sure that whomever takes over your code does not know where you live
    resuability
    can others use this wheel for their needs?
    portability
    does it run on other platforms? will a lot of changes be required to do so?
    understandability
    can others understand your code? did you try to ensure that others can understand it?
    interoperability
    how well does this software work with other software?
    productivity
    measurement of the development process, not necessarily how productive the software itself is
    timeliness
    ability to meet your deadline
    visibility
    is the documentation clear to internal and external users of the software?

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
Re: IYHO, what do you consider good code?
by kabel (Chaplain) on Jun 13, 2003 at 04:35 UTC
    you may consider the opposite approach as well:

    looking at bad code, and understanding why it is bad

    i.e., you can use the super search facility to get some examples.

    the important thing is to get commented code. if you can't imagine why that particular code is bad, a clarifying word will open your eyes and an 'aha' effect happens.
Re: IYHO, what do you consider good code?
by helgi (Hermit) on Jun 13, 2003 at 10:53 UTC
    To me, apart from the various points people have made about using warnings and strictures, structured code, using subroutines and so forth, the most important rule is:

    Use meaningful names!

    This applies to variables, subroutines, loops, filehandles, everything.

    Always take a little extra time, 10 seconds or so, to name your variables well.

    Good names can often make comments redundant and unnecessary.

    I hope I never ever have to maintain a program again that's full of variables named @tmp, $i, $n, $ldr, %hash or subroutines named process or run and all the other meaningless crap people foist off as names.


    --
    Regards,
    Helgi Briem
    helgi DOT briem AT decode DOT is

Re: IYHO, what do you consider good code?
by castaway (Parson) on Jun 13, 2003 at 08:56 UTC
    Good style? I'd consider properly indented and commented code good style, indenting especially helps you or other people to understand what is going on later.. Also try not to re-use big chunks of code, one or two lines repeated is ok, but if you find yourself formatting text a certain way, or similar, write a sub for it.. It helps later if you need to change how that works/looks..

    Can't think of much else at the moment, I'm not a 'strict' person (tho warnings is good).. Whatever works :)

    I'm surprised no-one has mentioned the style guide yet!

    C.

    # This script does not use strict, because most of mine don't
    # (Is that enough of a 'why no strict' comment? ,)

Re: IYHO, what do you consider good code?
by allolex (Curate) on Jun 13, 2003 at 06:02 UTC

    From a learner's point of view, good code has a lot to do with intuition. It is not true that all good code is understood intuitively. This is due to the necessity of knowing a bit about idomatic Perl and allowing your intuitions to develop before you can really understand someone else's code. Of course, it also helps to know how that person thinks ;)

    Unfortunately, the average learner doesn't know enough to have developed good intuition, so comments have to play a role somewhere. Perl can appear to be cryptic because of the shortcuts (e.g. syntactic sugar) that have been built into the language. And then there's the tendency to solve all problems with regular expressions...

    So for me, good code is code that is clear once you read it (two or three times) and that has explanations for the stuff that is not so clear.

    --
    Allolex

Re: IYHO, what do you consider good code?
by kodo (Hermit) on Jun 13, 2003 at 06:33 UTC
    Hi Doss,

    for me good code means what was already mentioned but also to have good structured code. Don't use to much subs, but try to give it a structure which also helps to make it reusable. If it's getting big think about putting parts of the code you might want to use again in a small module etc...
    Also learn to have a strict an clean style, which you always use and not change to often. I personally prefer to have a more K&R-styled style than the usual perl-style...
    Also only use tabs for indenting and not for lining up stuff etc. Have a look at perltidy if you can't manage to have a strict style yourself.

    kodo
Re: IYHO, what do you consider good code?
by adrianh (Chancellor) on Jun 15, 2003 at 00:40 UTC

    I always liked Kent Beck's list that code is simple enough when:

    • It runs the tests;
    • It expresses every intention you need to express;
    • There is no duplicated code;
    • There are minimal classes and methods.
Re: IYHO, what do you consider good code?
by kutsu (Priest) on Jun 13, 2003 at 17:29 UTC

    I have two things to add to the tremendous advice give by the other monks. Remember to test, test, test, before something goes into production. Also, look back at old code when you have a quiet moment, this will allow you to see how much you've learned, and if you improve it, esp. if boss wasn't expecting it, will usually impresses people. This may not be coding style, but debugging and maintaining style, which I think is important as well.

    Update: Added last sentence

    "Pain is weakness leaving the body, I find myself in pain everyday" -me

Re: IYHO, what do you consider good code?
by hsweet (Pilgrim) on Jun 13, 2003 at 20:17 UTC

    After grading a bunch of high school kids trying to write a program that opens a file, runs a foreach loop with a simple regex after a 20 week course my standards are quite low. Most of them could not even say use strict when I asked them to use strict. In writing

    stict and warnings are good thing most of the time. good comments all the time.

    Caring enough to think about it is probably as important as anything else.

    Time flies like an arrow, fruit flies like banannas

      Thank you so much every one. I have saved this page for later study, and I will take all of this to heart. I appreciate your input, and I will code accoriding to my interpretations of it. Hopefully, someday I'll become an experienced enough monk to give advice such as the advice given above. Have a lovely day :-)
      -Dhoss
      "Ergo!!! Vis a Vis!!! Concordidly!!!! Mr. Timberlake. I'm apologize, I don't usually like to use my big voice".
      -Will Ferril, MTV Movie Awards, as the Architect
Re: IYHO, what do you consider good code?
by one4k4 (Hermit) on Jun 13, 2003 at 15:46 UTC
    Turn off debug statements. I don't know how many times I've had to read through apache error_log files and determine what/where/why/when some piece of code written by somebody here is writing to stderr..

    I find it useful to do things like warn $sth when developing, but forgetting to remove those bits leads to production log file messes.

    :) Just my $0.02

    One4k4 - perlmonks@poorheart.com (www.poorheart.com)
      Usually when writing debug code, I will use this type of statement (for just the reason above)...
      use constant DEBUG => 1; ... ... warn "Foo" if DEBUG;
      or
      use constant DEBUG => 1; ... ... my $debugsub = DEBUG ? { warn @_ } : {}; #need to fix stack trace... ... ... &$debugsub(foobar);
      Allows turning it off in one location. Just my $0.02.

        Make it an environment variable and it's even easier:

        BEGIN { $ENV{DEBUG} = $ENV{DEBUG} ? 0 : 1; } use constant DEBUG => $ENV{DEBUG};

        Update: Good points both responses, though I'm slightly happier with the BEGIN block from a maintenance standpoint.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://265561]
Approved by Zaxo
Front-paged by diotalevi
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (4)
As of 2024-03-19 08:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found