in Java, JavaScript, lists, Observations, programming

7 ways to write beautiful code

I’ve noticed that the developer and designer community appear to be obsessed with lists. Is this for a reason that I have somehow missed? For example, over at dZone, 2 out of the top 3 most popular articles are lists: 15 CSS Tricks That Must be Learned and 10 Dirty Little Web Development Tricks – incidentally I liked both articles so I seem to have this obsession myself. OK this is not that many but hey I’ve seen loads of lists elsewhere. Anyway, I thought I would embrace this culture to feed my own addiction and I have detailed 7 (I was only going to do 5, and 6 was out as it’s not prime 😉 ) ways to write beautiful code.

First things first here, I’m talking about pure aesthetics, nothing else. As I have said previously, good code starts by being something other people find easy to read. In fact, Jeff Attwood had a blog post comparing coding to writing citing several sources. I urge you to take a look.

Anyway on to my list.

  1. Return from if statements as quickly as possible.

    For example, consider the following JavaScript function, this just looks horrific:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    
    function findShape(flags, point, attribute, list) {
        if(!findShapePoints(flags, point, attribute)) {
            if(!doFindShapePoints(flags, point, attribute)) {
                if(!findInShape(flags, point, attribute)) {
                    if(!findFromGuide(flags,point) {
                        if(list.count() > 0 && flags == 1) {
                              doSomething();
                        }
                    }
                }
           }
        }   
     }

    Instead we can change the above to the following:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    
    function findShape(flags, point, attribute, list) {
        if(findShapePoints(flags, point, attribute)) {
            return;
        }
     
        if(doFindShapePoints(flags, point, attribute)) {
            return;
        }
     
        if(findInShape(flags, point, attribute)) { 
            return;
        }
     
        if(findFromGuide(flags,point) {
            return;
        }
     
        if (!(list.count() > 0 && flags == 1)) {
            return;
        }
     
        doSomething();
     
    }

    You probably wouldn’t even want a function like the second one, too much going on (see point 7), but it illustrates exiting as soon as you can from an if statement. The same can be said about avoiding unnecessary else statements.

  2. Don’t use an if statement when all you simply want to do is return the boolean from the condition of the if.

    Once again an example will better illustrate:

    1
    2
    3
    4
    5
    6
    7
    8
    
    function isStringEmpty(str){
        if(str === "") { 
            return true;
        }
        else {
            return false;
        }
    }

    Just remove the if statement completely:

    1
    2
    3
    
    function isStringEmpty(str){
        return (str === "");
    }
  3. Please use whitespace it’s free!

    You wouldn’t believe the amount of people that just don’t use whitespace – you would think there was a tax associated with using it. Again another example and I hesitate to say this but this is from real live code (as was the first example), all I have done is change the programming language and some function names – to protect the guilty:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    
    function getSomeAngle() {
        // Some code here then
        radAngle1 = Math.atan(slope(center, point1));
        radAngle2 = Math.atan(slope(center, point2));
        firstAngle = getStartAngle(radAngle1, point1, center);
        secondAngle = getStartAngle(radAngle2, point2, center);
        radAngle1 = degreesToRadians(firstAngle);
        radAngle2 = degreesToRadians(secondAngle);
        baseRadius = distance(point, center);
        radius = baseRadius + (lines * y);
        p1["x"] = roundValue(radius * Math.cos(radAngle1) + center["x"]);
        p1["y"] = roundValue(radius * Math.sin(radAngle1) + center["y"]);
        pt2["x"] = roundValue(radius * Math.cos(radAngle2) + center["y"]);
        pt2["y"] = roundValue(radius * Math.sin(radAngle2) + center["y");
        // Now some more code
    }

    I mean I won’t bother putting an example of how it should be – it should just be sooo bloody obvious. That said, I see code like this ALL the time and so certain people do not find it that easy to judge how to use whitespace. Screw it, for them I will inject some whitespace into the example and it’s shown below.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    
    function getSomeAngle() {
        // Some code here then
        radAngle1 = Math.atan(slope(center, point1));
        radAngle2 = Math.atan(slope(center, point2));
     
        firstAngle = getStartAngle(radAngle1, point1, center);
        secondAngle = getStartAngle(radAngle2, point2, center);
     
        radAngle1 = degreesToRadians(firstAngle);
        radAngle2 = degreesToRadians(secondAngle);
     
        baseRadius = distance(point, center);
        radius = baseRadius + (lines * y);
     
        p1["x"] = roundValue(radius * Math.cos(radAngle1) + center["x"]);
        p1["y"] = roundValue(radius * Math.sin(radAngle1) + center["y"]);
     
        pt2["x"] = roundValue(radius * Math.cos(radAngle2) + center["y"]);
        pt2["y"] = roundValue(radius * Math.sin(radAngle2) + center["y");
        // Now some more code
    }
  4. Don’t have useless comments:

    This one can get quite irritating. Don’t point out the obvious in comments. In the example below everyone can see that we’re getting the students id, there is no need to point it out.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    
    function existsStudent(id, list) {
        for(i = 0; i < list.length; i++) {
           student = list[i];
     
           // Get the student's id
           thisId = student.getId();
     
           if(thisId === id) {
               return true;
           }
        }
        return false;   
    }
  5. Don’t leave code that has been commented out in the source file, delete it.

    If you are using version control, which hopefully you are – if not why not! – then you can always get that code back easily by reverting to a previous version. There is nothing more off putting when looking through code and seeing a large commented out block of code. Something like below or even a large comment block within a function itself.

    1
    2
    3
    4
    5
    6
    
    //function thisReallyHandyFunction() {
    //      someMagic();
    //      someMoreMagic();
    //      magicNumber = evenMoreMagic();
    //      return magicNumber;
    //}
  6. Don’t have overly long lines.

    There is nothing worse than when you look at code that has lines that go on forever – especially with sample code on the internet. The number of times I see this and go ahhhhhhhhhh (I’ll switch to Java for this, as generics makes this particularly easy to do):

    1
    2
    3
    4
    5
    6
    
    public static EnumMap<Category, IntPair> getGroupCategoryDistribution(EnumMap<Category, Integer> sizes, int groups) {
            EnumMap<Category, IntPair> categoryGroupCounts = new EnumMap<Category,IntPair>(Category.class);
     
            for(Category cat : Category.values()) {
                categoryGroupCounts.put(cat, getCategoryDistribution(sizes.get(cat), groups));
            }

    I’m not suggesting the 70 characters width that you had to stick to on old Unix terminals but a sensible limit like say 120 characters makes things a little easier. Obviously if you are putting sample code on the internet and you have it within a fixed width container, make it easier for people to read by actually having it fit in the container.

  7. Don’t have too many lines within a function/method.

    Believe it or not a few years ago now an old work colleague exclaimed that Visual C++ was “shit” as it didn’t allow you to have a method with more than 10,000 lines. I kid you not – well ok I can’t remember the exact number of lines but it was huge. I still see this time and time again where a function/method is at least 50 lines long. Can anyone tell me this is easy to follow? Not only that but it normally forms part of an if statement that you can never find the enclosing block because you are scrolling. To me anything over 30-35 lines is pretty hard to follow and requires scrolling. My recommendation is if it’s more than 10-15 lines consider splitting it up.

This is by no means an exhaustive list and I could have gone on longer – in fact my abolish the switch statement motto would have been number 8 if I had not already mentioned it before. However, it has to end somewhere but feel free to state your own annoyances and maybe I can update the post with some more.

Over and out.

Write a Comment

Comment

 

32 Comments

  1. Great post!, if people on charge of my actual legacy code would read these tips, my life be easier!

  2. For developers not aware of these things, there are Code Complete and Clean Code which belongs on every developers bookshelf.

  3. Thanks Javier. Unfortunately it’s not just legacy code – as I said some of the code in my post is actually from real systems, and this code is less than two years old! As Casper Bang says there are books available, but the biggest problem is likely to be getting the developers in question to read the books – it seems to the case that Programmers Don’t Read Books. Catch 22.

  4. The (economic) value of clean code that clearly communicates it intent is well described in Kent Beck’s book ‘Implementation Patterns’. There he points to ‘the cost of maintenance which is much higher than the cost of initial development’. That’s mostly because of ‘understanding existing code is time consuming and error prone’.

    Therefore i can only agree and only strongly motivate every professional software developer to engage in learning on how to write clean code, be it by reading books, reading foreign code (at least to become sensible to this issue) or blog entries like this one!
    As Casper already mentioned, Uncle Bob’s book ‘Clean Code’ would be a phantastic starting point, since it covers all your mentioned topics and of course far more of them.

    Personally, i would be really interested, how many developers are really keen to improve there skills, no matter if reading books or by other options.
    I often hear that those who regularly read blogs or participate in dev forums, open source projects and so forth are only the tip of the iceberg – personally i wonder if this is really true … therefore it would be really interesting to know about the above mentioned distribution.

    Greetings

    Mario

  5. I disagree with 1.

    I’d prefer it to have the connected together with AND, with nice indentation/spacing.

    I don’t like multiple return points

  6. @Henry Ho
    I agree that in the example I have given anding together would be equally as nice. However, in general, i.e. if we have an else associated with any of the ifs, then this may not work out as nice and I feel that multiple return points normally produces cleaner code. A quick check via Google points to some detailed discussion on this on Stack Overflow, so check it out.

    @Mario
    I was thinking the same thing myself, about how keen many developers are to improve their skills, when Casper Bang posted the book titles. I know from experience a few developers that don’t care at all and also friends have indicated that some people in their work also appear to have little interest. A broader study of this would indeed be interesting.

  7. I think your post is great, and this has nothing to do with the fact the we probably see coding the same way… 🙂

    I have a slight reservation WRT item #2: It is easier to debug the former (the one with the if()) than the latter. That said, I am not sure how to weigh this issue. We certainly don’t want to make all of our code 100% debug-ready.

  8. Henry,

    Although I disagree with on item #1, I definitly accept the fact that these stylistic issues are largely personal. A programmer who is used to writing a certain style of conditionals may find your approach easier.

    Any way, I think that sometimes practices are followed just due to tradition and not due to a concrete reason (I am not saying that this is true for you). One-entry-one-exit gained popularity in the late 60’s IIRC. I believe it was an (exaggerated) counter reaction to goto-based loops. Now, that goto is almost distinct, I don’t see any value in consolidating all my returns.

    I believe that many of this stylistic issue are conditioned by the tools we are using. Next generation IDEs may make some of the recommendations here obsolete. This is better explained here (and, honest to god, this is by no means a self promotion attempt): http://javadots.blogspot.com/2008/12/longer-is-sometimes-better.html

  9. //Please use whitespace it’s free!//

    LOL. 😀

    btw, nice tips.

    //Don’t leave code that has been commented out in the source file, delete it.//

    I think for a development project it is fine. But In my case, I’m maintaining a large web application in which I have to comment old code (should not delete it!) to include new bug fixes. 🙂

  10. I’m not sure about all languages, but the BBP in the .NET languages I know is to only have one return in your method.

    I like #2, I hadn’t thought of that before

    Whitespaces, linespaces and carriage returns in fact are not free. Although they can do wonders for the readability of your code:)

    Thanks for writing the article, some tips are solid, however others I do not believe to be BBPs.

  11. @Greg: how is whitespace not free? It takes up hard disk space for the developers, admittedly, and for interpreted languages that is also transferred to the user, but in general it literally costs nothing except a slight bit of added effort to logically think through how your code is structured… Which is arguably a good thing anyway.

    Even in the case of interpreted languages there are ways to compress files space-wise (most often used with Javascript, of course, but equally applicable to other languages). And compiled languages don’t incur that at all. Interpreted languages will likely pay an extremely small upfront processing impact as they build their AST, but once they have it they’ll walk that unless they have a particularly naive interpreter.

    So I’m curious to know what cost you see whitespace and such as having?

  12. @Gregg – Thanks! Great tips and good advice for cleaner, smoother code. These are all things I consistently point out in code reviews with my team.

    @Veera – “…I have to comment old code (should not delete it!) to include new bug fixes.”
    – I’d still go with deleting it. As Gregg points out, source control is your friend here. Version control is easier with diffs than comment blocks.

    @Greg – I’m pretty certain Whitespace is free. Unless we’re talking about source code file size on disk, which really isn’t a concern.

    In #4, I think that if(thisId === id) { might contain a typo (check the three = signs). Unless this is in a language with which I am not familiar (totally possible, but it looks like C#).

    Thanks again for posting!

  13. @Gregg: Nice post, I agree with the majority of the tips!

    @Veera: I agree with Stuart that versioning should be used instead of comments for tracking history cases.

    @Stuart: Three equals are used in javascript to check both value and type equality: http://javascript.about.com/library/blequals.htm

  14. @Stuart
    Thanks for reading and commenting. I too am puzzled by the cost of whitespace comment so it would have been interesting to hear what Greg was meaning – assuming we are not talking about just disk size, maybe we will never know 🙂

    @Maria
    Also thanks for reading, and for posting the JavaScript === definition with regards to Stuart’s point.

  15. Agree with all comments, especially the early return and whitespace.

    Here is another
    Change
    function isStringEmpty(str){
    if(str === “”) {
    return true;
    }
    else {
    return false;
    }
    }
    to
    function isStringEmpty(str){
    if(str === “”)
    return true;
    else
    return false;
    }

    //– another example
    foreach (string name in nameCollection)
    Console.WriteLine(name);

    Comments: Here is my personal flavour
    // this is a temporary comment, maybe commenting out code, TODO statements, etc

    //– This is a real comment, dont accidently delete me.

    //– SECTION COMMENT (yes, caps)
    //– PRIVATE METHODS

    …and lastly, as related to the comments above. I use them instead of Regions. I dont use region because of too many reasons to list right now.
    regards, Valamas

  16. Great post.

    3. OK white space may or may not be free. If it makes the code easier to read, go for it. You won’t see the compiler complaining much about it; but a fellow developer could if it is difficult to read.
    4. Code should be self explanatory, so daft pointless comments should not be needed. If they are needed, then have a look at your variable naming conventions.
    7. Long methods can pose a problem to understand fully. Most people can only take in around 7 pieces of information at any time. Having a method where you have to constantly think about more than this can lead to confusion and skipping over the code to find the important bits, possibly missing a potential bug. (Magical Seven Psych Review)

  17. Great post and nice article I through.
    Most of my projects followed 1 to 7 steps specially for java code(for code beautification their are many plugh-ins and tools avaliable
    i.e CheckStyle or PMD or IDE in build etc.)
    For JavaScript is there any tool or plugins avaliable?

  18. Hi Praveen. I’m not aware of any plugins for JavaScript, that said, I haven’t really looked much either. Maybe someone else would have a better idea, otherwise you are just going to have to write it beautiful without intervention 😉

  19. You are off base on #1. The problem there is a deeply nested structure, that is very difficult to understand. But trying to understand or maintain a method that is littered with if statements is also very difficult.

    Better solutions would be to use a series of “if-else” blocks, or divide the method into smaller methods.

  20. @Bob – The example was just to illustrate a point, I do say that “You probably wouldn’t even want a function like the second one”, and recommend reducing the method size. I’m not sure else blocks are any easier to read, and probably should be avoided if possible. The way to tidy up the first example would be to put it into smaller functions/methods.

  21. A neat article. I perfectly agree with it.

    I very well practice and preach the same. Very recently I have shared the #4 to my team members here 🙂

    #5 is really nice but at times we may need certain lines just for the sake of comparsion but again its a subjective call.

    #6 – of course the IDEs help us in formatting with the plugins.

    #7 — yes very true. Had been taught the same since academics and following to certain extent!!

    Keep up the good work.

    Cheers,
    Raghavan alias Saravanan M.

  22. Nice post although I don’t necessarily agree with all of the points, I do agree in standard coding practices.

    Coding standards have been an issue I’ve been interested in for over a decade. At university there was such a variety of styles from the student programmers that without standards it would make it extremely difficult to work together on future projects. Marking a myriad of styles would have been hard enough, but putting these styles together to build a project would cost far too much in wasted time and effort.

    When I graduated, the first system I worked on had next to no comments within the code. No comments to describe functions/procedures and no comments to describe the objects. When I mentioned this to a developer I was told \The Code is Self Documenting\. The decision not to fully document and standardize the code I believe led in part to the eventual decision to EOL that system. It was far too difficult to maintain and became overly complicated. There were numerous drives to retrofit comments/standards, it would have been a lot easier had this been considered from the outset.

    Documents such as the Java Coding Convetions: http://java.sun.com/docs/codeconv/ make it a lot easier for people to follow standards. I encourage anyone writing new code to find out the standard conventions for that language and stick to them. If however you are maintaining a legacy system you may find you have to stick to the style that has been used in the past. This really depends on how willing your organization is to do a full regression test of code that’s been modified.

  23. @Eoan yes I do think that you need documentation for functions/procedures and object constructors, but as developers we all know that this is not our favourite task but it should be done I agree 🙂 I think we should avoid frivolous comments though; if in doubt extract it out is my motto.

  24. I’m not sure I agree here… in terms of usefulness, I think it is better to be fast and messy. Release fast, figure out what users actually want, and give them what they want.

    Also important is to write code that avoids bugs. e.g. use asserts liberally. Annoying to read, and often the logic behind an assert might not make much sense, but I think it’s better to overdo asserts at the expense of readability.

  25. A pet hate of mine is magazine code, a legacy from the days when code had to be compressed in to as few pages as possible. You know

    if( Test() ){
    Something();
    } else {
    SomethingElse();
    }

    This doesn’t look so bad as there is little in the way of nesting – you only have to look at the C++ STL to get an idea of how ugly and unreadable this becomes.

    As you say, whitespace is free and makes code a lot easier to read:

    if( Test() )
    {
    Something();
    }
    else
    {
    SomethingElse();
    }

Webmentions

  • Python conventions (Zen of Python but others for other languages) – Quirino´s Projects August 8, 2013

    […] 7 ways to write beautiful code […]

  • 2008年國外最佳Web設計/開發技巧、腳本及資源總結 | QiHi 前端技术分享 August 8, 2013

    […] 來自8為極具靈感的演講者的10個網絡應用技巧 編寫賞心悅目的代碼的7種方法 10個CSS簡寫技巧讓你永遠受用(已翻譯成中文) 10個Web開發小技巧 […]

  • 7 ways to write beautiful code | Web development August 8, 2013

    […] Source Share this:TwitterFacebookLike this:LikeBe the first to like this. This entry was posted in Posts on November 21, 2012 by timurtatjajev. […]

  • Nice code and switches « NRGsoft August 8, 2013

    […] could find any useful tid-bits of information about what other people do to keep code nice. I found this article and I noticed B. B is to return the immediate value of a boolean test instead of testing if the […]

  • 2008年国外最佳Web设计/开发技巧、脚本及资源总结 | Brianguo1980's Blog August 8, 2013

    […] 编写赏心悦目的代码的7种方法 […]

  • What is beautiful sourcecode? | decky wpmu August 8, 2013

    […] 7 ways to write beautiful codeより。 美しいソースコードを書く7つの方法。 例えば、japascriptの関数。 function findShape(flags, point, attribute, list) { if(!findShapePoints(flags, point, attribute)) { if(!doFindShapePoints(flags, point, attribute)) { if(!findInShape(flags, point, attribute)) { if(!findFromGuide(flags,point) { if(list.count() > 0 && flags == 1) { doSomething(); } } } } } } […]

  • 一些Web设计/开发技巧、脚本及资源 | Kevin' Blog August 8, 2013

    […] 编写赏心悦目的代码的7种方法 […]

  • Writing beautiful code « inphamous development August 8, 2013

    […] http://www.equivalence.co.uk/archives/101 Please use whitespace it’s free! You wouldn’t believe the amount of people that just don’t use whitespace – you would think there was a tax associated with using it. […]

  • 国外实用的web设计资源网站合集 | 友友库 - UUCUO.COM August 8, 2013

    […] 编写赏心悦目的代码的7种方法 […]

  • 2008年国外最佳Web设计/开发技巧、脚本及资源总结 August 8, 2013

    […] 编写赏心悦目的代码的7种方法 […]

  • Blog post 03/14/2010 (a.m.) « PN.Truong Phuc's Blog August 8, 2013

    […] 7 ways to write beautiful code | Equivalence […]

  • Auto Post 03/14/2010 (a.m.) « PN.Truong Phuc's Blog August 8, 2013

    […] 7 ways to write beautiful code | Equivalence […]

  • 2008年国外最好Web设计、开发技巧、脚本以及资源总结 | 小卡在线 August 8, 2013

    […] 10个优化技巧 所有网站都应具备的10个SEO元素 编写赏心悦目的代码的7种方法 10个CSS简写技巧让你永远受用(已翻译成中文) 10个Web开发小技巧 […]

  • Best of 2008 for developers: 2008+ tips, tricks, scripts and sources! August 8, 2013

    […] Tips 10 SEO elements all websites should have 10 Web App Tips From 8 Inspirational Speakers 7 ways to write beautiful code 10 Dirty Little Web Development Tricks 15 CSS Tricks That Must be Learned 101 CSS Techniques Of All […]

  • 2008年国外web资源素材帖集锦 - 518工作室 August 8, 2013

    […] 编写赏心悦目的代码的7种方法 […]

  • [转载]2008年国外最佳前端开发技巧、脚本及资源总结 | 软件测试起航 August 8, 2013

    […] 编写赏心悦目的代码的7种方法 […]

  • 我想网 » Blog Archive » 2008年国外最佳Web设计/开发技巧、脚本及资源总结 August 8, 2013

    […] 编写赏心悦目的代码的7种方法 […]

  • 2008年国外web资源素材帖集锦 | ITer August 8, 2013

    […] 编写赏心悦目的代码的7种方法 […]

  • fritz freiheit.com » Link dump for Dec. 12th, 2008 August 8, 2013

    […] 7 ways to write beautiful code | Equivalence (SoftwareDevelopment,Code,Snippet,Programming,Tip,List) […]

  • 2008年国外最佳Web设计/开发技巧、脚本及资源总结 | 紧跟IT潮流 August 8, 2013

    […] 10个优化技巧 所有网站都应具备的10个SEO元素 编写赏心悦目的代码的7种方法 10个CSS简写技巧让你永远受用(已翻译成中文) 10个Web开发小技巧 […]

  • 转载 –2008年最佳Web设计/前端开发技巧、脚本及资源总结 « Eva’s Blog August 8, 2013

    […] 编写赏心悦目的代码的7种方法 […]

  • 5ihappy工作室 » 2008年国外最佳Web设计/开发技巧、脚本及资源总结 August 8, 2013

    […] 编写赏心悦目的代码的7种方法 […]

  • IT Magzine : Best resources for developers: 2008+ tips, tricks, scripts and sources August 8, 2013

    […] Tips 10 SEO elements all websites should have 10 Web App Tips From 8 Inspirational Speakers 7 ways to write beautiful code 10 Dirty Little Web Development Tricks 15 CSS Tricks That Must be Learned 101 CSS Techniques Of All […]

  • Interesting Finds: 2008.12.08~2008.12.11 - gOODiDEA.NET August 8, 2013

    […] 7 ways to write beautiful code […]