• Improve code using minimum thoughts

    Think about the most concise, clear and readable way to write the code your writing. Assume you were writing a function to get a file extension (.gif, .doc, etc.). You could be tempted to use string manipulation functions.

    1
    2
    3
    4
    5
    6
    7
    
    $filename = 'file.doc';
    $dot_position = strpos( $filename, '.' );
    if ( $dot_position !== false )
    {
        $extension = substr( $filename, $dot_position + 1  );
    }
    var_dump($extension)

    It’s a lot of code for such a simple task. Beside that, files with multiple dots ( filename.with.dots.html ) won’t be handled properly.

    1
    2
    3
    
    $filename = 'file.doc';
    $extension = array_pop ( explode( '.', $filename ) );
    var_dump($extension)

    The lesson here is to restlessy try to find the best solutions , even when you thought you knew how to accomplish the task. The one-liner above, is more easy to read and much less error-prone. It will work with file with multiple dots or with no extension without any problem. (note: you may want to filter $filename with basename() to avoid directory names dot to interfere).

    I am gonna give another example – imagine you’re trying to print a different string for a bunch of pages on you’re site.

    1
    2
    3
    4
    5
    6
    
    if ( $page_id == 32 || $page_id == 10 || $page_id == null )
    {
        echo 'inactive';
    } else {
        echo 'active';
    }

    While this code is pretty ok, you could note that $page_id is repeated one time for every page you want to set as inactive.

    1
    2
    3
    4
    5
    6
    7
    
    $inactive_pages = array( 32, 10, null );
    if ( in_array( $page_id, $inactive_pages ) )
    {
        echo 'inactive';
    } else {
        echo 'active';
    }

    This way you can add exceptions just inserting a new element in $inactive_pages array. This will make easier refactor the code to read $inactive_pages from a configuration file or from a database.
    In situations where you need to keep your code even smaller you could even write a one-liner (but don’t exceed with them, as many people find them less readable – and often they’re right):

    1
    
    echo in_array( $page_id, array( 32, 10, null )  )  ? 'inactive' : 'active';
    Tags:

Comments on this post

Leave a Reply

  • Security Code :


    + 5 = twelve