Jason Whatson

  • Git hub
  • Twitter
  • Skype
  • Linkedin
  • Instagram
  • STAY CONNECTED

Software engineer - Web & Mobile development, cloud computing : Sydney, AU;
  • About me
  • My resume
  • Contact
  • My Blog
  • Quotes
  • My portfolio’s
    • Software portfolio
    • Graphics portfolio
    • Music production & recording

Basic software engineering principles – Don’t Repeat Yourself (DRY)

  • Jun 5, 2013

    Dont Repeat Yourself

    In this post we are going explore 5 different ways to achieve the DRY (Don’t Repeat Yourself) principle when building software and systems.

    Every piece of knowledge must have a single, unambiguous, authoritative representation within a system. – The Pragmatic Programmer

    More code is more complexity which adds a cost of maintainability to the project. For this reason it is very important to always have only one code implementation for a piece of functionality (which is generic enough to handle “simular” functionality) within the system.

    You should never be repeating code or system logic. Because Duplication is Evil! (DIE)

    Depending on the system architecture and programming paradigm, DRY can be achieved in several ways these are listed below:

    1) Generic subroutines

    When you need to write new code which has similar (or the exact same) functionality to previous code already in the project you should take the logic (the previous code) and make it a generic callable sub routine, which can be used for multiple purposes.

    This generic sub routine can cover all the use-cases via parameter values passed to it.

    As in the example below, say we have a e-commerce program. We have the subroutine calcItemPrice which calculates the price of items we sell. The price returned includes $20 for shipping and $2 for a credit card fee.

    Now say at a later date our client or boss comes along and says “if the customer lives in the same country as ours we will offer free shipping”. We could add this functionality through a subroutine like we see in calcItemPriceFreeShipping however this is bad and goes against DRY because we are repeating logic.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    calcItemPrice(itemprice){
        shipping = 20;
        return itemprice + shipping + 2;//two dollar credit card processing fee
    }
     
    /*wrong*/
    calcItemPriceFreeShipping(itemprice){
        return itemprice + 2;//two dollar credit card processing fee
    }
     
    /*correct*/
    calcItemPrice_Correct(itemprice,freeshipping){
        shipping = 20;
        if(freeshipping = true) shipping = 0;
        return itemprice + shipping + 2;//two dollar credit card processing fee
    }

    Why is it bad? Because we are repeating logic, and this has problems as I explain below.

    Now lets say the government comes along at some date in the future and says, “we want to take a tax on all goods sold of 10%”. Instead of having to change code in both sub routines (calcItemPrice and calcItemPriceFreeShipping). We now only have to change it in one (calcItemPrice_Correct).

    Our logic now becomes:

    1
    2
    3
    4
    5
    calcItemPrice_Correct(itemprice,freeshipping){
        shipping = 20;
        if(freeshipping = true) shipping = 0;
        return (itemprice + shipping + 2) + 10%;
    }

    2) Inheritance

    In Object Oriented Programming, inheritance by definition helps you achieve DRY ideology. A child class, extends the functionality of its parent class. The parent class is generic in nature and provides functionality to multiple deriving child classes.

    For example if you have the parent class “Shape” and the 2 child classes “Square” and “Rectangle” , the Shape class can provide the logic to calculate the shapes area (Width x Height) so this logic is not repeated in both the child classes.

    3) Templates and generics

    Templates and generics allows us to implement a algorithm which can work with multiple types of input. Eg, we could have a subroutine called calculateAverage() which given a list of numbers computes the average.

    Using templates / generics (called differently depending on the type of programming language) we can write the algorithm once to work with both peoples ages (integers) and money eg $1.35 (floating point).

    Through templates and generics we eliminate having to repeat the algorithm twice for each data type.

    4) DLL or SO

    At a higher level (beyond a single program), you can achieve DRY ideology across multiple programs. This is what is called Library’s, Shared Objects or Dynamic Link Library (depending on the operating system). The advantages of this is if code in a shared library has a bug, fixing the bug results in a fix across all programs and systems which utilize the library.

    For example, if we are writing a web browser that supports rendering jpeg images. We can use libjpeg (a common library which has the algorithms to decode jpeg compressed images).

    Then perhaps tomorrow we are tasked with writing a music application which shows the album cover of the current song from a jpeg image file. We should use the libjpeg library in this program also.

    Now lets say there is bad and uncommon bug, that renders red pixels black in both our browser and music app when the image has exactly 12321 red pixels . To fix both programs we only have to change code in the commonly shared library (libjpeg) and both programs benefit from this fix.

    5) API provided by multiple systems over a network (service oriented architecture)

    A common example is a web API or webservice, in which 2 systems communicate to each other in HTTP. The systems could talk in any protocol (and theres others much more efficient) but HTTP is very common today.

    Lets say we run a chain of jewellery stores, and customer come in and want a quote on custom jewellery pieces. We are tasked with developing a program which calculates the cost for the person buying the jewellery. Within this program we could have logic that calls a central system (communicating over the internet) to get the current price for gold.

    Another example might be within a bank, all the tellers computers sync with a central time server (a service which is the Single-Source-Of-Truth for the correct time). This is important so that all the transactions are exactly the same and in sync.

    Having a single source of truth for the price of gold and the time is important. And the logic to determine the values are not repeated with each computer within the total system.

    Conclusion

    As seen its important to architect programs and systems to achieve DRY at all levels of a application. Simply put, less duplication of logic is easier to maintain and easier fix when things go wrong.

    Is there any other ways to achieve DRY and Single-Source-Of-Truth, that I have left out? Leave a comment below.

    Don't Repeat Yourself
