<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Henry Coles on Medium]]></title>
        <description><![CDATA[Stories by Henry Coles on Medium]]></description>
        <link>https://medium.com/@henry.coles?source=rss-26865c0b6fc6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8y6aK727LwROiILxhXMkkg.png</url>
            <title>Stories by Henry Coles on Medium</title>
            <link>https://medium.com/@henry.coles?source=rss-26865c0b6fc6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 19:59:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@henry.coles/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Green tests and ham]]></title>
            <link>https://medium.com/ncr-edinburgh/green-tests-and-ham-b4694f90f7eb?source=rss-26865c0b6fc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4694f90f7eb</guid>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Henry Coles]]></dc:creator>
            <pubDate>Wed, 08 Nov 2017 10:48:11 GMT</pubDate>
            <atom:updated>2017-11-08T10:48:11.277Z</atom:updated>
            <content:encoded><![CDATA[<h4>In which I attempt to make an nuanced point in the style of Dr Seuss</h4><p><em>So you have code to be written and you know it is best<br>when you are writing that code to start with a test.<br>You’ve heard this from Charlie and Richard and Sue<br>and all kinds of people so you know it is true.</em></p><p><em>And also these people, these Charlies and Sues,<br>have all sorts of other things to say about tests too.<br>They’ve told your that tests should mainly be small<br>that the thing that you test should not be the program’s total and all.</em></p><p><em>(Well ok, do that a little.<br>DO test some things that are BIG<br>but aim on the whole for a great pyramid.<br>With lots of small things at the bottom<br>and some big ones on top<br>and things in the middle which both big and small they are not.)</em></p><p><em>And so you have done this, done like Charlie and Dick,<br>built a great pyramid on top of very small bricks.<br>But when it came time to refactor some years down the line<br>did all those tests that you wrote make sure that things worked out just fine?<br>Or did you hit problems?<br>Were things not all ok?<br>Did you find that your tests just got in the way?</em></p><p><em>So how did this happen?<br>What’s going on?<br>Could it be that Charlie and Sue were both totally wrong?</em></p><p><em>Like most things in life it’s not as simple as that<br>your head is for more than just holding your hat.<br>Things are all nuanced and complex and cruel<br>and you can’t get results following just one simple rule.<br>All of that mush between your ear and your ear<br>must be constantly thinking, “what’s going on here?”</em></p><p><em>Writing tests first is all well and good<br>(and if you’ve never tried it then really you should).<br>But much more important than when it was written<br>is what that test looks like and what it does when its bidden.</em></p><p><em>If you have tests with fingers in the guts of your code<br>those tests are tied to those guts and won’t want to let go!<br>When your code is gutted those tests will always pull back <br>(whether the change is elegant or some horrid hack).</em></p><p><em>So never write tests that put fingers in guts<br>(in short beware coupling it really does suck).<br>But coupling is subtle and not always easy to see<br>(and nasty and viscous it just won’t leave us be).<br>And when you can’t see it it’s hard to get rid<br>which brings us back to that great pyramid.</em></p><p><em>Now it’s true that the things at the bottom might well be small<br>but that’s not the reason that they’re down there at all.<br>With smallness comes a danger that’s hard to explain<br>but that danger and putting fingers in guts is the same.</em></p><p><em>Things from the classroom, those cool algorithms<br>those things are small and are usefully hidden<br>in all of the programs that we want to write<br>they’re tiny, and hidden and used out of sight.</em></p><p><em>Those things are general, and rarely will change<br>(though we might swap them for others where the interface is the same).<br>Small things like those are all nice and stable<br>not like the small things in our code we often test just cos we’re able.</em></p><p><em>Our small things are different, they’re just part of the guts<br>of our webapps and services and front ends and such.<br>Our small things will change as we change our designs<br>they’ll vanish, disappear come to the end of their times.</em></p><p><em>If our tests are mainly written in terms of those<br>they’ll constantly be changing and causing us woes.<br>If these are mainly the tests that we choose to write <br>then the behaviour we want from our app drops out of sight.</em></p><p><em>And when those tests are gone (along with the units they test) <br>then ones at the top will be the only ones left.<br>The ones at the top that are too slow to run<br>too flakey and awkward to help get anything done.</em></p><p><em>The base of that pyramid isn’t defined by size<br>it’s defined by the things for which those tests should strive.<br>Tests at the bottom they have to be fast and easy to run<br>(when we make a change running them is step number one)<br>Fast alone of course just isn’t enough,<br>the tests at the bottom must do other cool stuff.</em></p><p><em>Whenever we run them the result must be always the same<br>(if that isn’t the case there’s no end of pain).<br>So these tests are fast and they run anywhere <br>(so any coder can run them without hours of despair).</em></p><p><em>So why is it important that the things they test are small?<br>It isn’t important, just not important at all!<br>What is important is that the thing they test <br>is just one sensible thing picked out of all of the rest.<br>One thing with behaviour that isn’t too likely to change<br>a thing that </em><strong><em>must</em></strong><em> happen no matter how our code is arranged.</em></p><p><em>Of course things always change, we know that they do<br>so some of the bricks at the bottom will always have to change too.<br>Some will go missing, some might leave gaps.<br>All we are saying is that perhaps,<br>if we stop thinking of size when writing our tests<br>things are more likely to work out for the best.</em></p><p><em>Before I go I must mention the one thing that we lose<br>by forgetting about size in the units we choose.<br>When we test small things it’s easy, when something goes wrong<br>to point to the bit where the problem comes from.</em></p><p><em>With big things that’s harder as there’s more to look through<br>so there is an advantage to testing small things its true.<br>But on balance, often (if we must make a choice)<br>it is the test suite built on stable foundations that will make us rejoice.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4694f90f7eb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ncr-edinburgh/green-tests-and-ham-b4694f90f7eb">Green tests and ham</a> was originally published in <a href="https://medium.com/ncr-edinburgh">NCR Edinburgh</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Early exit]]></title>
            <link>https://medium.com/ncr-edinburgh/early-exit-c86d5f0698ba?source=rss-26865c0b6fc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c86d5f0698ba</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Henry Coles]]></dc:creator>
            <pubDate>Fri, 15 Sep 2017 10:26:04 GMT</pubDate>
            <atom:updated>2017-09-15T10:26:04.366Z</atom:updated>
            <content:encoded><![CDATA[<p>Although it’s quite short, the most popular section of <a href="http://javabook.ncredinburgh.com/">Java for small teams </a>(as judged by the number of comments on reddit) is the “bad advice” section at the end.</p><p>The idea of this section was to capture some of the “negative value” advice and rules that are sometimes followed and enforced without question. If you’ve ever been in the situation where you’ve been asked to do stupid things in the name of “best practice” you can understand its appeal.</p><p>I had Hungarian notation imposed on me in the past and in my early career forced myself to follow the single exit point rule before finally seeing sense.</p><p>As a recovered single-exit-point programmer I thought I had a pretty good grasp of arguments for and against it, but this item generated some interesting community feedback with points I hadn’t considered.</p><h3>Single exit point rule recap</h3><p>The single exit point rule is the idea that a method or function should only ever return from one location. The idea has been around since before Java existed and is an enforced constraint in some languages.</p><p>It sounds pretty sensible. If a method only ever exits from one place it must be easier to understand right?</p><p>Perhaps.</p><p>If your method is 100 lines long knowing it can only exit right at the end probably is useful. But we don’t write 100 line methods any more.</p><p>Do we?</p><p>What happens if you tell a Java programmer that all methods should have only one return statement?</p><p>They will probably write something like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95c6858f4d36301db28287f244374c97/href">https://medium.com/media/95c6858f4d36301db28287f244374c97/href</a></iframe><p>Doesn’t look too bad does it?</p><p>How about if we <em>don’t </em>instruct them to have a single exit point?</p><p>You’ll probably get something like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de62e6a96536fbb45f219a0218f92102/href">https://medium.com/media/de62e6a96536fbb45f219a0218f92102/href</a></iframe><p>What’s wrong with it?</p><p>Nothing.</p><p>In fact it’s a little clearer than the single exit point method.</p><p>The difference is minor, but in the multi exit version it is slightly clearer what happens when x isn’t greater than 0 as the returned value is declared at the point of return. In the single exist point version we have to scan up a few lines to the declaration.</p><p>In the single exit point version we also have a tiny bit of bloat in the form of the extra retVal variable. We assign to it and then over-write which is a little ugly.</p><p>Other versions of this logic using both single and multiple exit points are possible.</p><p>For example if we add an else statement we can make the single exit version a little clearer and stop overwriting the initial value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81531418fef519a2e0874cf416c95f0d/href">https://medium.com/media/81531418fef519a2e0874cf416c95f0d/href</a></iframe><p>Is this now better than the multi-exit version?</p><p>No.</p><p>This is the problem with the single-exit point rule — applying it as a universal rule doesn’t make things any better, but might make things a little worse.</p><p>If we look around for more complex examples we’ll find some where the single exit version is clearer, some where the multi exit version is clearer and countless more where they are about the same.</p><p>Martin Fowler and Kent Beck put things nicely in “Refactoring: Improving the Design of Existing Code”</p><blockquote>“… one exit point is really not a useful rule. Clarity is the key principle: If the method is clearer with one exit point, use one exit point; otherwise don’t.”</blockquote><h3>Community feedback</h3><p>It turns out there are still a few proponents of the single exit point rule out there, and we got some good feedback from Jean-Baptiste Giraudeau who works on the <a href="http://www.functionaljava.org/">Functional Java</a> and <a href="https://github.com/derive4j/derive4j">derive4j</a> projects.</p><p>As you can tell from the projects he’s involved with he has a background in functional languages. His first point was that enforcing having only a single exit point seems to be working out pretty well for modern functional languages like Haskell.</p><p>This is true and prompted me to think about why it works out well in those situations but not for Java.</p><p>The answer is, of course, that they are different languages.</p><p>Functional languages are expression based (i.e everything returns a value), while Java code consists largely of statements.</p><p>To demonstrate the difference lets look at some Scala code. Because in Scala everything is an expression the following is valid.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/189cb27eeea2efef92b9798260900939/href">https://medium.com/media/189cb27eeea2efef92b9798260900939/href</a></iframe><p>The if statement returns a value, so we can assign it to a variable. In Java this would be a syntax error as if is a statement and returns nothing.</p><p>A Scala version of our example function might therefore look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cc3e2b7702682220cb624fba5b4c43a/href">https://medium.com/media/7cc3e2b7702682220cb624fba5b4c43a/href</a></iframe><p>It looks a lot like our earlier single exit point Java example, except we don’t have to create an extra variable to store the result.</p><p>Of course Java isn’t made entirely of statements, it has some expressions as well.</p><p>Which brings us to this interesting single exit point implementation that I hadn’t considered.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f93602e414b6bfe40e9fc76e98c6be6/href">https://medium.com/media/2f93602e414b6bfe40e9fc76e98c6be6/href</a></iframe><p>This uses Java’s ? operator which forms an expression in exactly the same fashion as if does in Scala, returning the value from either side of the branch.</p><p>I rarely use the ? operator as I find it overly terse, but it lets us express this particular logic quite nicely, if a little tersely.</p><p>Is this clearly superior to our earlier multi exit version?</p><p>No.</p><p>Personally I find the multi exit version much easier to read, but that is in part because I’m not used to this more compact idiom. If I’d been writing like this for a little while I’d probably be able to make sense of the ? version at a glance.</p><p>Although its statement based core isn’t going anywhere, the introduction of Lambdas and streams in Java 8 means we are all going to be writing a greater proportion of expressions in our code. As we’ve seen expressions and short single exit point methods fit together well.</p><p>It still won’t make sense to decree that all methods should be single exit, but I suspect we will all naturally write a greater proportion of them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c86d5f0698ba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ncr-edinburgh/early-exit-c86d5f0698ba">Early exit</a> was originally published in <a href="https://medium.com/ncr-edinburgh">NCR Edinburgh</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Into The Lair of the Beast]]></title>
            <link>https://medium.com/ncr-edinburgh/into-the-lair-of-the-beast-e2dde945abb5?source=rss-26865c0b6fc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2dde945abb5</guid>
            <category><![CDATA[management]]></category>
            <category><![CDATA[methodology]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Henry Coles]]></dc:creator>
            <pubDate>Mon, 21 Aug 2017 15:24:27 GMT</pubDate>
            <atom:updated>2017-08-23T08:04:50.768Z</atom:updated>
            <content:encoded><![CDATA[<h4>A true story from a previous life</h4><p>A few months ago, <a href="https://twitter.com/0hjc/status/867411485202333698">I shared a tale on Twitter</a> that has apparently now made it into the course material on requirements engineering at <a href="https://www.tum.de/en/">TUM</a>. I thought I’d share it again here in a less tweety form.</p><p>What follows really happened. One or two minor details have been changed in the name of artistic licence.</p><h3>My Tale</h3><p>Many moons ago, in more fearful times, I served the beast we called “<strong><em>The Business</em></strong>”. The beast held all in its thrall. Our waking hours were spent tending to its needs. Feeding the beast so that it might grow and consume more worlds.</p><p>One day, the <strong><em>Great Waterfall</em></strong> delivered to my weary band a mighty tome — “<strong><em>The Business Requirements Documen</em></strong>t”.</p><p>It was prepared by the <strong><em>cleric</em> </strong>class that consorted with the beast and interpreted its whims and desires. The Great Waterfall had delivered many such tomes before. After each delivery my band would enter upon a quest to fulfill the Beast’s desires.</p><p>As always the tome was cryptic and strange. The pages held many words, but little meaning. Only one thing was clear from the clerics’ writings, if the quest were not complete by the<strong> setting of the third moon, all would die</strong>.</p><p>Again.</p><p>I wondered, as I had many a time before, why must all die by the third moon. Could the beast not show mercy?</p><p>I was but a lowly warrior. It was not my place to question the Beast. Only a cleric might approach it. Only a cleric could hope to interpret the Beast’s whims and translate it to the language of mortal man.</p><p>Our leader began to plan. The quest was long and the third moon near. We would hire mercenaries so that we could go faster.</p><p>Again, we would take the dangerous short cut through the <strong><em>forest of Hack</em></strong>. I did not like this plan, but our leader was deaf to my pleas.</p><p>The mercenaries more often dropped their axes on our feet than slayed the enemy. The swamp of technical debt that lay between the forest of Hack and our goals seemed deeper and more treacherous with each passing year.</p><p>Perhaps if we stopped and built a bridge over the <strong><em>Chasm of Known Issues</em></strong> we might complete the quest faster and with fewer dead?</p><p>But no. The beast must be fed and the clerics approved of the plan. We would proceed as before.</p><p>I was despondent, but a plan began to form in my head. A desperate plan. A suicidal plan. A plan that was to end in both enlightenment and great sadness.</p><p>I would speak to the Beast.</p><p>Abandoning my band and ignoring the commands of my leader, I sneaked into the Beast’s lair. The Beast was surprised at my approach, but did not show anger that it was addressed by a lowly warrior.</p><p>I asked it, “Why must all drop dead if the quest is not complete by the rising of the third moon?”</p><p>And the Beast explained to me the terrible truth.</p><p>“By the third moon,” The Beast explained “my supply of stationery will run low.”</p><p>“When the quest is complete, paragraphs 3 and 4b of the standard disclaimer must be updated.”</p><p>“It would be a great waste to print copies of the old version again just before the quest was complete. So the quest must be completed just before the next print run.”</p><p>Knowing now the truth I returned to my band and told them what I had discovered.</p><p>There was no need for us to hire mercenaries. No need to enter the forest of Hack. No need to cross the swamp of technical debt.</p><p>No need for us to die.</p><p>For less than it would cost to hire a mercenary for one day we could print the Beast all the stationary it could desire.</p><p>But of course I was young and foolish and did not understand the way of the world.</p><p>The clerics were angry - I should not have spoken to the Beast and could not possibly have comprehended what it said. They had faithfully transcribed all its utterings. Could I not read what the Great Waterfall had delivered?</p><p>The quest must be complete by the third moon for that was what the requirements said. We continued to the forest of Hack more weary than before knowing that we must die to save three bronze coins.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2dde945abb5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ncr-edinburgh/into-the-lair-of-the-beast-e2dde945abb5">Into The Lair of the Beast</a> was originally published in <a href="https://medium.com/ncr-edinburgh">NCR Edinburgh</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I once saved half a million dollars with a one character code change]]></title>
            <link>https://medium.com/ncr-edinburgh/how-i-once-saved-half-a-million-dollars-with-a-one-character-code-change-31f3fdca1f68?source=rss-26865c0b6fc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/31f3fdca1f68</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Henry Coles]]></dc:creator>
            <pubDate>Fri, 21 Jul 2017 10:56:36 GMT</pubDate>
            <atom:updated>2017-07-25T08:46:01.289Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Or four one liners every Java programmer should know</em></h4><p>I have a programmer war story to share, but first a bit of more recent context.</p><p>Last year when we published the first draft of ‘<a href="http://javabook.ncredinburgh.com/">Java for small teams</a>’ a commentator on Reddit took exception to the section <a href="https://ncrcoe.gitbooks.io/java-for-small-teams/content/style/10_optimise_for_readability.html">‘Optimise for Readability’</a>.</p><p>This section contains the widely circulated advice that you should worry first about whether your code is clear, correct and readable rather than whether it performs well.</p><p>Not too controversial in 2016 and still not controversial in 2017.</p><p>Experience has taught us that micro-optimisation often has little or no beneficial effect on performance, but does make code harder to understand and maintain.</p><p>Real performance problems are often in places we don’t expect them to be. The effective way to speed up an application is to profile it and remove the bottlenecks you find. Most often the changes required to remove these bottlenecks are nothing like the micro-optimizations we typically imagine in advance.</p><p>So what was the objection? The redditor helpfully commented:</p><blockquote>“no no no”</blockquote><p>and cited this <a href="http://ubiquity.acm.org/article.cfm?id=1513451">article by Randall Hyde</a> in the ACM.</p><p>I’d not seen the article before, but it makes some good points. It doesn’t however argue that premature optimisation is something we should do.</p><p>Its main thrust is that “premature optimization is the root of all evil” has been used as an excuse not to optimize at all, or to leave it as an item to be addressed late in development. Like other things saved until the end it then does not happen in any meaningful way.</p><p>I think this is entirely true. It’s a mistake I’ve made plenty of times. I’ve worked on many projects where we didn’t profile or performance test until late in the day. We often shipped slow, memory hungry code.</p><p>Sometimes it was easy to fix incrementally, sometimes it wasn’t. Concentrating first on readability and performance second only works if we remember the second bit.</p><p>While micro-optimizing each individual method is likely to result in un-maintainable code and little performance benefit, not thinking about performance at all can also end badly.</p><p>Over time I’ve become a little better at this. When I start up a new project I make sure that as soon as we have a walking skeleton in place, we create some sort of test that looks at what happens when the code is placed under load.</p><p>These tests serve a very different purpose than the performance tests that I first encountered in my early career. Those tests tried to model realistic loads and took place in realistic environments.</p><p>They tried to answer questions such as:</p><blockquote>“How much load will our production system be able to handle?”</blockquote><p>Or</p><blockquote>“What hardware should we advise our clients to run our software on to deal with their expected load?”</blockquote><p>These remain important questions, but the tests I write don’t help answer them.</p><p>They are still useful though. In the same way that a small unit tests answer difference questions than a realistic end to end system test, small load tests and micro benchmarks answer different questions to realistic performance tests.</p><p>Small performance tests can give us early answers to questions like:</p><ul><li>“Are there any obvious bugs that become visible under load?”</li><li>“Did that code change make things slower?”</li><li>“Did that code change actually make things faster?”</li><li>“Where are the bottlenecks in things I can easily change?”</li></ul><p>There may well be larger problems and bottlenecks in the overall system and the infrastructure to which it is deployed that these tests will not reveal, but having some imperfect information early is better than having none at all.</p><p>Some care has to be taken as making these tests too small also has problems.<br>Writing micro-benchmarks for every function is a great way to waste time while achieving little of any value. The first tests I write now tend to be as big as they can be while still being convenient to run against locally modified code.</p><p>There is some great tooling out there that makes writing load tests easy. I’ve only used it a handful of times, but I’m already a big fan of <a href="https://github.com/gatling/gatling">Gatling</a>. For writing small micro-benchmarks, <a href="http://openjdk.java.net/projects/code-tools/jmh/">JMH</a> is the go to tool (but beware the previous warning about making tests too small).</p><h3>My one character change</h3><p>Another good point raised by the article is that sometimes micro-optimizations do matter.</p><p>Not often, but sometimes.</p><p>Randall provides the bit of the Hoare quote that everyone forgets:</p><blockquote>“We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.”</blockquote><p>Along with the full quote, we’re prone to forgetting that 3%.</p><p>Which brings me to the story from my past.</p><p>I was once part of a team that inherited a sprawling application originally written in Java 3 (or 1.3 as we called it back then).</p><p>Our team was agile in the sense that we called our meetings stand-ups and developers were empowered to change and improve things. As long as the enterprise architects agreed to it. And as long as we spent a number of weeks writing documents first.</p><p>The code was awful in ways that were entirely new to me but, despite the best efforts of the architecture team, we managed to gradually improve things.</p><p>But there were still lots of problems, and some of them began to impact the business plan.</p><p>The original developers of the application had not written any performance tests and had never profiled it, but performance tests were occasionally run by contractors using expensive proprietary tools and the results were not good.</p><p>The main bottlenecks were in third party components that the vendors had proven incapable of improving. In endless meetings it was argued that the performance was “good enough”. And it had to be because we couldn’t fix it.</p><p>And there were other problems.</p><p>The application required what was (for the time) a large heap of 1.5 gig. Although the theoretical maximum size for a 32bit heap is 4 Gigabytes, in practice the largest heap we could allocate on a Windows server (yes it ran on Windows) was about 1.5 Gig.</p><p>So we were right up against a hard limit.</p><p>This was a huge problem, as we couldn’t roll out new features that might increase the heap size any further. After lots of meetings and discussion the ‘Enterprise Architects’ came up with a plan.</p><p>It involved some expensive re-architecturing.</p><p>It required some very expensive new servers.</p><p>It required a lot of even more expensive new licences for the third party components.</p><p>It required delaying the features the business wanted until all this work was done.</p><p>But it had to be done or business couldn’t continue.</p><p>While the planning for this huge project was going on I fired up a profiler and started having a play around.</p><p>As well as the profiler I was armed with an early version of the excellent E<a href="http://www.eclipse.org/mat/">clipse memory analyzer</a>.</p><p>After a bit of analysis I made a single character changed to the code base.</p><p>This reduced the peak memory consumption of the application by about 60%, reduced GC pause times and probably also brought us slightly closer to world peace, but I had no way to measure that.</p><p>What was the change?</p><p>I changed this:</p><pre>Set&lt;Thing&gt; aSet = new HashSet&lt;Thing&gt;();</pre><p>To this:</p><pre>Set&lt;Thing&gt; aSet = new HashSet&lt;Thing&gt;(0);</pre><p>Most of these sets were empty for the entirety of their life, but each one was consuming enough memory to hold the default number of entries.</p><p>Huge numbers of these empty sets were created and together they consumed over half a gigabyte of memory. Over a third of our available heap.</p><p>My simple change set the initial capacity to 0, greatly reducing the overhead.</p><p>There will have been a small corresponding performance cost when something was added to the sets as they would need to be re-sized, but this was dwarfed by the reduction in GC cost.</p><h3>Good micro-optimizations</h3><p>My tiny micro-optimisation had a small cost in terms of code readability (“What’s that (0) doing there?”) but paid for this cost many many times over.</p><p>I added a comment to explain why the zero was there and some integration tests that tried to measure the memory consumption of the custom data structures and fail if they increased.</p><p>For a long time I was tempted to always add a 0 to the constructor of a Set I thought was likely to be empty.</p><p>If you are also tempted, don’t.</p><p>Unless you know that the trick will make a different in that location, the optimisation is premature. There is no benefit, but there is still a cost. And it is a real cost — I had to spend time justifying the presence of that ‘0&#39; many times over the years as other developers questioned its purpose.</p><p>And if the optimisation was applied everywhere how would people know which ones were important?</p><p>This particular trick also no longer has any benefit.</p><p>As I found out while writing this article, modern JDKs do not allocate any space in a HashSet until something is added. If I had kept applying this trick pre-emptively I would have been wasting my time.</p><p>So my story shows that micro optimizations can be useful, though usually the results are much less dramatic.</p><p>Sometimes we can identify a key point where such as change will have large effect, but perhaps there is a gain to be had from the cumulative effect of lots of small optimizations. Each one on its own is irrelevant, but the net effect might be measurable.</p><p>Or it might not.</p><p>So when should we do this?</p><p>We should do it in two situations</p><ol><li>When we know we are trading off code readability for a meaningful gain (thanks to profiling and testing)</li><li>When we are not making a trade off at all</li></ol><p>Lets talk about that 2nd one.</p><p>Even if we haven’t profiled and do not know the size of the gain, if the (presumed) optimized version of the code is equally as readable as the non optimized version it makes sense to use it.</p><p>Perhaps we will get no gain from it at all.</p><p>Perhaps it actually performs worse than other alternatives we considered.</p><p>But if we are not compromising any other factor by using it then it makes sense to use our best guess at the most efficient implementation.</p><p>Performance testing and profiling should highlight if we were wrong in a way that matters.</p><p>Considering performance last means that we <strong>do consider it</strong> and give it weight <strong>when all other things are equal</strong>.</p><p>There is an also a much more compelling set of micro-optimisations. These are optimizations that are both (possibly) slightly more efficient, and also slightly cleaner compared to the code they commonly replace.</p><p>These one liners are usually utility methods in the Java libraries. Once you know they’re there you’ll find that code that doesn’t use them looks… Well, slightly wrong.</p><p>It is highly unlikely that the use of these one liners in any one place will have a noticeable impact on performance, but if they are used consistently throughout the code base they might have an overall positive effect. They generally are slightly more memory efficient than the code they replace, and might therefore improve garbage collection.</p><p>Or they might not, but it doesn’t matter as they also make the code slightly cleaner.</p><p>That is reason enough to use them by itself.</p><p>We don’t really need to talk about performance at all when discussing these one liners. They are just better ways of expressing something that is commonly expressed more clumsily.</p><h3>Four one liners every Java programmer should know</h3><h4>java.util.Arrays.asList</h4><p>For when you need to convert an array to a fixed size list.</p><pre>List&lt;String&gt; ss = Arrays.asList(“1”, “2”);</pre><p>This is cleaner and more efficient than the commonly seen alternatives such as:</p><pre>List&lt;String&gt; ss = new ArrayList&lt;&gt;();<br>ss.add(“1”);<br>ss.sdd(“2”);</pre><p>The list implementation returned by asList is specialized and may consume slightly less memory than an ArrayList.</p><p>Be aware that the lists created by this method are non-modifiable and will throw a java.lang.UnsupportedOperation if you try to modify them.</p><p>(<a href="https://medium.com/@dantaro?source=responses---------0-----------">Devin McIntyr</a>e has pointed out that the returned list is not fully runtime immutable. Although add and remove will throw, the set method does modify the collection)</p><h4>java.util.Collections.empty*</h4><p>Similar to Arrays.asList the java.util.Collections class contains methods that create unmodifiable versions of the common collections classes specialized to contain either no entries or single entries.</p><p>The most common ones are:</p><ul><li>emptyMap</li><li>emptyList</li><li>emptySet</li><li>singletonList</li><li>singletonMap</li><li>singletonSet</li></ul><p>But there are other more specialized methods there as well.</p><p>Again, using these results in cleaner more descriptive code compared to the<br>common alternatives and the specialized data structures returned may have a slightly smaller footprint.</p><h4>valueOf</h4><p>The form:</p><pre>Boolean b = Boolean.valueOf(true);</pre><p>Is slightly more efficient than the subjectively uglier:</p><pre>Boolean b = new Boolean(true);</pre><p>valueOf will return one of two fixed Boolean instances while calling the constructor will always allocate a new object.</p><p>Similarly for Integers valueOf will return a shared instance for values between -128 and 127.</p><p>Long.valueOf will similarly return objects from a cache.</p><p>The Oracle JDK does not currently look to use a cache for Floats or Doubles when calling valueOf. So using valueOf in preference to new for floating points might not have an advantage, but it has no disadvantage either.</p><p>Overloaded versions of the valueOf methods construct their desired types from Strings. If you need to create a boxed primitive from a String, this is the way to do it.</p><p>It is worth noting that, although it is not guaranteed by the spec, in practice Java compilers implement autoboxing by calling valueOf.</p><p>So:</p><pre>Boolean b = true;</pre><p>and</p><pre>Boolean b = Boolean.valueOf(true);</pre><p>Are equivalent.</p><p>(Steve McLeod has pointed out in the comments that as of Java 9 the constructor will deprecated — so all the more reason to use valueOf.)</p><h4>parseXXX</h4><p>Similar to valueOf the parseXXX methods convert a string to a primitive, only in this case the primitive is not boxed.</p><pre>float f = Float.parseFloat(“1.2”);</pre><p>This does exactly what the method says, and compared to the commonly seen alternative:</p><pre>float f = new Float(“1.2”);</pre><p>It avoids the construction and unboxing of a Float object.</p><p>Similar methods exist for Boolean, Double, Integer and the other primitive types.</p><h4>isEmpty</h4><p>A common clumsy idiom is to check if a Collection is empty by checking its size:</p><pre>if ( list.size() == 0 ) {<br>  // do stuff<br>}</pre><p>The clearer and more concise:</p><pre>if ( list.isEmpty() ) {<br>  // do stuff<br>}</pre><p>May also be more computationally efficient, depending on the data structure it is being called on.</p><p>Often there is no performance difference, but for a large ConcurrentLinkedQueue the difference can be significant.</p><h4>What else is out there?</h4><p>And that concludes the short list. I’d imagine that all of them were familiar to a programmer that had been working with Java for over a year, but if you are just starting out you wouldn’t know to look for them unless someone told you they were there.</p><p>There are undoubtedly other similar useful functions scattered about the JDK that provide the happy combination of cleanliness and infinitesimally small performance gain over the clumsier code they replace.</p><p>If you know of any please share.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31f3fdca1f68" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ncr-edinburgh/how-i-once-saved-half-a-million-dollars-with-a-one-character-code-change-31f3fdca1f68">How I once saved half a million dollars with a one character code change</a> was originally published in <a href="https://medium.com/ncr-edinburgh">NCR Edinburgh</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>