<?xml version="1.0" encoding="UTF-8"?>
<!--Generated by Squarespace Site Server v5.9.2 (http://www.squarespace.com/) on Thu, 11 Mar 2010 09:13:40 GMT--><feed xmlns="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/"><title>Journal</title><subtitle>Journal</subtitle><id>http://blog.fnord.se/journal/</id><link rel="alternate" type="application/xhtml+xml" href="http://blog.fnord.se/journal/"/><link rel="self" type="application/atom+xml" href="http://blog.fnord.se/journal/atom.xml"/><updated>2009-11-18T12:30:24Z</updated><generator uri="http://www.squarespace.com/" version="Squarespace Site Server v5.9.2 (http://www.squarespace.com/)">Squarespace</generator><entry><title>My opinions on multiple function / method exit points</title><id>http://blog.fnord.se/journal/2009/11/18/my-opinions-on-multiple-function-method-exit-points.html</id><link rel="alternate" type="text/html" href="http://blog.fnord.se/journal/2009/11/18/my-opinions-on-multiple-function-method-exit-points.html"/><author><name>Henrik Gustafsson</name></author><published>2009-11-18T12:13:31Z</published><updated>2009-11-18T12:13:31Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>Edited repost of <a href="http://stackoverflow.com/questions/36707/should-a-function-have-only-one-return-statement/36870#36870">this</a> stackoverflow reply since several people have asked me about this lately.</p>

<p>There are good things to say about having a single exit-point, just as there are bad things to say about the inevitable <a href="http://c2.com/cgi/wiki?ArrowAntiPattern">"arrow"</a> programming that results for some types of problems.</p>

<p>The ideal function/method should have a straight execution path with a single exit-point, no conditionals, no side effects and exactly one return point. This is a good thing to strive for, as few <a href="http://googletesting.blogspot.com/2008/11/my-unified-theory-of-bugs.html">"wiring bugs"</a> can hide in that kind of code; but this is not always possible or feasible.</p>

<p>If using multiple exit points during input validation or resource allocation, I try to put all the 'error-exits' very visibly at the top of the function in a <a href="http://www.refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html">guard clause</a> manner.</p>

<p>Both the <a href="http://ssdl-wiki.cs.technion.ac.il/wiki/index.php/Spartan_programming">Spartan Programming</a> article of the "SSDSLPedia" and <a href="http://c2.com/cgi/wiki?SingleFunctionExitPoint">the single function exit point</a> article of the "Portland Pattern Repository's Wiki" have some insightful arguments around this. Also, of course, there is <a href="#36711">this post</a> to consider.</p>

<p>If you really want a single exit-point (in any non-exception-enabled language) for example in order to release resources in one single place, I find the careful application of goto to be good; see for example this rather contrived example (compressed to save screen real-estate):</p>

<pre><code>int f(int y) {
    int value = -1;
    void *data = NULL;

    if (y &lt; 0)
        goto clean;

    if ((data = malloc(123)) == NULL)
        goto clean;

    /* More code */

    value = 1;
clean:
   free(data);
   return value;
}
</code></pre>

<p>Personally I, in general, dislike arrow programming more than I dislike multiple exit-points, although both are useful when applied correctly. The best, of course, is to structure your program to require neither. Breaking down your function into multiple chunks usually help :)</p>

<p>Although when doing so, I find I end up with multiple exit points anyway as in this example, where some larger function has been broken down into several smaller functions:</p>

<pre><code>int g(int y) {
  value = 0;

  if ((value = g0(y, value)) == -1)
    return -1;

  if ((value = g1(y, value)) == -1)
    return -1;

  return g2(y, value);
}
</code></pre>

<p>Depending on the project or coding guidelines, most of the boiler-plate code could be replaced by macros. As a side note, breaking it down this way makes the functions g0, g1 ,g2 very easy to test individually.</p>

<p>Obviously, in an OO and exception-enabled language, I wouldn't use if-statements like that (or at all, if I could get away with it with little enough effort), and the code would be much more plain. And non-arrowy. And most of the non-final returns would probably be exceptions.</p>

<p>In short;</p>

<ul>
<li>Few returns are better than many returns</li>
<li>More than one return is better than huge arrows, and <a href="http://www.refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html">guard clauses</a> are generally ok.</li>
<li>Exceptions could/should probably replace most 'guard clauses' whenever possible.</li>
</ul>
]]></content></entry><entry><title>Varför vaccinerade jag mig?</title><id>http://blog.fnord.se/journal/2009/11/17/varfor-vaccinerade-jag-mig.html</id><link rel="alternate" type="text/html" href="http://blog.fnord.se/journal/2009/11/17/varfor-vaccinerade-jag-mig.html"/><author><name>Henrik Gustafsson</name></author><published>2009-11-17T17:41:34Z</published><updated>2009-11-17T17:41:34Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>Jag var idag och vaccinerade mig mot <a href="http://en.wikipedia.org/wiki/Pandemic_H1N1/09_virus">A(H1N1)v / nya influensan / svininfluensan / galtfebern</a>, och förutsatt att jag inte drar på mig den riktiga influensan dom närmaste två veckorna (som exempelvis i väntrummet efter vaccinationen där massa människor var samlade på liten yta...barriärvård, tack? :) så bör jag vara rätt safe.</p>