Jason Whatson

Jason Whatson

Jason is a software developer from Sydney Australia who loves to write software to build great products and help businesses succeed with their goals. Jason is a aspiring entrepreneur who subscribes to the lean startup ideology.

14 Comments

  1. Pete

    −Reply
    June 6th, 2013

    Regarding the “generic subroutines section”…

    * You have hard-coded in the shipping and the credit card fee values, so your subroutine is only generic for consumers that use those fee rates. If these are constant then they should be declared as constants, if they are variable then they should either be parameters or variables on the declaring class.

    * Your test of the freeshipping variable is needlessly verbose. If it is a boolean then you do not need to test that it is true. Logical test expressions like this compile to give an expression tree that evaluates with a boolean result, so you can just as easily use the boolean variable as the logical test in your if without needing to explicitly testing it for true

    * Your assignment of the shipping variable is poorly optimized. You use one branch and potentially two assignment operations where one branch and one assignment could be used (shipping = freeshipping ? 0 : 20;)

    * Your 10% tax rate does not function as expected. Instead of returning the new price including the 10% hike, it returns only the value of the 10% tax, without the value of the original item (“* 10%” should actually read “* 110%”)

    • Jason Whatson

      Jason Whatson

      −Reply
      June 6th, 2013

      Thanks for the code review, however the point wasn’t to produce perfect optimal code. The point was to show how to rewrite a subroutine to handle a simular but different use case. And why having 2 simular but slightly different subroutines is a problem when we need to come back and change code.

      It was written in a my own c-style pseudocode. Not any actual language that can be compiled.

      As you suggested, I have changed my “pseudo tax calculation”.

  2. football

    −Reply
    September 21st, 2014

    It will truly allow you to access to the most up to the minute scores of all playing teams.
    Gene Wojciechowski’s ode to college football is a
    great read. Among those that came out in the wish list is a better line play, addition of team entrances, and crowd
    atmosphere.

  3. Neha

    −Reply
    April 23rd, 2017

    relly important

  4. Http://69.16.224.12

    −Reply
    September 3rd, 2020

    Thanks for any other excellent article.
    The place else may anybody get that kind of information in such a
    perfect means of writing? I have a presentation next week, and I
    am on the look for such information.

  5. lensa69

    −Reply
    September 7th, 2020

    What a information of un-ambiguity and preserveness of precious know-how concerning unexpected emotions.

  6. depoxito.blogspot.com

    −Reply
    September 10th, 2020

    The best in class, Depoxito offer you high-end experience that
    talk to the look and environment of authentic VIP standarts, we find the money for you the
    best captivating to high-level experience of VIPs expect in any top end casino, grand
    conscious casino royale present you the additional
    studio design element including the grand blackjack, offering
    our VIP Customer the best experience of a Salon privee table.

    New style table after that feature across the room in the manner of
    grand roulette upgraded on our provider playtechs mini prestige roulette which delivering more interesting and richer playing experience.
    The new experience contains a sum of seven tables including five
    blackjack tables, one roulette table and one baccarat
    table. Grand alive casino royale has been tall hand-engineered to fit the needs of our customer
    to using it, and contains unique elements that is specially meant
    to maximize the impact value we got from our customers
    and diversify it to the existing network.
    Soon, Depoxito will fabricate an enlarged realism technology on conscious casino
    for our VIP member, these most protester technology ever seen in liven up casino including this augmented reality.
    Which permit players to experience products upon an entire further level which is never seen back literally leaping out of the game and taking the blackjack,
    baccarat, roulette and additional game into the total entire level.

    Depoxito VIP Baccarat, we provide you the
    no question exclusive rouse VIP Baccarat that is played once stirring
    to 7 players at the similar table and our severely trained pretty living baccarat dealer.
    And of course our VIP devotee will tone as if they were truly sitting at one of
    the top casino baccarat table. This immersive gaming experience creates a
    hugely daring tell that our VIP players will find hard to surpass.

    Here is the list of stir casino game that depoxito provide, we have enough money the widest range of liven up casino games
    upon the spread around including : blackjack unlimited, blackjack prestige, roulette, baccarat, poker, hi-lo, sic bo, and grand conscious casino
    royale such as Grand Baccarat, Grand Blackjack and Grand
    Roulette for our VIP member. And of course as a fanatic of Depoxito you can enjoy every the games that we provide to you, all you craving
    to reach is just visit our site depoxito and register it solitary takes
    going on to 3 minutes and subsequently youre pleasing to take steps
    any game that you want.
    Be our VIP, living thing our VIP aficionada of course fixed
    you the best advance you can acquire from us all you compulsion to be a VIP member
    is very easy. all you craving is just keep playing on our site, deposit and
    feign considering a VIP in the same way as the amount that our company
    had written, save playing and our customer bolster will gain access
    to you that you are promoted to become a VIP zealot on our site.

  7. deposaja

    −Reply
    September 12th, 2020

    It’s hard to find experienced people for this topic, but you seem like
    you know what you’re talking about! Thanks

  8. bukadepo.net

    −Reply
    September 17th, 2020

    Thank you a lot for sharing this with all of us you actually understand
    what you’re speaking approximately! Bookmarked. Please additionally visit
    my web site =). We can have a hyperlink alternate agreement among us

  9. depobola

    −Reply
    September 19th, 2020

    Asking questions are genuinely good thing if you are not understanding something entirely, except this paragraph gives
    good understanding yet.

  10. http://linkpkvgame.com/

    −Reply
    October 9th, 2020

    Linkpkv is a service provider of a list of reliable internet poker gambling internet sites
    in Indonesia. The collection of lists of poker websites that we provide are the
    best in Asian countries. The linkpkv group selects all the best sites to be recommended to Indonesian bettors.
    All online poker sites available upon the linkpkv
    site have obtained an official license plus we are here also fully accountable for the set of holdem poker sites that all
    of us provide.

    Linkpkv is a provider associated with a listing of trustworthy
    online poker wagering sites in Indonesia. An accumulation of lists of
    poker sites of which we provide usually are the best in Asia.
    The linkpkv team selects all the best websites to be recommended to Indonesian gamblers.
    All poker sites available on the linkpkv site have furthermore obtained the official license
    and we are usually here also fully accountable for
    the set of poker sites that individuals provide.

  11. Lensamovie

    −Reply
    December 12th, 2020

    View the Best Movie associated with All Time
    What video do you want to be able to watch today?
    Sniper videos may be required about your list.
    This is usually the most fun shooting struggle, where every sniper
    action is always interesting in order to watch.

  12. http://daftarnova88.info

    −Reply
    December 25th, 2020

    Bandar Judi Nova88

    Nova88 is one of the better reliable online bookies in Indonesia which provides been operating given that
    2004. More as compared to thousand individuals register as official people each day at Nova88.com
    for one reason only, specifically we remain dedicated to paying members’ winnings.
    Coupled with the upgraded and a lot more complex platform
    wagering system. Through the Maxbet server migrated to the Nova88 storage space, customers will encounter the gaming encounter for maximum overall gameplay.

