<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
  <title>Kristian Klette</title>
  <link>https://www.klette.us/</link>
  <description>Notes from a grumpy software engineer on code rot, dependency hell, and the systems that outlive the people who built them.</description>
  <language>en</language>
  <lastBuildDate>Mon, 09 Nov 2026 09:55:12 +0000</lastBuildDate>
  <item>
    <title>Migrate Django models to UUID primary key</title>
    <link>https://www.klette.us/post/migrate-django-models-to-uuid-primary-key/</link>
    <guid>https://www.klette.us/post/migrate-django-models-to-uuid-primary-key/</guid>
    <pubDate>Thu, 28 Sep 2017 14:17:40 +0000</pubDate>
    <description>&lt;p&gt;Sometimes, old design decisions comes back to bite you. This is one of those tales.&lt;/p&gt;
&lt;p&gt;A project I&amp;rsquo;m working on had a Django model similar to this:&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;python&quot;&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;f&quot;&gt;Municipality&lt;/span&gt;(models.Model):
    code = models.CharField(max_length=&lt;span class=&quot;n&quot;&gt;2&lt;/span&gt;, primary_key=True)
    name = models.CharField(max_length=&lt;span class=&quot;n&quot;&gt;100&lt;/span&gt;)
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;and it was used by other models such as:&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;python&quot;&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;f&quot;&gt;ZipCode&lt;/span&gt;(models.Model):
    code = models.CharField(max_length=&lt;span class=&quot;n&quot;&gt;2&lt;/span&gt;, primary_key=True)
    municipality = models.ForeignKey(Municipality)
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;And all was good, until we needed to expand the municipality model to support different countries, and thus a single unique field with only the code - which may collide across countries, was not enough.&lt;/p&gt;
&lt;p&gt;For all the modern parts of the code base we use &lt;code&gt;UUID&lt;/code&gt;s as the primary key,
so we wanted to migrate the primary key of &lt;code&gt;Municipality&lt;/code&gt; to a &lt;code&gt;UUID&lt;/code&gt;, while
retaining all the relations.&lt;/p&gt;
&lt;p&gt;As of September 2017, Django does not support migrating primary keys in any nice manner, so we&amp;rsquo;re on our own here.&lt;/p&gt;
&lt;p&gt;We tried a lot of magic solutions, but we always got stuck with the migrations system not being able to detect and handle the changes nicely.&lt;/p&gt;
&lt;p&gt;After some research and quite a bit of trial and error, we settled on the following approach. It has some draw backs I&amp;rsquo;ll get back to, but works reasonable well.&lt;/p&gt;
&lt;p&gt;A quick reminder on how the world looks from a database perspective. When you define a &lt;code&gt;ForeignKey&lt;/code&gt;-field in Django, it creates a database column of the same type as the primary key of the referenced model on the referring model, and adds the foreign key constraints. So in the example above, we have two tables (in pseudo SQL):&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;sql&quot;&gt;&lt;span class=&quot;k&quot;&gt;CREATE&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;TABLE&lt;/span&gt; municipality (
   code varchar(&lt;span class=&quot;n&quot;&gt;2&lt;/span&gt;) &lt;span class=&quot;k&quot;&gt;PRIMARY&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;KEY&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;NOT&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;NULL&lt;/span&gt;,
   name varchar(&lt;span class=&quot;n&quot;&gt;100&lt;/span&gt;)
);

&lt;span class=&quot;k&quot;&gt;CREATE&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;TABLE&lt;/span&gt; zipcode (
   code varchar(&lt;span class=&quot;n&quot;&gt;2&lt;/span&gt;) &lt;span class=&quot;k&quot;&gt;PRIMARY&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;KEY&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;NOT&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;NULL&lt;/span&gt;,
   municipality_id VARCHAR(&lt;span class=&quot;n&quot;&gt;2&lt;/span&gt;) &lt;span class=&quot;k&quot;&gt;REFERENCES&lt;/span&gt;(municipality.id) &lt;span class=&quot;k&quot;&gt;NOT&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;NULL&lt;/span&gt;
);
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;So, we need to break the foreign key constraints, alter the root model, then map the the new primary key ids to the old ones, and re-apply the foreign keys to it.&lt;/p&gt;
&lt;p&gt;We start by breaking the foreign keys in the referring models.&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;python&quot;&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;f&quot;&gt;ZipCode&lt;/span&gt;(models.Model):
    code = ...  &lt;span class=&quot;c&quot;&gt;# Same as before&lt;/span&gt;
    municipality = models.CharField(max_length=&lt;span class=&quot;n&quot;&gt;2&lt;/span&gt;)
&lt;/code&gt;&lt;/pre&gt;&lt;pre&gt;&lt;code data-lang=&quot;sh&quot;&gt;python manage.py makemigrations -n break_zipcode_muni_foreignkey
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Now that the &lt;code&gt;Municipality&lt;/code&gt; model is free from any external referring models,
we can go to work on it.&lt;/p&gt;
&lt;p&gt;Start by adding the new id field:&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;python&quot;&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;f&quot;&gt;Municipality&lt;/span&gt;(models.Model):
    id = models.UUIDField(default=uuid.uuid4)