<p>Innan jag skriver något mer kanske jag ska påpeka att jag inte har någon som helst medicinsk utbildning, så tänk själva och fråga er läkare om något är oklart.</p>

<p>Så varför vaccinerade jag mig? Förutom det uppenbara -- jag har ingen lust att ligga hemma och vara sjuk i flera veckor -- så är det mest en fråga om solidaritet.</p>

<p>Ju fler som vaccinerar sig, ju färre smittvägar har viruset, och ju färre smittvägar ju mindre risk är att personer som inte kan ta vaccinet av diverse anledningar exponeras för smittan, d.v.s <a href="http://en.wikipedia.org/wiki/Herd_immunity">populationsimmuniteten</a> höjs. Mängden människor som inte kan ta vaccinet och mängden människor som riskerar allvarliga effekter överlappar till stor del om man får tro avsnittet <a href="http://www.fass.se/LIF/produktfakta/artikel_produkt.jsp?NplID=20070324000011#contraindication">"Innan du får Pandemrix"</a> i FASS artikel om Pandemrix och frågorna 3 och 17 i ECDCs <a href="http://www.ecdc.europa.eu/en/healthtopics/Documents/0906_Influenza_AH1N1_FAQ.pdf">Frequently asked questions on
pandemic (H1N1) 2009</a>.</p>

<p>Som en bieffekt kan man hoppas att inte så många blir sjukskrivna samtidigt pga vaccinet och kan gå till jobbet och bidra till BNP som dom goda löneslavar vi är :)</p>

<p>Enligt mig(!) giltiga ursäkter att inte ta vaccinet</p>

<ul>
<li>Graviditet</li>
<li>Äggallergi</li>
<li>Febersjuk (vilket bara är en temporär ursäkt)</li>
<li>Du har redan haft influensan</li>
<li>Rekommendation från läkare eller sköterska</li>
</ul>

<p>Enligt mig(!) ogiltiga ursäkter</p>

<ul>
<li><a href="http://www.lakemedelsverket.se/alla-nyheter/nyheter-2009/sammanfattning-av-kunskapslaget-for-tiomersal/">Kvicksilver/Tiomersal/Thimerosal är farligt!</a></li>
<li><a href="http://www.lakemedelsverket.se/Alla-nyheter/NYHETER-2009/Sammanstallning-av-inrapporterade-biverkningar-av-Pandemrix-fram-till-10-november-/">Men bieffekterna…!</a></li>
<li>Jag har tappat bort kallelsen (<a href="http://www.krisinformation.se/web/Pages/Page____31603.aspx">Droppa in på ditt närmaste vaccinationsställe!</a>)</li>
<li><a href="http://maps.google.com/">Jag vet inte vart vaccinationsstället ligger</a></li>
<li>Jag sitter ändå bara på min kammare, träffar inget folk etc.</li>
<li>Jag är lat/sprut-rädd/whatever (även om du försöker rationalisera det till något annat!)</li>
<li><a href="http://www.antivaxxers.com/">WAA WAA KONSPIRATION BIG PHARMA ILLUMINATI AUTISM</a></li>
</ul>

<p>På bloggen <a href="http://tankebrott.wordpress.com/">Tankebrott</a> görs ett mer grundligt jobb än vad jag gör i att reda ut det hela <a href="http://tankebrott.wordpress.com/2009/10/20/skeptikerskolan-del-10-lathund-till-vaccin-och-svininfluensa/">här</a>.</p>

<p>För den som har intresse i att följa influensans utveckling kan jag rekommendera <a href="http://www.ecdc.europa.eu/en/healthtopics/Pages/Influenza_A(H1N1)_Outbreak.aspx">ECDCs site om H1N1-pandemin</a> samt Smittskyddsinstitutets <a href="http://www.smittskyddsinstitutet.se/publikationer/smis-nyhetsbrev/influensarapporter/sasongen-20092010/">influensarapport-sida</a> för information som inte är helt <a href="http://tankebrott.wordpress.com/2009/10/28/medias-ansvar-2/">förstörd</a> av <a href="http://tankebrott.wordpress.com/2009/10/30/medias-ansvar-del-2-samvetslosa-opportunister/">kvällspressen</a>.</p>

<p>Så har du inte vaccinerat dig än, så gå till ditt närmaste vaccinationsställe och få din skattefinansierade immunförsvarsuppgradering! </p>