Leave A Reply

Leave a Reply Cancel reply

Recent Posts

  • Book Review: Unnatural Selection: Why the Geeks will Inherit the Earth – Mark Roeder
  • Incremental backups to Amazon S3 on CentOS using duplicity
  • An example of how Golang makes concurrent programming easy and awesome
  • Installing NGINX + PHP 5.5 with opcache + MySql on CentOS 6 (LEMP)
  • Basic software engineering principles – Don’t Repeat Yourself (DRY)

Recent Comments

  • Speakerzdn on Book Review: Unnatural Selection: Why the Geeks will Inherit the Earth – Mark Roeder
  • http://daftarnova88.info on Basic software engineering principles – Don’t Repeat Yourself (DRY)
  • Donald Webb on Golang vs JAVA vs PHP: Comparing productivity
  • Donald Webb on Golang vs JAVA vs PHP: Comparing productivity
  • Lensamovie on Basic software engineering principles – Don’t Repeat Yourself (DRY)

Archives

  • March 2014
  • February 2014
  • January 2014
  • November 2013
  • June 2013
  • April 2013
  • May 2010

Categories

  • Book Reviews
  • Programming
  • Software engineering
  • Web hosting

Meta

  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org

About me

I am a software developer from Sydney Australia who loves to write software to build great products and help businesses succeed with their goals.

I am an aspiring entrepreneur who subscribes to the lean startup ideology and creator of “positive affirmations”, a app for Android and iPhone.

Contact

Phone: 0439372293
Email: jason@mindfsck.net

Random Quote

If you’re afraid – don’t do it, – if you’re doing it – don’t be afraid! — Genghis Khan

© Copyright 2021 Jason Whatson. All Rights Reserved.