&lt;/code&gt;&lt;/pre&gt;&lt;pre&gt;&lt;code data-lang=&quot;sh&quot;&gt;python manage.py makemigrations -n add_id_field_to_muni
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;For some reason, the default didn&amp;rsquo;t work in my case, so I added a step in the created migration to create new unique ids for all rows.&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;python&quot;&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;f&quot;&gt;create_ids&lt;/span&gt;(apps, schema_editor):
    Municipality = apps.get_model(&lt;span class=&quot;s&quot;&gt;&amp;#39;loc&amp;#39;&lt;/span&gt;, &lt;span class=&quot;s&quot;&gt;&amp;#39;Municipality&amp;#39;&lt;/span&gt;)
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; m &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; municipality:
        m.id = uuid.uuid4()
        m.save()
        
&lt;span class=&quot;c&quot;&gt;# ...&lt;/span&gt;

operations = [
    migrations.AddField(...),
    migrations.RunPython(code=create_ids),
]
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Now we have a &lt;code&gt;UUID&lt;/code&gt; &lt;code&gt;id&lt;/code&gt;-field on &lt;code&gt;Municipality&lt;/code&gt;, and we should be able to switch the primary key around.&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;python&quot;&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;f&quot;&gt;Municipality&lt;/span&gt;(models.Model):
    id = models.UUIDField(default=uuid.uuid4, primary_key=True)
    code = models.CharField(max_length=&lt;span class=&quot;n&quot;&gt;2&lt;/span&gt;, unique=True)
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Create the migration, and make sure that the &lt;code&gt;AlterField&lt;/code&gt; operation for &lt;code&gt;code&lt;/code&gt; is run before the &lt;code&gt;AlterField&lt;/code&gt; on &lt;code&gt;id&lt;/code&gt;. We&amp;rsquo;ve added &lt;code&gt;primary_key&lt;/code&gt; to the &lt;code&gt;id&lt;/code&gt; field and &lt;code&gt;unique=True&lt;/code&gt; to the &lt;code&gt;code&lt;/code&gt; field, since we still want to enforce that constraint for now, and we lost it when we removed the &lt;code&gt;primary_key&lt;/code&gt; attribute from it.&lt;/p&gt;
&lt;p&gt;Congratulations, we now have a new &lt;code&gt;UUID&lt;/code&gt; primary key. But we still need to clean up everything we broke the foreign keys from.&lt;/p&gt;
&lt;p&gt;Lets start by creating an empty migration:&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;sh&quot;&gt;python manage.py makemigrations --empty -n fix_zipcode_fk_to_muni_uuid loc
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Open the file, and let us begin:&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;python&quot;&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;f&quot;&gt;match&lt;/span&gt;(apps, schema_editor):
    ZipCode = apps.get_model(&lt;span class=&quot;s&quot;&gt;&amp;#39;loc&amp;#39;&lt;/span&gt;, &lt;span class=&quot;s&quot;&gt;&amp;#39;ZipCode&amp;#39;&lt;/span&gt;)
    Muni = apps.get_model(&lt;span class=&quot;s&quot;&gt;&amp;#39;loc&amp;#39;&lt;/span&gt;, &lt;span class=&quot;s&quot;&gt;&amp;#39;Municipality&amp;#39;&lt;/span&gt;)
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; zip_code &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; ZipCode.object.all():
        zip_code.temp_muni = Muni.get(code=z.municipality)
        zip_code.save()
    
&lt;span class=&quot;c&quot;&gt;# ...&lt;/span&gt;
operations = [
    migrations.AddField(
        model_name=&lt;span class=&quot;s&quot;&gt;&amp;#39;zipcode&amp;#39;&lt;/span&gt;,
        name=&lt;span class=&quot;s&quot;&gt;&amp;#39;temp_muni&amp;#39;&lt;/span&gt;,
        field=models.UUIDField(null=True),
    ),
    migrations.RunPython(code=match),
    migrations.RemoveField(model_name=&lt;span class=&quot;s&quot;&gt;&amp;#39;zipcode&amp;#39;&lt;/span&gt;, name=&lt;span class=&quot;s&quot;&gt;&amp;#39;municipality&amp;#39;&lt;/span&gt;),
    migrations.RenameField(
        model_name=&lt;span class=&quot;s&quot;&gt;&amp;#39;zipcode&amp;#39;&lt;/span&gt;, old_name=&lt;span class=&quot;s&quot;&gt;&amp;#39;temp_muni&amp;#39;&lt;/span&gt;, new_name=&lt;span class=&quot;s&quot;&gt;&amp;#39;municipality&amp;#39;&lt;/span&gt;),
    migrations.AlterField(
        model_name=&lt;span class=&quot;s&quot;&gt;&amp;#39;zipcode&amp;#39;&lt;/span&gt;,
        name=&lt;span class=&quot;s&quot;&gt;&amp;#39;municipality&amp;#39;&lt;/span&gt;,
        field=models.ForeignKey(
            on_delete=django.db.models.deletion.PROTECT,
            to=&lt;span class=&quot;s&quot;&gt;&amp;#39;municipality&amp;#39;&lt;/span&gt;)
]
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Let us go through the steps here.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Add a temporary field for storing the &lt;code&gt;UUID&lt;/code&gt; of &lt;code&gt;Municipality&lt;/code&gt; that we want to connect to. We don&amp;rsquo;t make it a &lt;code&gt;ForeignKey&lt;/code&gt;-field just yet, as Django gets confused about the naming later on.&lt;/li&gt;
&lt;li&gt;We run the &lt;code&gt;match&lt;/code&gt; function for looking up the new ids by the old lookup key, and store it in the temp field.&lt;/li&gt;
&lt;li&gt;Remove the old &lt;code&gt;municipality&lt;/code&gt; field&lt;/li&gt;
&lt;li&gt;Rename the temp field to &lt;code&gt;municipality&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;And finally migrate the type to a foreign key to create all the database constraints we need.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;And there you go. All done.&lt;/p&gt;
&lt;p&gt;There are some down sides here. Since we split the migrations into several files/migrations, we leave ourself vulnerable if any of the later migrations fail. This will probably leave the application in a pretty unworkable state. So make sure to test the migrations quite a bit. You can reduce the risk by hand editing all the steps into one migration, but if you have references from multiple different apps, then you need to the breaking and restoring in separate steps anyway.&lt;/p&gt;
&lt;h3 id=&quot;logging--debugging&quot;&gt;Logging / Debugging&lt;/h3&gt;
&lt;p&gt;You&amp;rsquo;ll most likely end up with some SQL errors during the process of creating these, so a nice trick I like to do is to create a simple logging migration operation.&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;python&quot;&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;f&quot;&gt;log&lt;/span&gt;(message):
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;f&quot;&gt;fake_op&lt;/span&gt;(apps, schema_editor):
        &lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;(message)
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; fake_op
    
    
 &lt;span class=&quot;c&quot;&gt;# ...&lt;/span&gt;
 
 operations = [
     migration.RunPython(log(&lt;span class=&quot;s&quot;&gt;&amp;#39;Step 1&amp;#39;&lt;/span&gt;)),
     migration.AlterField(..),
     migration.RunPython(log(&lt;span class=&quot;s&quot;&gt;&amp;#39;Step 2&amp;#39;&lt;/span&gt;)),
     &lt;span class=&quot;c&quot;&gt;# ...&lt;/span&gt;
 ]
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This allows you to see where in the process you fail.&lt;/p&gt;
&lt;p&gt;To see what SQL Django creates for a given migration, run
&lt;code&gt;python manage.py sqlmigrate &amp;lt;appname&amp;gt; &amp;lt;migration_number&amp;gt;&lt;/code&gt; - this is super useful for checking whether operations are run in the order that you expect.&lt;/p&gt;</description>
  </item>
  <item>
    <title>Easy steps for better living with Java</title>
    <link>https://www.klette.us/post/n-easy-steps-for-living-with-java/</link>
    <guid>https://www.klette.us/post/n-easy-steps-for-living-with-java/</guid>
    <pubDate>Mon, 08 Sep 2014 17:58:00 +0000</pubDate>
    <description>&lt;p&gt;Here are some easy steps I try to do on every Java-project I&amp;rsquo;m working on. They are based upon what I&amp;rsquo;ve seen as major problem sources in different code bases, and should be fairly easy to apply - at least on new code.&lt;/p&gt;
&lt;h2 id=&quot;tooling&quot;&gt;Tooling&lt;/h2&gt;
&lt;p&gt;The first steps are to enable some basic tooling that can help us keep the project a bit of better shape. All of these comes with a cost, namely build time, but it&amp;rsquo;s totally worth it.&lt;/p&gt;
&lt;h3 id=&quot;enable-strict-compilation&quot;&gt;Enable strict compilation&lt;/h3&gt;
&lt;p&gt;The javac-compiler exposes flags that increases the amount of linting the compiler does, and how it should treat the warnings produced by the compiler.&lt;/p&gt;
&lt;p&gt;Enabling it is as easy as adding &lt;code&gt;-Xlint:all -Werror&lt;/code&gt; to the compiler arguments.&lt;/p&gt;
&lt;p&gt;Using maven with the maven-compiler-plugin version 3.1 and up, simple do something like this in your pom.xml:&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;xml&quot;&gt;&lt;span class=&quot;k&quot;&gt;&amp;lt;build&amp;gt;&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;&amp;lt;plugins&amp;gt;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;&amp;lt;plugin&amp;gt;&lt;/span&gt;
      &lt;span class=&quot;k&quot;&gt;&amp;lt;artifactId&amp;gt;&lt;/span&gt;maven-compiler-plugin&lt;span class=&quot;k&quot;&gt;&amp;lt;/artifactId&amp;gt;&lt;/span&gt;
      &lt;span class=&quot;k&quot;&gt;&amp;lt;groupId&amp;gt;&lt;/span&gt;org.apache.maven.plugins&lt;span class=&quot;k&quot;&gt;&amp;lt;/groupId&amp;gt;&lt;/span&gt;
      &lt;span class=&quot;k&quot;&gt;&amp;lt;version&amp;gt;&lt;/span&gt;3.1&lt;span class=&quot;k&quot;&gt;&amp;lt;/version&amp;gt;&lt;/span&gt;
      &lt;span class=&quot;k&quot;&gt;&amp;lt;configuration&amp;gt;&lt;/span&gt; 
        &lt;span class=&quot;k&quot;&gt;&amp;lt;compilerArgs&amp;gt;&lt;/span&gt;
          &lt;span class=&quot;k&quot;&gt;&amp;lt;arg&amp;gt;&lt;/span&gt;-Werror&lt;span class=&quot;k&quot;&gt;&amp;lt;/arg&amp;gt;&lt;/span&gt;
          &lt;span class=&quot;k&quot;&gt;&amp;lt;arg&amp;gt;&lt;/span&gt;-Xlint:all&lt;span class=&quot;k&quot;&gt;&amp;lt;/arg&amp;gt;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;&amp;lt;/compilerArgs&amp;gt;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;&amp;lt;encoding&amp;gt;&lt;/span&gt;UTF-8&lt;span class=&quot;k&quot;&gt;&amp;lt;/encoding&amp;gt;&lt;/span&gt;
      &lt;span class=&quot;k&quot;&gt;&amp;lt;/configuration&amp;gt;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;&amp;lt;/plugin&amp;gt;&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;&amp;lt;/plugins&amp;gt;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;&amp;lt;/build&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;or if you use Gradle, then this should do the trick:&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;groovy&quot;&gt;compileJava {
   options.&lt;span class=&quot;f&quot;&gt;compilerArgs&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&amp;#34;-Xlint:all&amp;#34;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&amp;#34;-Werror&amp;#34;&lt;/span&gt;
   options.&lt;span class=&quot;f&quot;&gt;encoding&lt;/span&gt; = &lt;span class=&quot;s&quot;&gt;&amp;#39;UTF-8&amp;#39;&lt;/span&gt;
}
&lt;/code&gt;&lt;/pre&gt;&lt;h3 id=&quot;use-static-analysis&quot;&gt;Use static analysis&lt;/h3&gt;
&lt;p&gt;Static analysis is an extremely useful tool for catching potential errors early. Aside from the built-ins in the compiler, my favorite tool is FindBugs. The latest release (3.0) includes support for Java 8, which has been a deal breaker for a while.&lt;/p&gt;
&lt;p&gt;Adding it as a part of your build is quite easy, add the following snippet to your pom.xml:&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;xml&quot;&gt;&lt;span class=&quot;k&quot;&gt;&amp;lt;plugin&amp;gt;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;&amp;lt;groupId&amp;gt;&lt;/span&gt;org.codehaus.mojo&lt;span class=&quot;k&quot;&gt;&amp;lt;/groupId&amp;gt;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;&amp;lt;artifactId&amp;gt;&lt;/span&gt;findbugs-maven-plugin&lt;span class=&quot;k&quot;&gt;&amp;lt;/artifactId&amp;gt;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;&amp;lt;version&amp;gt;&lt;/span&gt;3.0.0&lt;span class=&quot;k&quot;&gt;&amp;lt;/version&amp;gt;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;&amp;lt;configuration&amp;gt;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;&amp;lt;effort&amp;gt;&lt;/span&gt;Max&lt;span class=&quot;k&quot;&gt;&amp;lt;/effort&amp;gt;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;&amp;lt;threshold&amp;gt;&lt;/span&gt;Low&lt;span class=&quot;k&quot;&gt;&amp;lt;/threshold&amp;gt;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;&amp;lt;xmlOutput&amp;gt;&lt;/span&gt;true&lt;span class=&quot;k&quot;&gt;&amp;lt;/xmlOutput&amp;gt;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;&amp;lt;/configuration&amp;gt;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;&amp;lt;executions&amp;gt;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;&amp;lt;execution&amp;gt;&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;&amp;lt;goals&amp;gt;&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;&amp;lt;goal&amp;gt;&lt;/span&gt;check&lt;span class=&quot;k&quot;&gt;&amp;lt;/goal&amp;gt;&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;&amp;lt;/goals&amp;gt;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;&amp;lt;/execution&amp;gt;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;&amp;lt;/executions&amp;gt;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;&amp;lt;/plugin&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This does add a bit of time to your build, but I think it is worth it. If your codebase is so large that this adds an unacceptable amount of build time, consider running it on jenkins or something.&lt;/p&gt;
&lt;h3 id=&quot;dont-allow-duplicate-library-versions&quot;&gt;Don&amp;rsquo;t allow duplicate library versions&lt;/h3&gt;
&lt;p&gt;Any non-trivial java application that uses third-party libraries are prone to having multiple versions of libraries included in the classpath. Since the java classloading is not guaranteed to be deterministic, this can cause you immense headaches really fast.&lt;/p&gt;
&lt;p&gt;If you use gradle with the java plugin, you can detect these problems out of the box. Just add the following to your build file:&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;groovy&quot;&gt;configurations.&lt;span class=&quot;f&quot;&gt;all&lt;/span&gt; {
   resolutionStrategy {
       failOnVersionConflict()
   }
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;If you use Maven on the other hand, you probably want the enforcer plugin. To use it, add the following to your pom.xml:&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;xml&quot;&gt;&lt;span class=&quot;k&quot;&gt;&amp;lt;plugin&amp;gt;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;&amp;lt;groupId&amp;gt;&lt;/span&gt;org.apache.maven.plugins&lt;span class=&quot;k&quot;&gt;&amp;lt;/groupId&amp;gt;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;&amp;lt;artifactId&amp;gt;&lt;/span&gt;maven-enforcer-plugin&lt;span class=&quot;k&quot;&gt;&amp;lt;/artifactId&amp;gt;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;&amp;lt;version&amp;gt;&lt;/span&gt;1.3.1&lt;span class=&quot;k&quot;&gt;&amp;lt;/version&amp;gt;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;&amp;lt;executions&amp;gt;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;&amp;lt;execution&amp;gt;&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;&amp;lt;id&amp;gt;&lt;/span&gt;enforce&lt;span class=&quot;k&quot;&gt;&amp;lt;/id&amp;gt;&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;&amp;lt;configuration&amp;gt;&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;&amp;lt;rules&amp;gt;&lt;/span&gt;
                    &lt;span class=&quot;k&quot;&gt;&amp;lt;DependencyConvergence&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;/&amp;gt;&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;&amp;lt;/rules&amp;gt;&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;&amp;lt;/configuration&amp;gt;&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;&amp;lt;goals&amp;gt;&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;&amp;lt;goal&amp;gt;&lt;/span&gt;enforce&lt;span class=&quot;k&quot;&gt;&amp;lt;/goal&amp;gt;&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;&amp;lt;/goals&amp;gt;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;&amp;lt;/execution&amp;gt;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;&amp;lt;/executions&amp;gt;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;&amp;lt;/plugin&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;h2 id=&quot;the-code&quot;&gt;The code&lt;/h2&gt;
&lt;p&gt;These steps are more related to the code you write. There are, as with all things, exceptions where these guidelines does not apply, but in the general case, these should serve you well to remember.&lt;/p&gt;
&lt;h3 id=&quot;null-is-the-exception&quot;&gt;Null is the exception&lt;/h3&gt;
&lt;p&gt;We&amp;rsquo;ve all seen &lt;code&gt;NullPointerException&lt;/code&gt; stacktraces in our logs, and they are always annoying to fix. In my experience, they are often just fixed with a null-check, and then passing the problem on the caller of the function where occurred. This results in a code base littered with null-checks, and a lot of defensive - or blatantly unsafe code, where you are never sure if something is set or not.&lt;/p&gt;
&lt;p&gt;Unfortunately we have no way of disabling nulls in Java, so all the burden is on us to defend the outer borders of our code against this.
Now, some data is inherently optional, but they can be marked as such. In Java 8 you have a built-in &lt;code&gt;Optional&amp;lt;T&amp;gt;&lt;/code&gt;-type, and if you are on 1.6 or 1.7 you can use the Optional-class from Guava.&lt;/p&gt;
&lt;p&gt;So, instead of returning null, return &lt;code&gt;Optional.empty()&lt;/code&gt; or if returning an empty value does not make sense, throw an exception. Its what they are for.&lt;/p&gt;
&lt;h3 id=&quot;do-not-allow-broken-data&quot;&gt;Do not allow broken data&lt;/h3&gt;
&lt;p&gt;Most enterprisy java projects have to deal with broken external systems, such as old databases, or some SOAP-service where everything is optional. Regardless of the type, we should guard our own software from the dirty data. Use &lt;code&gt;Optional&amp;lt;T&amp;gt;&lt;/code&gt; for the fields where is does make sense, and if the data provided from the external system does not hold up to a minimal set of requirements, don&amp;rsquo;t pass it along, drop it on the floor!&lt;/p&gt;
&lt;p&gt;If these causes some requirement not to be fulfilled, then fix it in the integration layer, but do not send shitty data down the line.&lt;/p&gt;
&lt;p&gt;One way of ensuring that bad instances of your models can be created, use the constructor and validate the input.&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;java&quot;&gt;&lt;span class=&quot;k&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;f&quot;&gt;Person&lt;/span&gt; {
   &lt;span class=&quot;k&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;final&lt;/span&gt; String name;
   &lt;span class=&quot;k&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;final&lt;/span&gt; Integer age;

   &lt;span class=&quot;k&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;f&quot;&gt;Person&lt;/span&gt;(&lt;span class=&quot;k&quot;&gt;final&lt;/span&gt; String name, &lt;span class=&quot;k&quot;&gt;final&lt;/span&gt; Integer age) {
      &lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;.&lt;span class=&quot;f&quot;&gt;name&lt;/span&gt; = checkNotNull(name, &lt;span class=&quot;s&quot;&gt;&amp;#34;name cannot be null&amp;#34;&lt;/span&gt;);
      &lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;.&lt;span class=&quot;f&quot;&gt;age&lt;/span&gt; = checkNotNull(age, &lt;span class=&quot;s&quot;&gt;&amp;#34;age cannot be null&amp;#34;&lt;/span&gt;);
   }
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;code&gt;checkNotNull(obj, message)&lt;/code&gt; is included with Guava, and throws a &lt;code&gt;NullPointerException&lt;/code&gt; if the given instance is &lt;code&gt;null&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;One pattern we have deployed successfully is to have a &amp;ldquo;safe factory&amp;rdquo; for the model, which returns an &lt;code&gt;Optional&amp;lt;T&amp;gt;&lt;/code&gt; of the instance.&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;java&quot;&gt;&lt;span class=&quot;k&quot;&gt;public&lt;/span&gt; Optional&lt;span class=&quot;k&quot;&gt;&amp;lt;&lt;/span&gt;Person&lt;span class=&quot;k&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;f&quot;&gt;safeCreate&lt;/span&gt;(&lt;span class=&quot;k&quot;&gt;final&lt;/span&gt; String name, &lt;span class=&quot;k&quot;&gt;final&lt;/span&gt; Integer age) {
   &lt;span class=&quot;k&quot;&gt;try&lt;/span&gt; {
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; Person(name, age);
   } &lt;span class=&quot;k&quot;&gt;catch&lt;/span&gt; (NullPointerException npe) {
    LOGGER.&lt;span class=&quot;f&quot;&gt;warn&lt;/span&gt;(&lt;span class=&quot;s&quot;&gt;&amp;#34;Invalid data provided for {}. Name: {}, Age: {}&amp;#34;&lt;/span&gt;, Person.&lt;span class=&quot;f&quot;&gt;class&lt;/span&gt;.&lt;span class=&quot;f&quot;&gt;getName&lt;/span&gt;(), name, age);
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; Optional.&lt;span class=&quot;f&quot;&gt;empty&lt;/span&gt;();
   }
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Using this pattern you can easily map input data to a list of valid instances. Using Java 8, one might do something like this:&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;java&quot;&gt;externalSystem.&lt;span class=&quot;f&quot;&gt;getPeople&lt;/span&gt;().&lt;span class=&quot;f&quot;&gt;stream&lt;/span&gt;()
.&lt;span class=&quot;f&quot;&gt;map&lt;/span&gt;(p &lt;span class=&quot;k&quot;&gt;-&amp;gt;&lt;/span&gt; Person.&lt;span class=&quot;f&quot;&gt;safeCreate&lt;/span&gt;(p.&lt;span class=&quot;f&quot;&gt;getName&lt;/span&gt;(), p.&lt;span class=&quot;f&quot;&gt;getAge&lt;/span&gt;()))
.&lt;span class=&quot;f&quot;&gt;filter&lt;/span&gt;(Optional::isPresent)
.&lt;span class=&quot;f&quot;&gt;map&lt;/span&gt;(Optional::get)
.&lt;span class=&quot;f&quot;&gt;collect&lt;/span&gt;(Collectors.&lt;span class=&quot;f&quot;&gt;toList&lt;/span&gt;());
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;or in Java 6/7:&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;java&quot;&gt;List&lt;span class=&quot;k&quot;&gt;&amp;lt;&lt;/span&gt;Optional&lt;span class=&quot;k&quot;&gt;&amp;lt;&lt;/span&gt;Person&lt;span class=&quot;k&quot;&gt;&amp;gt;&amp;gt;&lt;/span&gt; transformed = &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; ArrayList&lt;span class=&quot;k&quot;&gt;&amp;lt;&amp;gt;();&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; (RawPerson rp : externalSystem.&lt;span class=&quot;f&quot;&gt;getPeople&lt;/span&gt;()) {
  transformed.&lt;span class=&quot;f&quot;&gt;add&lt;/span&gt;(Person.&lt;span class=&quot;f&quot;&gt;safeCreate&lt;/span&gt;(rp.&lt;span class=&quot;f&quot;&gt;getName&lt;/span&gt;(), rp.&lt;span class=&quot;f&quot;&gt;getAge&lt;/span&gt;()));
}
List&lt;span class=&quot;k&quot;&gt;&amp;lt;&lt;/span&gt;Person&lt;span class=&quot;k&quot;&gt;&amp;gt;&lt;/span&gt; persons = Optional.&lt;span class=&quot;f&quot;&gt;presentInstances&lt;/span&gt;(transformed);
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The point is not to include objects that you are unsure of through the stack. The complexity starts dominating the system so fast.&lt;/p&gt;
&lt;h3 id=&quot;default-to-immutable-objects&quot;&gt;Default to immutable objects&lt;/h3&gt;
&lt;p&gt;Prefer and default to Immutable objects. Throw out the old Java Beans book, and enter into a much nicer world. Creating mostly immutable objects is quite easy. Mark your fields as final, and only allow them to be set during construction. NO SETTERS!&lt;/p&gt;
&lt;p&gt;Collections require a bit more attention, but using the immutable collections from Guava takes you a long way.&lt;/p&gt;
&lt;p&gt;If you need to modify the instance, return a new copy with the modified data.&lt;/p&gt;
&lt;h3 id=&quot;ioc-containers&quot;&gt;IoC Containers&lt;/h3&gt;
&lt;p&gt;IoC containers are quite popular, with Spring arguably is the most popular one. They can do you good, but be aware of the ease. Since it is so easy to inject instances all over the place, things get real messy very fast. See
&lt;a href=&quot;https://klette.us/some-tips-to-prevent-dependency-hell-in-the-land-of-ioc/&quot;&gt;https://klette.us/some-tips-to-prevent-dependency-hell-in-the-land-of-ioc/&lt;/a&gt; for patterns on how to reduce the pain.&lt;/p&gt;
&lt;p&gt;Avoid if possible. There is nothing wrong with calling &lt;code&gt;new MyClass()&lt;/code&gt; by yourself.&lt;/p&gt;
&lt;h3 id=&quot;reflection&quot;&gt;Reflection&lt;/h3&gt;
&lt;p&gt;Reflection is an escape-hatch that should only be used if you have no other options. It might be tempting, but it destroys everything from performance, to automated refactoring tools, and flow analysis tools.&lt;/p&gt;
&lt;p&gt;Please just dont. Find another way, and you&amp;rsquo;ll be happier for it.&lt;/p&gt;
&lt;h3 id=&quot;documentation&quot;&gt;Documentation&lt;/h3&gt;
&lt;p&gt;In most real projects, there comes a time where you have to get your hands dirty, and code some complex logic, or deal with some other broken system. Documentation in these cases is paramount.&lt;/p&gt;
&lt;p&gt;I have seen a secondary effect to documenting the code, that is documenting the methods &lt;strong&gt;before&lt;/strong&gt; you write the implementation. Similar to writing the tests first, this seems to, for me at least, keep me much more honest and the methods are much clearer.&lt;/p&gt;
&lt;p&gt;Give it a try for a couple of days.&lt;/p&gt;</description>
  </item>
  <item>
    <title>Building Java 8 apps with Gradle</title>
    <link>https://www.klette.us/post/building-java-8-apps-with-gradle/</link>
    <guid>https://www.klette.us/post/building-java-8-apps-with-gradle/</guid>
    <pubDate>Sun, 29 Dec 2013 14:59:24 +0000</pubDate>
    <description>&lt;p&gt;If you try to build your java-app with gradle against JDK8,and  you error out on the tests being run, then this is most likely due to Gradle using ASM4.x for test-detection.&lt;/p&gt;
&lt;p&gt;This has been fixed in Gradle 1.10 by using ASM5-beta to scan for tests, instead of 4.x as used in previous versions.&lt;/p&gt;
&lt;p&gt;If you are unable to upgrade to Gradle 1.10 for some reason,
you can apply the following trick to skip the scanning of tests, and just include them manually.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;test.scanForTestClasses = false
test {
    include &#x27;api/**/*Test.class&#x27;
    include &#x27;service/**/Test*.class&#x27;
    exclude &#x27;**/*$*.class&#x27; // exclude anonymous inner classes
}
&lt;/code&gt;&lt;/pre&gt;</description>
  </item>
  <item>
    <title>Keeping sane in the depth of madness</title>
    <link>https://www.klette.us/post/keeping-sane-in-the-depth-of-madness/</link>
    <guid>https://www.klette.us/post/keeping-sane-in-the-depth-of-madness/</guid>
    <pubDate>Sat, 28 Dec 2013 21:19:00 +0000</pubDate>
    <description>&lt;p&gt;This last year I&amp;rsquo;ve been working on systems that integrate with a master ERP-system over SOAP. As with all thing enterprise, things tends to get a bit messy.&lt;/p&gt;
&lt;p&gt;Most interactions with the SOAP-interface requires the user to specify a lot of identifactors for other objects. In our system, most of these are represented as &lt;code&gt;Long&lt;/code&gt;-instances.&lt;/p&gt;
&lt;p&gt;A naive implementation of this does not a happy programmer make.&lt;/p&gt;
&lt;p&gt;A typical service for talking through the SOAP may look a bit like this.&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;java&quot;&gt;&lt;span class=&quot;k&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;void&lt;/span&gt; &lt;span class=&quot;f&quot;&gt;triggerAccountAgreementUpdate&lt;/span&gt;(
	Long account,
    Long agreement,
    Long userTypeId,
    Long addressId,
    Long updateTypeId, ....) {}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;On the surface, that might not be so bad, but give it some time, a couple of more parameters that suddenly are needed, and
the typical call of this methods looks something like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;srvc.triggerAccountAgreementUpdate(
    12313243L,
    14223421L,
    2L,
    234251L,
    1065L, ...)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is starting to be hard to read. Some of the readability issues can be solved with declaring all the paramteres as properly named variables. One more problem that appears is when you have multiple ids of entities that look like each other. One example of this that I&amp;rsquo;ve found is where you have different types of addresses that you work with. If the type is only encoded in the names, these can be mistaken for each other,
creating weird bugs that are hard to track down.&lt;/p&gt;
&lt;p&gt;Given that this is in a statically typed (though with a bit broken type system) programming language, we should be able to leverage types to guide us.&lt;/p&gt;
&lt;p&gt;In languages such as Scala and Go, this can easily be done via type aliasing&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;go&quot;&gt;&lt;span class=&quot;k&quot;&gt;type&lt;/span&gt; &lt;span class=&quot;f&quot;&gt;CustomerId&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;int32&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;type&lt;/span&gt; &lt;span class=&quot;f&quot;&gt;AddressId&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;int32&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;In Java, we have no such luck, and must go through the usual boilerplate hell.&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;java&quot;&gt;&lt;span class=&quot;k&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;f&quot;&gt;CustomerId&lt;/span&gt; {
	&lt;span class=&quot;k&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;final&lt;/span&gt; Long id;
    &lt;span class=&quot;k&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;f&quot;&gt;CustomerId&lt;/span&gt;(&lt;span class=&quot;k&quot;&gt;final&lt;/span&gt; Long id) {
    	&lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;.&lt;span class=&quot;f&quot;&gt;id&lt;/span&gt; = checkNotNull(id);
    }
    &lt;span class=&quot;c&quot;&gt;// .equals and .hashCode below
&lt;/span&gt;&lt;span class=&quot;c&quot;&gt;&lt;/span&gt;}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;By creating these types we can be a bit more explicit in our methods, and give the programmer a bit more information to work with.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public void triggerAccountAgreementUpdate(
	AccountId account,
    AgreementId agreement,
    UserTypeId userTypeId,
    AddressId addressId,
    UpdateType updateTypeId, ....) {}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The overhead of doing this might be discouraging, but we&amp;rsquo;ve had great results by using this technique. I think this becomes more and more important as the complexity of the application grows. Given a n-layered stack where the data has to flow through a wide range of methods and indirections before actually being used, then it is crucial not to mess this stuff up.&lt;/p&gt;
&lt;p&gt;For more examples of this technique and others take a look at &lt;a href=&quot;http://vimeo.com/78909069&quot;&gt;Jessica Kerrs excellent talk from Øredev this year&lt;/a&gt;.&lt;/p&gt;
&lt;h3 id=&quot;additional-note&quot;&gt;Additional note&lt;/h3&gt;
&lt;p&gt;Since REST and JSON is all the rage these days, here is a small tip for using these identifier types using jackson.&lt;/p&gt;
&lt;p&gt;Given the entity &lt;code&gt;Customer&lt;/code&gt; defined like this:&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;java&quot;&gt;&lt;span class=&quot;k&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;f&quot;&gt;Customer&lt;/span&gt; {
    &lt;span class=&quot;k&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;final&lt;/span&gt; CustomerId id;
    &lt;span class=&quot;k&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;final&lt;/span&gt; String name;
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;then the default serialization would produce something like this:&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;json&quot;&gt;{&lt;span class=&quot;k&quot;&gt;&amp;#34;id&amp;#34;&lt;/span&gt;: {&lt;span class=&quot;k&quot;&gt;&amp;#34;id&amp;#34;&lt;/span&gt;: &lt;span class=&quot;n&quot;&gt;1234&lt;/span&gt;}, &lt;span class=&quot;k&quot;&gt;&amp;#34;name&amp;#34;&lt;/span&gt;: &lt;span class=&quot;s&quot;&gt;&amp;#34;Alice Example&amp;#34;&lt;/span&gt;}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Thats a bit silly.&lt;/p&gt;
&lt;p&gt;We can fix this by using the &lt;code&gt;@JsonUnwrapped&lt;/code&gt;-annotation provided by Jackson.&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;java&quot;&gt;&lt;span class=&quot;k&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;f&quot;&gt;Customer&lt;/span&gt; {
    &lt;span class=&quot;f&quot;&gt;@JsonUnwrapped&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;final&lt;/span&gt; CustomerId id;
    &lt;span class=&quot;k&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;final&lt;/span&gt; String name;
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;If you use this annotation, then other annotations thats should affect the field, must be put in the CustomerId-class, not in the Customer-class.&lt;/p&gt;
&lt;p&gt;For using the field as a &lt;code&gt;*Param&lt;/code&gt; in Jersey (JAX-RS) the id-classes must obey the rules given in &lt;a href=&quot;https://jersey.java.net/documentation/latest/jaxrs-resources.html#d0e1811&quot;&gt;https://jersey.java.net/documentation/latest/jaxrs-resources.html#d0e1811&lt;/a&gt;.
TL;DR of these are provide a constructor that takes a single string-argument for constructing the entity, or have a static method &lt;code&gt;valueOf(string)&lt;/code&gt; that can create new instances.&lt;/p&gt;</description>
  </item>
  <item>
    <title>Dependency hell in the land of IoC</title>
    <link>https://www.klette.us/post/some-tips-to-prevent-dependency-hell-in-the-land-of-ioc/</link>
    <guid>https://www.klette.us/post/some-tips-to-prevent-dependency-hell-in-the-land-of-ioc/</guid>
    <pubDate>Thu, 17 Oct 2013 11:54:53 +0000</pubDate>
    <description>&lt;p&gt;Using automated dependency injection has made the life of a developer a bit easier, or so it seems for a while. Maybe a bit too easy. In this post I&amp;rsquo;ll describe some of the mess this can lead to, and what you should do to avoid it, or fix it if it has already happened.&lt;/p&gt;
&lt;p&gt;The examples and mentioned libraries are Java-based, but most languages have something similar.&lt;/p&gt;
&lt;h3 id=&quot;what-is-dependency-injection&quot;&gt;What is dependency injection?&lt;/h3&gt;
&lt;p&gt;Dependency injection (DI) is at its core a way of passing
dependencies to a class to it by some means.&lt;/p&gt;
&lt;p&gt;It can be easily explained by some piece of code:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class NoDependencyInjection {
    private OtherService os;
    private DifferentService ds;

    public NoDependencyInjection() {
        os = new OtherService();
        ds = new DifferentService();
    }
}
class WithDependencyInjection {
    private OtherService os;
    private DifferentService ds;

    public WithDependencyInjection(OtherService os, DifferentService ds) {
       this.os = os;
       this.ds = ds;
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The main difference is that the class &lt;code&gt;NoDependencyInjection&lt;/code&gt; is responsible for creating and managing its dependencies on its own, while the &lt;code&gt;WithDependencyInjection&lt;/code&gt;-class does not care how the dependencies are created, its just passed them, and uses their exposed API.&lt;/p&gt;
&lt;p&gt;One common problem with the &lt;code&gt;NoDependencyInjection&lt;/code&gt;-class way of doing things is about testability. Given that &lt;code&gt;OtherService&lt;/code&gt; talks to a database, how do you make it so that you can properly unittest &lt;code&gt;NoDependencyInjection&lt;/code&gt;?&lt;/p&gt;
&lt;p&gt;You&amp;rsquo;d have to create some mock database, and do a lot of setup for &lt;code&gt;OtherService&lt;/code&gt;, which &lt;code&gt;NoDependencyInjection&lt;/code&gt; really should know nothing about, or create some sort of factory, that you can for each test specify the sort of object to return, something like &lt;code&gt;ServiceFactory.setService(myServiceStub)&lt;/code&gt;. The problem with the factory method is that your tests cannot run at the same time, since you are most likely using the same factory instance to create the service.&lt;/p&gt;
&lt;p&gt;In my opinion &lt;code&gt;OtherService&lt;/code&gt; should be testet on its own, and &lt;code&gt;NoDependencyInjection&lt;/code&gt; should just rely on &lt;code&gt;OtherService&lt;/code&gt; to function the way it is supposed to.&lt;/p&gt;
&lt;p&gt;Once a program reaches a certain size and complexity, the dependency setup starts to get a bit cumbersome. This led to the arrival of DI-frameworks. The Spring-project might contain the most used one, and provides the developer with the &lt;code&gt;@Autowire&lt;/code&gt;-annotation. This tells the framework to &lt;em&gt;inject&lt;/em&gt; a ready made instance of that dependency into to the class at runtime. This annotation has two basic usage patterns, field annotation and constructor annotation.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class Service {
	@Autowired // Field annotation. Gets injected via reflection
    private OtherService os;
    
    @Autowired // Inject at construction
    public Service(OtherService os) {}
}
&lt;/code&gt;&lt;/pre&gt;&lt;h3 id=&quot;the-problem&quot;&gt;The problem&lt;/h3&gt;
&lt;p&gt;One problem that often occurs are classes that have way more dependencies than any class should have. Automated dependency injections makes it, perhaps, a bit too easy to add a new dependency to a class, without properly thinking about the consequences. This is even easier on classes that have no tests attached to them, since you never see the cost of setting the class up to a functional state.&lt;/p&gt;
&lt;p&gt;These classes tend to look something like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class MyService {
    @Autowired
    private OtherService os;
    
    @Autowired
    private OtherService2 os2;
    
    @Autowired
    private OtherService3 os3;
    
    @Autowired
    private OtherService4 os4;
    
    @Autowired
    private OtherService5 os5;
    
    @Autowired
    private OtherServiceN osN;
    
    // .. methods are about five pages down

}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This is what I&amp;rsquo;d like to call legacy-by-design. It might work, but is nearly impossible to test (and if you manage it, it&amp;rsquo;s likely 500 lines of mock setup before you even get to test anything).&lt;/p&gt;
&lt;p&gt;Why does this happen? For starters, It&amp;rsquo;s clearly not tested - the pain of testing this would have caused the developers to split the service long before that mess happened. Once a class gets, say 10 dependencies, the broken window effect starts to creep up on you.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Ugh, this is messy. Oh well, whats one more dependency? I&amp;rsquo;ll just add it.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Who cares about one more broken window in a house full of them?&lt;/p&gt;
&lt;h3 id=&quot;so-what-can-be-done&quot;&gt;So what can be done?&lt;/h3&gt;
&lt;p&gt;One small observation I&amp;rsquo;ve made is that if you use constructor based injection, it seems to deter people from adding more arguments &lt;strong&gt;more&lt;/strong&gt; than adding a new field. My data set is quite small, so take this with a grain of salt, but the initial findings are promising.&lt;/p&gt;
&lt;p&gt;So, if you use DI-frameworks, try to use constructor based injections. A nice bonus effect is that it is much easier to test, as you don&amp;rsquo;t have to bring up a Spring context in this instance, or something like Mockito&amp;rsquo;s &lt;code&gt;@InjectMocks&lt;/code&gt;-magic. Still using Spring&amp;rsquo;s &lt;code&gt;@Autowired&lt;/code&gt; annotation, this is easily done like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class MyService {
    private final OtherService os;
    
    @Autowired
    public MyService(final OtherService os) {
        this.os = os;
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This only gets you so far though, and does not really fix the classes that are already broken. To fix these, you&amp;rsquo;ll just have to roll your sleeves up and get ready for the treachorous road of refactoring untested code. The book &lt;a href=&quot;http://www.amazon.com/Working-Effectively-Legacy-Michael-Feathers/dp/0131177052/ref=sr_1_1?ie=UTF8&amp;amp;qid=1382084518&amp;amp;sr=8-1&amp;amp;keywords=working+with+legacy+code&quot;&gt;Working Effectively with Legacy Code&lt;/a&gt; has some great techniques for doing such work. But the gist of the processes is finding natural groups of functionality that can be moved to its own class. If no such groups are really present, which sometimes happens in complex integration work, you can consider moving some of the methods used from the dependencies to a new interface, with as few methods as possible, and create a facade class that proxies the calls to the dependencies. This allows you to stub the interface for tests more easily, and new patterns are likely to emerge.&lt;/p&gt;
&lt;p&gt;Let&amp;rsquo;s see if we can create a decent example.&lt;/p&gt;
&lt;p&gt;Given this class:&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;java&quot;&gt;&lt;span class=&quot;f&quot;&gt;@Service&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;f&quot;&gt;BookingService&lt;/span&gt; {
    &lt;span class=&quot;f&quot;&gt;@Autowired&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;private&lt;/span&gt; RoutingService routingService;
    
    &lt;span class=&quot;f&quot;&gt;@Autowired&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;private&lt;/span&gt; AvailabilityService availabilityService;
    
    &lt;span class=&quot;f&quot;&gt;@Autowired&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;private&lt;/span&gt; LocationRepository locationRepository;
    
    &lt;span class=&quot;f&quot;&gt;@Autowired&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;private&lt;/span&gt; CustomerRepository customerRepository;
    
    &lt;span class=&quot;f&quot;&gt;@Autowired&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;private&lt;/span&gt; StaffRepository staffRepository;
    
    &lt;span class=&quot;c&quot;&gt;// .. Imagine a lot more dependencies here
&lt;/span&gt;&lt;span class=&quot;c&quot;&gt;&lt;/span&gt;    
    &lt;span class=&quot;k&quot;&gt;public&lt;/span&gt; Booking &lt;span class=&quot;f&quot;&gt;requestBooking&lt;/span&gt;(
        Long customerId,
        WorkType workType,
        DateTime dateOfWork
    ) {
        Customer c = customerRepository.&lt;span class=&quot;f&quot;&gt;get&lt;/span&gt;(customerId);
        Location l = locationRepository.&lt;span class=&quot;f&quot;&gt;get&lt;/span&gt;(c.&lt;span class=&quot;f&quot;&gt;homeAddress&lt;/span&gt;());
        Set&lt;span class=&quot;k&quot;&gt;&amp;lt;&lt;/span&gt;Staff&lt;span class=&quot;k&quot;&gt;&amp;gt;&lt;/span&gt; possibleStaff = staffRepository.&lt;span class=&quot;f&quot;&gt;findForWorkType&lt;/span&gt;(workType);
        
        Set&lt;span class=&quot;k&quot;&gt;&amp;lt;&lt;/span&gt;Staff&lt;span class=&quot;k&quot;&gt;&amp;gt;&lt;/span&gt; staffInRangeAndAvail = Sets.&lt;span class=&quot;f&quot;&gt;newHashSet&lt;/span&gt;();
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; (Staff staffMember : possibleStaff) {
            Long distance = routingService
                                .&lt;span class=&quot;f&quot;&gt;distanceBetween&lt;/span&gt;(l, staffMember.&lt;span class=&quot;f&quot;&gt;officeLocation&lt;/span&gt;());
            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; (distance &lt;span class=&quot;k&quot;&gt;&amp;lt;&lt;/span&gt; 10000 &lt;span class=&quot;k&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt;
                    availabilityService.&lt;span class=&quot;f&quot;&gt;isFree&lt;/span&gt;(staffMember, dateOfWork)) {
                staffInRangeAndAvail.&lt;span class=&quot;f&quot;&gt;add&lt;/span&gt;(staffMember);
            }
        }
        
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; (staffInRange.&lt;span class=&quot;f&quot;&gt;isEmpty&lt;/span&gt;()) {
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;null&lt;/span&gt;;
        }
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; Booking(staffInRange.&lt;span class=&quot;f&quot;&gt;get&lt;/span&gt;(0)); &lt;span class=&quot;c&quot;&gt;// Something like that        
&lt;/span&gt;&lt;span class=&quot;c&quot;&gt;&lt;/span&gt;    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;So, whats going on here. A quick glance shows that the &lt;code&gt;requestBooking&lt;/code&gt; method uses five dependencies, which is quite a lot.&lt;/p&gt;
&lt;p&gt;One possible route is to encapsulate the things that have to do with finding the staff members that have the right skills and are in range into a seperate class.&lt;/p&gt;
&lt;p&gt;So, we can create a quick interface for the functionality&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;interface WorkorderStaffFinder {
    Set&amp;lt;Staff&amp;gt; staffForWork(WorkType type, Location l, DateTime timeOfWork);
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;and a quick implementation&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class DefaultWorkorderStaffFinder implements WorkorderStaffFinder {

    private RoutingService routingService;
    private AvailabilityService availabilityService;
    private StaffRepository staffRepository;
    
    @Autowired
    public DefaultWorkorderStaffFinder(...) {} // assign dependencies
    
    Set&amp;lt;Staff&amp;gt; staffForWork(
        WorkType type,
        Location l,
        DateTime timeOfWork
    ) {
        Set&amp;lt;Staff&amp;gt; possibleStaff = staffRepository.findForWorkType(workType);
        Set&amp;lt;Staff&amp;gt; staffInRangeAndAvail = Sets.newHashSet();
        for (Staff staffMember : possibleStaff) {
            Long distance = routingService
                            .distanceBetween(l, staffMember.officeLocation());
            if (distance &amp;lt; 10000 &amp;amp;&amp;amp;
                    availabilityService.isFree(staffMember, dateOfWork)) {
                staffInRangeAndAvail.add(staffMember);
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The original class now looks like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;@Service
class BookingService {
    
    @Autowired
    private LocationRepository locationRepository;
    
    @Autowired
    private CustomerRepository customerRepository;
    
    @Autowired
    private WorkorderStaffFinder workorderStaffFinder;

    
    // .. Imagine a lot more dependencies here
    
    public Booking requestBooking(
        Long customerId,
        WorkType workType,
        DateTime dateOfWork
    ) {
        Customer c = customerRepository.get(customerId);
        Location l = locationRepository.get(c.homeAddress());
        Set&amp;lt;Staff&amp;gt; staff = workorderStaffFinder
                            .staffForWork(workType, l, dateOfWork);
                            
        if (staffInRange.isEmpty()) {
            return null;
        }
        return new Booking(staffInRange.get(0)); // Something like that        
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;We have removed two dependencies, and we can now more easily test the business
logic of &lt;code&gt;requestBooking&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;If you think about it, why should the &lt;code&gt;requestBooking&lt;/code&gt;-method care how the
possible staff members are found? It should only care if some are found or not.
This is one aspect of the single responsibility principle that is a part of
SOLID (or some other buzzy-abbreviation).&lt;/p&gt;
&lt;p&gt;Ideally we should end up with a &lt;code&gt;BookingService&lt;/code&gt;-class that we can test
like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;@Test
public requestBookingShouldReturnNullIfNoStaffIsAvailable() {
    BookingService bs = new BookingService(
    						customerRepositoryMock,
    						locationRepositoryMock,
                            new EmptyResultWorkorderStaffFinder());
    
    Booking b = BookingService.requestBooking(1L, WorkType.TECH, DateTime.now());
    
    assertThat(b).isNull();
}

class EmptyResultWorkorderStaffFinder implements WorkorderStaffFinder {
    Set&amp;lt;Staff&amp;gt; staffForWork(...) {
        return new Set&amp;lt;Staff&amp;gt;();
    }
}
&lt;/code&gt;&lt;/pre&gt;</description>
  </item>
  <item>
    <title>Java dependencies</title>
    <link>https://www.klette.us/post/java-dependencies/</link>
    <guid>https://www.klette.us/post/java-dependencies/</guid>
    <pubDate>Thu, 10 Nov 2011 23:08:00 +0000</pubDate>
    <description>&lt;p&gt;A little python snippet for creating dot-representation of the
dependencies in a java app.&lt;/p&gt;
&lt;p&gt;Let this little baby chew on your target/classes dir and you will get a
dot-file on stdout.&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;python&quot;&gt; &lt;span class=&quot;c&quot;&gt;#!/usr/bin/env python&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;import&lt;/span&gt; re
&lt;span class=&quot;k&quot;&gt;import&lt;/span&gt; os
&lt;span class=&quot;k&quot;&gt;import&lt;/span&gt; sys
&lt;span class=&quot;k&quot;&gt;from&lt;/span&gt; os.path &lt;span class=&quot;k&quot;&gt;import&lt;/span&gt; join, basename

LIB_REG_EXP = re.compile(&lt;span class=&quot;s&quot;&gt;&amp;#39;[,+L#][a-z][A-Za-z0-9/]+&amp;#39;&lt;/span&gt;)
PACKAGE_FILTER = &lt;span class=&quot;s&quot;&gt;&amp;#39;&amp;#39;&lt;/span&gt;
CLASS_PREFIX_REMOVE = &lt;span class=&quot;s&quot;&gt;&amp;#39;&amp;#39;&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; len(sys.argv) &lt;span class=&quot;k&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;2&lt;/span&gt;:
    PACKAGE_FILTER = sys.argv[&lt;span class=&quot;n&quot;&gt;2&lt;/span&gt;]

&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; len(sys.argv) &lt;span class=&quot;k&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;3&lt;/span&gt;:
    CLASS_PREFIX_REMOVE = sys.argv[&lt;span class=&quot;n&quot;&gt;3&lt;/span&gt;]

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;f&quot;&gt;get_class_dependecies&lt;/span&gt;(class_file_contents):
    libraries = set(map(&lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; x: x.replace(&lt;span class=&quot;s&quot;&gt;&amp;#39;/&amp;#39;&lt;/span&gt;,&lt;span class=&quot;s&quot;&gt;&amp;#39;.&amp;#39;&lt;/span&gt;), [l[&lt;span class=&quot;n&quot;&gt;1&lt;/span&gt;:] &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; l &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; LIB_REG_EXP.findall(class_file_contents)]))
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; filter(&lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; x: PACKAGE_FILTER &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; x, libraries)

class_dependecies = {}
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; root, dirs, files &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; os.walk(sys.argv[&lt;span class=&quot;n&quot;&gt;1&lt;/span&gt;]):
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&amp;#39;.svn&amp;#39;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; dirs:
        dirs.remove(&lt;span class=&quot;s&quot;&gt;&amp;#39;.svn&amp;#39;&lt;/span&gt;)
    class_files = [f &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; f &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; files &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; f.endswith(&lt;span class=&quot;s&quot;&gt;&amp;#39;.class&amp;#39;&lt;/span&gt;) &lt;span class=&quot;k&quot;&gt;and&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&amp;#39;$&amp;#39;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; f]
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; class_file &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; class_files:
        class_content = open(join(root, class_file)).read()
        class_name = join(root, class_file).replace(&lt;span class=&quot;s&quot;&gt;&amp;#39;/&amp;#39;&lt;/span&gt;,&lt;span class=&quot;s&quot;&gt;&amp;#39;.&amp;#39;&lt;/span&gt;)[len(CLASS_PREFIX_REMOVE):-&lt;span class=&quot;n&quot;&gt;6&lt;/span&gt;]
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; PACKAGE_FILTER &lt;span class=&quot;k&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; class_name:
            &lt;span class=&quot;k&quot;&gt;continue&lt;/span&gt;
        class_dependecies[class_name] = []
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; dep &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; get_class_dependecies(class_content):
            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; dep == class_name:
                &lt;span class=&quot;k&quot;&gt;continue&lt;/span&gt;
            class_dependecies[class_name].append(dep)

&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&amp;#34;digraph G {&amp;#34;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; key, deps &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; class_dependecies.items():
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; dep &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; deps:
        &lt;span class=&quot;k&quot;&gt;print&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&amp;#39;&amp;#34;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;%s&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&amp;#34; -&amp;gt; &amp;#34;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;%s&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&amp;#34;;&amp;#39;&lt;/span&gt; % (key, dep)
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&amp;#34;}&amp;#34;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;The second argument creates a basic filter for the class-names you want.
The third parameter is used for removing the folder-names
(target.classes. in usual cases)&lt;/p&gt;
&lt;p&gt;Example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;python dotclass.py target/classes us.klette.myproject target.classes. &amp;gt; deps.dot
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Have fun&lt;/p&gt;</description>
  </item>
  <item>
    <title>Rot</title>
    <link>https://www.klette.us/post/rot/</link>
    <guid>https://www.klette.us/post/rot/</guid>
    <pubDate>Sat, 08 Oct 2011 12:30:19 +0000</pubDate>
    <description>&lt;p&gt;&lt;img src=&quot;/img/tumblr_lsqyhxKgBL1qhrmsu.jpg&quot; alt=&quot;Photo by WillSculling&quot;&gt;&lt;/p&gt;
&lt;p&gt;I’m quite fascinated by how quickly code rots and becomes a mess,
despite the programmers best intentions. A lot could be fixed by testing
and and refactoring more often, but it always seems to come second to
getting shit done, and does sometimes have unintended effects.&lt;/p&gt;
&lt;p&gt;For some reason I see this more often in Java code than in other
languages. Maybe it’s because of its class-madness creating deep nested
code (try to trace a call through Jersey, I dare you.).&lt;/p&gt;
&lt;p&gt;Jersey is actually a nice example of this. The code is in itself clean,
documented and well tested, but it is still (in my opinion) a mess.
Seems to me that abstraction does not only have an performance penalty,
but a readability issue as well. And in this case, it seems the code has
been tested and refactored multiple times, but still it’s hard to
understand.&lt;/p&gt;
&lt;p&gt;Seems like there is a fine line between reusability and loss of
understanding for what happens inside the black box.&lt;/p&gt;
&lt;p&gt;Photo by &lt;a href=&quot;http://www.falconerdevelopment.com/go/Will%20Scullin/&quot;&gt;Will
Sculling&lt;/a&gt;&lt;/p&gt;</description>
  </item>
  <item>
    <title>Take control over your data: banking</title>
    <link>https://www.klette.us/post/take-control-over-your-data-banking/</link>
    <guid>https://www.klette.us/post/take-control-over-your-data-banking/</guid>
    <pubDate>Mon, 18 Jul 2011 07:46:00 +0000</pubDate>
    <description>&lt;p&gt;So, banking data is quite interesting. If one could get a hold of your
credit card transactions in an easy way, that would be sweet. But, its
not that easy.&lt;/p&gt;
&lt;p&gt;My bank, DNBNor, has a feature that you can download either an excel
document, or a CSV formatted dump of the transactions against one of
your accounts on a monthly basis. The programmers choice would be CSV,
but I found the CSV exports to be spotty, so excel it it.&lt;/p&gt;
&lt;p&gt;But I don’t want to my analysis in Excel, so Perl to the rescue. The
following snippet takes an Excel document, exported from DNBNor, as it’s
first argument, and gives you an JSON-representation of the data to
STDOUT. Should be quite easy to manipulate these in any language of your
choice.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#!/usr/bin/perl

use strict;
use utf8;
use warnings;
use Switch;
use Spreadsheet::ParseExcel;
use JSON::XS;

my $excel = Spreadsheet::ParseExcel-&amp;gt;new;

die &amp;quot;Need an xls-file containing DNB Nor transaction list as frowst argument\n&amp;quot; unless @ARGV;

my $doc = $excel-&amp;gt;Parse($ARGV[0]) or die(&#x27;Could not parse excel file\n&#x27;, $@);

my @transactions = ();

for(my $sheet=0; $sheet &amp;lt; $doc-&amp;gt;{SheetCount} ; $sheet++) {
    my $current_sheet = $doc-&amp;gt;{Worksheet}[$sheet];
    for(my $row = $current_sheet-&amp;gt;{MinRow}; defined $current_sheet-&amp;gt;{MaxRow} &amp;amp;&amp;amp; $row &amp;lt;= $current_sheet-&amp;gt;{MaxRow}; $row++) {
        # Skip header row
        if ($row == $current_sheet-&amp;gt;{MinRow}){
            next;
        }
        my %transaction = ();
        for(my $column = $current_sheet-&amp;gt;{MinCol}; defined $current_sheet-&amp;gt;{MaxCol} &amp;amp;&amp;amp; $column &amp;lt;= $current_sheet-&amp;gt;{MaxCol} ; $column++) {
            my $cell = $current_sheet-&amp;gt;{Cells}[$row][$column];
            if (defined($cell)){
                switch ($column){
                    case 0 { $transaction{&#x27;date&#x27;} = $cell-&amp;gt;Value || undef; }
                    case 1 { $transaction{&#x27;description&#x27;} = $cell-&amp;gt;Value || undef; }
                    case 2 { $transaction{&#x27;interest_date&#x27;} = $cell-&amp;gt;Value || undef; }
                    case 3 {
                        $transaction{&#x27;debit&#x27;} = $cell-&amp;gt;Value || undef;
                        $transaction{&#x27;credit&#x27;} = &#x27;0.00&#x27;;
                        }
                    case 4 {
                        $transaction{&#x27;credit&#x27;} = $cell-&amp;gt;Value || undef;
                        $transaction{&#x27;debit&#x27;} = &#x27;0.00&#x27;;
                        }
                }
            }
        }
        push @transactions, \%transaction;
    }
}

my $json = JSON::XS-&amp;gt;new-&amp;gt;utf8-&amp;gt;encode({&#x27;transactions&#x27; =&amp;gt; \@transactions});
print STDOUT $json . &amp;quot;\n&amp;quot;;

exit 0;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;GIST available at
&lt;a href=&quot;https://gist.github.com/ea0c6ef9e712e2caec88&quot;&gt;https://gist.github.com/ea0c6ef9e712e2caec88&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Requires Spreadsheet::Excel and JSON::XS - both available at CPAN.&lt;/p&gt;
&lt;p&gt;Have fun :-)&lt;/p&gt;</description>
  </item>
  <item>
    <title>Word cloud of my thesis so far</title>
    <link>https://www.klette.us/post/word-cloud-of-my-thesis-so-far-i-guess-you-might/</link>
    <guid>https://www.klette.us/post/word-cloud-of-my-thesis-so-far-i-guess-you-might/</guid>
    <pubDate>Wed, 15 Jun 2011 17:11:29 +0000</pubDate>
    <description>&lt;p&gt;Word cloud of my thesis so far. I guess you might be able to guess what
I’m writing about :-)&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;/img/tumblr_lmud34exFs1qizvg8o1_1280.png&quot; alt=&quot;&quot;&gt;&lt;/p&gt;</description>
  </item>
  <item>
    <title>apache2-mpm-itk and libapache2-mod-wsgi</title>
    <link>https://www.klette.us/post/apache2-mpm-itk-and-libapache2-mod-wsgi/</link>
    <guid>https://www.klette.us/post/apache2-mpm-itk-and-libapache2-mod-wsgi/</guid>
    <pubDate>Thu, 31 Mar 2011 10:58:00 +0000</pubDate>
    <description>&lt;p&gt;If you are running Apache 2 with &lt;a href=&quot;http://mpm-itk.sesse.net&quot;&gt;mpm-itk&lt;/a&gt; and
mod_wsgi on a debian system, you’re a bit out of luck performance wise.&lt;/p&gt;
&lt;p&gt;From the MPM-ITK documentation:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;mpm-itk is based on the traditional &lt;em&gt;prefork&lt;/em&gt; MPM, which means it’s
non-threaded; in short, this means you can run non-thread-aware code
(like many &lt;a href=&quot;http://www.php.net/&quot;&gt;PHP&lt;/a&gt; extensions) without problems. On
the other hand, you lose out to any performance benefit you’d get with
threads, of course; you’d have to decide for yourself if that’s worth
it or not. You will also take an additional performance hit over
prefork, since there’s an extra fork per request.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;So mod_wsgi in embedded mode will make apache load your whole python
project each request. That seems quite inefficient, so we’ll run
mod_wsgi’s daemon mode.&lt;/p&gt;
&lt;p&gt;mod_wsgi’s daemon mode launces background deamons that caches your
code, and even have have built-in support for running under mpm-itk. The
only problem is that for this support to be enables mod_wsgi must be
compiled against an mpm-itk patched apache 2. In Debian this is not the
case, so the daemon sockets will be owned by www-data and not the user
that you assigned to the vhost.&lt;/p&gt;
&lt;p&gt;You will see something like this in your apache error log:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[Fri Mar 18 13:11:40 2011] [error] [client 2001:700:300:9::188] (13)Permission denied: mod_wsgi (pid=22237): Unable to connect to WSGI daemon process &#x27;myuser&#x27; on &#x27;/var/run/wsgi/wsgi.22197.0.1.sock&#x27; after multiple attempts.,
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I’ve filed a bug with debian on this isses
(&lt;a href=&quot;http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=619252&quot;&gt;#619252&lt;/a&gt;),
but no responses yet.&lt;/p&gt;
&lt;p&gt;Luckely it’s not very hard to build your own mod_wsgi package to
support daemon mode under mpm-itk.&lt;/p&gt;
&lt;p&gt;Here is a quick how-to on the matter:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$ apt-get source libapache2-mod-wsgi
$ cd mod-wsgi-3.3
$ mkdir debian/patches

$ cat - &amp;gt; debian/patches/series
fix-mod-wsgi-for-itk.patch
^D

$cat - &amp;gt; debian/patches/fix-mod-wsgi-for-itk.patch
Remove #ifdefined for mpm-itk support, and only support mpm-itk, as we only use mpm-itk
--- a/mod_wsgi.c
+++ b/mod_wsgi.c
@@ -10037,11 +10037,7 @@
*/

 if (!geteuid()) {
-#if defined(MPM_ITK)
 if (chown(process-&amp;gt;socket, process-&amp;amp;gte;uid, -1) &amp;lt; 0) {
-#else
-if (chown(process-&amp;gt;socket, ap_unixd_config.user_id, -1) &amp;lt; 0) {
-#endif
 ap_log_error(APLOG_MARK, WSGI_LOG_ALERT(errno), wsgi_server,
&amp;quot;mod_wsgi (pid=%d): Couldn&#x27;t change owner of unix &amp;quot;
&amp;quot;domain socket &#x27;%s&#x27;.&amp;quot;, getpid(),
^D

$ debchange -i
$ dpkg-buildpackage
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;the resulting package will work as expected. I haven’t tested if it
works on any non-mpm-itk enabled apache, but I wouldn’t bet on it.&lt;/p&gt;
&lt;p&gt;Now, go forth and hack some python web apps!&lt;/p&gt;</description>
  </item>
</channel>
</rss>