<p>Och på vägen dit, i väntrummet och på hemresan kan jag rekommendera att lyssna på <a href="http://www.theskepticsguide.org/archive/podcastinfo.aspx?mid=1&amp;pid=10001">The Skeptics Guide To The Universe H1N1-special</a>.</p>
]]></content></entry><entry><title>Trying out the picture gallery</title><id>http://blog.fnord.se/journal/2009/9/24/trying-out-the-picture-gallery.html</id><link rel="alternate" type="text/html" href="http://blog.fnord.se/journal/2009/9/24/trying-out-the-picture-gallery.html"/><author><name>Henrik Gustafsson</name></author><published>2009-09-24T19:23:23Z</published><updated>2009-09-24T19:23:23Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>I figured it'd be neat to be able to post pictures from time to time etc, so I tried out the photo gallery with a handful of pictures I took this spring. Try it out on the <a href="http://blog.fnord.se/pictures/">Pictures</a> page.</p>
<p>&nbsp;</p>
<p>&nbsp;</p>]]></content></entry><entry><title>Overused Extract Method refactoring</title><id>http://blog.fnord.se/journal/2009/9/21/overused-extract-method-refactoring.html</id><link rel="alternate" type="text/html" href="http://blog.fnord.se/journal/2009/9/21/overused-extract-method-refactoring.html"/><author><name>Henrik Gustafsson</name></author><published>2009-09-21T20:57:31Z</published><updated>2009-09-21T20:57:31Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>I was reading the ObjectMentor blogs the other day, and came across a post called <a href="http://blog.objectmentor.com/articles/2009/09/11/one-thing-extract-till-you-drop">"One Thing: Extract till you Drop"</a> by Robert C. Martin. I definitely see the point of using extract method to a great extent in order to clarify the extent of the program, but I felt that example went a bit too far for a number of reasons.</p>

<ol>
<li>The names of the extracted methods made very little sense. Even when knowing what the class does it is hard to figure out the difference between <code>replaceAllSymbols()</code> and <code>replaceAllInstances()</code> and their relations to the other methods. You actually need to read them all in order to puzzle together the call-graph.</li>
<li>It introduces mutability in the class quite unnecessarily making reuse of the instance impossible.</li>
<li>Some of the extracted methods have strangely asymmetric abstraction levels.</li>
</ol>

<p>There are also some other issues regarding efficiency and thread-safeness that I reacted strongly to, especially since they are so easy to avoid.</p>

<p>When implementing it myself I thought about the scenarios when this would be used, and I could find two main ones. The first is to use this to iterate over different strings using the same dictionary and the second is to iterate over different dictionaries using the same string. Not knowing anything about the use-case I went for the former.</p>

<p>I made an attempt to improve it in the comments, but I was tired and messed it up a bit. Normally I probably would have solved the same problem in a manner closer to this:</p>

<pre><code>public class SymbolReplacer {
    private static final Pattern pattern =
        Pattern.compile("\\$([a-zA-Z]\\w*)");

    private final SymbolLookup lookup;

    SymbolReplacer(SymbolLookup lookup) {
        this.lookup = lookup;
    }

    public String replace(CharSequence stringToReplace) {
        final Matcher matcher = pattern.matcher(stringToReplace);
        return buildReplacement(matcher).toString();
    }

    private StringBuffer buildReplacement(Matcher matcher) {
        final int bufferLength =
            matcher.regionEnd() - matcher.regionStart();
        final StringBuffer buffer =
            new StringBuffer(bufferLength);

        fillBuffer(matcher, buffer);
        return buffer;
    }

    private void fillBuffer(Matcher matcher, StringBuffer buffer) {
        while (matcher.find())
            matcher.appendReplacement(buffer,
                getMatchReplacement(matcher));
        matcher.appendTail(buffer);
    }

    public String getMatchReplacement(Matcher matcher) {
        final String expansion =
            lookup.lookupValue(matcher.group(1));
        return (expansion != null) ?
            expansion :
            Matcher.quoteReplacement(matcher.group(0));
    }
}
</code></pre>

<p>I introduced the interface <code>SymbolLookup</code> as a replacement for the secret <code>getSymbol()</code> method. There are a few things I would like to fix in this as well; the <code>getMatchReplacement()</code> method is not as clear as I would have liked, and the line of abstraction between the different methods/layers is not well defined. Still, provided that SymbolLookup is thread-safe, so is this class. Also, you can reuse the instance to iterate over many strings.</p>
]]></content></entry><entry><title>Some info</title><id>http://blog.fnord.se/journal/2009/9/20/some-info.html</id><link rel="alternate" type="text/html" href="http://blog.fnord.se/journal/2009/9/20/some-info.html"/><author><name>Henrik Gustafsson</name></author><published>2009-09-20T11:00:00Z</published><updated>2009-09-20T11:00:00Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>Just trying out some new software. This page may or may not stay at the same place (probably not), and may or may not continue to be updated and may or may not continue to exist for long.</p>]]></content></entry></feed>