Mrz 07 2012

Random Hacks of Kindness in Hamburg

Random Hacks of Kindness ist eine weltweite Organisation (www.rhok.org) die Programmierevents für einen guten Zweck veranstaltet. Zu diesen Events treffen sich Programmierer und Kreative sowie Aufgabensteller an einem weltweit koordinierten Termin um gemeinsam Software zu entwickeln die einen Unterschied macht. Die Aufgaben kommen von NGOs, Stiftungen und sonstigen gemeinnützigen Organisationen.

Bis jetzt haben die Events in Deutschland nur in Berlin stattgefunden, Zeit das ganze auch in Hamburg zu organisieren. Hamburg wird am 2. und 3. Juni erstmals an einem globalen Event teilnehmen. Organisiert wird das ganze von einer Gruppe von interessierten: Florian Holzhauer, Wolfgang Wopperer vom Betahaus und einer Gruppe von freiheit.com, zu der auch ich gehöre. Den Ort müssen wir noch wählen, aber wir haben da tatsächlich den Luxus das wir Auswahl haben.

Aktuell befinden wir uns in der Phase das wir Aufgabenstellungen suchen die einen lokalen Bezug haben, oder zumindest deren Ideengeber in Hamburg sitzen, damit diese an dem Event teilnehmen können. Dazu haben wir schon mal eine kleine Ankündigung bei der Socialbar gemacht. Um die Ideen schon mal für das Event vorzubereiten treffen wir uns am 27. März um 19 Uhr im Betahaus um schon mal über die Ideen zu sprechen. Dazu sind alle die Interesse haben herzlich eingeladen. Wenn ihr kommen wollt tragt euch in diesem Doodle ein, damit wir ein wenig Überblick haben wieviele Leute kommen.

Wir werden ein großartiges RHoK HH machen. Es gibt auch schon ein Twitter Account über den dann Neuigkeiten kommen werden: @RHokHH.

 

Permanentlink zu diesem Beitrag: http://blog.thiesen.org/archives/2012/03/07/random-hacks-of-kindness-in-hamburg/

Nov 23 2011

Programming Concurrency on the JVM

The fun thing about Venkat Subramaniam’s latest book is the way he jumps to and fro between a couple of JVM based languages: Java, Scala and Clojure. He shows interesting ways to do given tasks in different languages and introduces a couple of interesting frameworks I at least have not heard of before. The most interesting frameworks he shows are Akka, which is an Actor Based Concurrency Framework, written in Scala but which comes with an API that is just as well usabale from Java. Furthermore, I knew the concepts of Software Transactional Memory but did not know that there are working implementations for the JVM. One of them beeing Multiverse.

 

I really liked the book, because I really like the idea of using a framwork implemented in Scala through its Java API in Groovy. Sometimes it gets quite tiresome to have many of the same examples just shown in different languages, but it is always good to practice Scala or Clojure reading skills. If you feel safe in Java concurrency, i.e. you now Concurrency in Practice by heart, I warmly recommend this book.

Permanentlink zu diesem Beitrag: http://blog.thiesen.org/archives/2011/11/23/programming-concurrency-on-the-jvm/

Nov 21 2011

Secrets of the JS Console

For some reason, up to until three weeks ago, I didn’t know that there is more to an API in the JS console than “console.log”. They API has been defined by Firebug first and is now more or less considered standard in all major browsers. Here is a short list of usefull commands:


$$('.foo') // gives you a shortcut to querySelectorAll

$0 // gives you the result of the last executed call

$1 // gives you access to the currently selected DOM Element in the Inspect view

clear() // clears the console

time('foo') // start Timing for foo

timeEnd('foo') // end Timing for foo

inspect( domElement  ) // shows the given dom element in Inspect view

The documentation can be found either in the Firebug Wiki or at Chromes Devtools Docs.

Permanentlink zu diesem Beitrag: http://blog.thiesen.org/archives/2011/11/21/secrets-of-the-js-console/

Nov 20 2011

Code with style: “get” means Getter

Properties are always accessed via method calls on their owning object. For readable properties there will be a getter method to read the property value. For writable properties there will be a setter method to allow the property value to be updated.

Java BeansSpec  (08.08.1997)

These three sentences have done something weired to my brain. The somehow completely rewired my brain to believe that every method that starts with get means Getter. And this comes with a price: I usually expect a getter to be an O(1) operation. I expect it to be the same three bytecode sequence that is a simple field access and a return. Nothing more. The same goes for a method that starts with set. I don’t expect them to throw exceptions, I don’t expect them to talk to the filesystem or to the network. Just a simple field access, nothing more.

And I am not alone.

Most of the Java programmers are somehow hardwired to have this JavaBean asumption. So naming a method that does more than a simple get or a simple set to an object field should not be named get or set.  If it creates something name it “create”, if it finds something name it “find”, if it stores something name it “store”. You get the idea. As I’m always on the reading side of code, I believe that the these naming conventions are quite good, but they are not only a convention on how to name something, but also a convetion on how to not name things. So if it is not a getter, do not name it get! When looking for alternatives,  Stephen Colebourne did a nice collection on common prefixes in the Java world.

Permanentlink zu diesem Beitrag: http://blog.thiesen.org/archives/2011/11/20/code-with-style-%e2%80%9cget%e2%80%9d-means-getter/

Nov 18 2011

Google Merchant Module for ROME

Google Merchant is the way a company can feed their products into Google Shopping and ROME is a Java Library to create and parse RSS and ATOM feeds. Google Merchant allows RSS as one of the feed formats you can use to feed them their data. In order to get additional information into ROME created feeds you have to implement 4 classes, so it is not really easy to get your data there.

I created a small Library to make RSS feeds that conform to Google Merchants requirements:

        final SyndFeed feed = new SyndFeedImpl();
        feed.getModules().add( new GoogleMerchantModuleImpl() );

        final SyndEntry entry = new SyndEntryImpl();

        entry.setTitle( "Title" );

        final GoogleMerchantModule merchantData = new GoogleMerchantModuleImpl();
        merchantData.setImageLink( "SOME IMAGE URL" );

        entry.getModules().add( merchantData );

It’s under MIT License up in Github, you can direct download the Version 0.1 here.

Permanentlink zu diesem Beitrag: http://blog.thiesen.org/archives/2011/11/18/google-merchant-module-for-rome/

Nov 16 2011

Code with style: Readability is everything

So, by now everybody got it: Code is there to be read by people, to be analyzed by people and to be understood by people. The fact that you can put it through a compiler and run it is a nice sideffect, but nothing to focus on. Besides writing readable tests of course.

But when software is growing and many different hands touch the same spots, it somehow gets dirty. So even when you have usually quite high coding standards, it still can happen that I stumble upon something like this:

User user = userService.createNewUser( email, password,
                                       false, true, null, 5 );

I like to be able to read a line of code like a line of text. Which means that I at least want to be able to get the “words” without the surrounding context.

So what would you be able to tell about the above snipplet? I would say: it apparently creates a new user, using some service and it requires an email and a password, which might be stored somewhere. And the point that makes me cry: apparently some magic flags, a nullable parameter and a magic number.

So lets see how we can clean this up with some new patterns. I usually make up my own names, if someone has a rather more common name for them feel free to comment, I will  be happy to replace them.

Enum as Flag Pattern (aka do not use boolean literals) 


enum FailIfExists { YES, NO };
enum NewPasswordChecks { YES, NO }

User user = userService.createNewUser( email, password,
                                       FailIfExists.NO,
                                       NewPasswordChecks.YES,
                                       null, 5 );

So, what can you tell about the method call now. The problem of methods that react to flags aside, the readability is better. You at least can deduct now that there might be no error if the user already exists and that it uses the “new” password checks. It is even easier to refactor to use the third password validation algorithm should it ever be changed again.

When setting up a new project you might try to disallow all boolean literals in certain high level classes, I don’t know if it works that well with third party libraries. This might be a cool Checkstyle rule to try.

No nullable Parameters Pattern (aka keep your implementation details internal)

So what is my next problem? Well, the given null parameter value. I believe that the ability to cope with null values is an implementation detail that belongs in the class that defines a method. So the UserService interface should provide us with an overridden version createNewUser that does not have the fifth parameter. Then the implementation could hide the fact that this parameter is really nullable. And it avoids the clutter of methods that have n optional object parameters.

If you use Findbugs in combination with the great JSR 305 annotations, which by the way can be enforced using a Checkstyle plugin, you might try to disallow using the Nullable Annotation in public methods. Maybe even for protected methods. In any case, you should never have to use a null parameter while calling a visible method of another class.

No literals outside constant definitions (aka give names to your magic numbers)

The last thing is a classic, but there are still a couple of people who do not use constants instead of literals. I think the general rule is that you should never use a numeric literal inside a method, but always a class declared constant. Furthermore this might even be extended to be valid for String literals and as told in the first point to boolean literals.

So let’s revisit my short (and bad) example taking the above mentioned points into consideration:


enum FailIfExists { YES, NO };
enum NewPasswordChecks { YES, NO }

private static final int INITIAL_NUMBER_OF_INVITES = 5;

User user = userService.createNewUser( email, password,
                                       FailIfExists.NO,
                                       NewPasswordChecks.YES,
                                       INITIAL_NUMBER_OF_INVITES );

Given that you might see this lines of code during a review, where you can’t browse the complete source of your project, one might now be able to better understand what this method does: it creates a new user with the given email and passwords, succeeds even when the user already exists, uses some mythical new password check and gives him an initial number invites of five. This can be guessed by just reading code, without a single line of JavaDoc and even without once visiting the declaring class or interface.

So in future, when writing code, try to consider if you would understand your method calls without ever having seen the implementation or even the declaration of the called method.

Permanentlink zu diesem Beitrag: http://blog.thiesen.org/archives/2011/11/16/code-patterns-readability-is-everything/

Nov 14 2011

Quickhacks: Visualizing contributions with git

Contributions for Git

So I had a little fun with git history visualization. Gource is there to show the progress of a repo over time, but I always wanted to get an actual snapshot of the repo at a given point in time. I wrote a little program, that basically does a “git ls-files” and then a “git blame -e” for all files that seem to  be source files. Then it resolves the Email-Addresses using gravatar and scales the image relative to the amount of lines the contributor is currently blamed for. The above image shows the visualisation for Git itself. It still needs some polishing, the algorithms for packing and sizing are all a bit off and not really correct, but mostly it creates nice imags. It is up on github if you want to play with it.

Contributions by Author for Prototype (the js library)

Contributions for pdf.js

Permanentlink zu diesem Beitrag: http://blog.thiesen.org/archives/2011/11/14/quickhacks-visualizing-contributions-with-git/

Nov 13 2011

Quickhacks: Github Event Widget for WordPress

A couple of days ago Github announced their new Event timeline API. As I wanted to have a nice widget for this blog but didn’t want to write any PHP I thought maybe they would do PJSON and I could implement a client side pure JavaScript solution. Apparently, they accept a “?callback=” Parameter to the request, so I using jQuerie’s excelent Ajax abstraction it’s plain simple to get your own feed:

var user = "marcus";
var url = "https://api.github.com/users/" + user  "/events?callback=?";

jQuery.ajax( {
             url : url,
             dataType : 'jsonp',
             success : handleData
            } );

Now you just have to implement the handleData method to do something nice to the data. Throw  in the excelent Moment.js and you got what you see to the right. The full script is in a Gist. 150 lines is still a little long but I’m not really in a golfing mood right now.
To integrate use a plain Text Widget for WordPress which includes the two scripts, given that jQuery is already somewhere there:
<script src="https://raw.github.com/timrwood/moment/master/moment.min.js"></script>
<script src="https://raw.github.com/gist/1328963/2054490501f09765cca086127377a9add4781f2c/github-events.js"></script>

<ul id="github"><ul/>
Feel free to fork and create your own. I did not map all events because I just wanted a selection to be displayed.

Permanentlink zu diesem Beitrag: http://blog.thiesen.org/archives/2011/11/13/quickhacks-github-event-widget-for-wordpress/

Nov 11 2011

Code with style: Exception handling antipatterns

There a couple of exception handling patterns that I come across regularly that I believe to be plain wrong or harmful. In order to get rid of them I’d like to present them here and explain the reasons why they should be avoided:

Log-Log-Log and Rethrow

Imagine a typically layered application design where you have a DAO layer at the bottom, a service or business logic layer in between and a frontend layer on top. Now imagine that you decided to wrap most exceptions from the lower layer and rethrow them with an exception which is more apropriate to the level of abstraction that you are currently on:

DAO Layer:

public T getById( Id id ) {
try {
 ....
 } catch( Exception e ) {
 LOG.error( e.getMessage(), e );
 throw new WrapperException( e );
 }
}
 

Service Layer:

public T doSomething( Id id )
try {
 T foo = getById( id );
....
 } catch( Exception e ) {
 LOG.debug( e.getMessage(), e );
 throw new WrapperException( e );
 }
}

This happens again in the UI layer. You usually do not have per layer logfiles, as this would make it harder to see the flow of the application. But when you log the exception on every layer, it leads to a lot of log clutter. The best way is to define a layer that logs the exception, the business layer being the obvious candidate here. Thus you have a defined way to handle lower layer exceptions. This pattern does not appear that often anymore, as unchecked exceptions are generally considered the better solution today.

Fail Silently

There are two versions of the fail silently antipattern:

Version 1:

 try {
....
} catch (Exception e ) {
// empty block<
 }

Version 2:

 try {
....
 return true;
} catch (Exception e ) {
 return true;
 }

The two versions of the Fail Silently Pattern have the same problem: you will never know that an exception happened. Combined with the fact that Exception is caught all kinds of runtime problems can be hidden. Usually, you should always catch specialized exceptions that you expect and can handle. If you’re doing frameworks or using libraries that might throw all kinds of exceptions, or you write handling code that needs to handle all kinds of exceptions on some way you still must log what is happening there. Otherwise you will never be able to explain certain behavior in production. And an exception handling block should never return the same value as the usual code path. After all it is an exception handling block.

Fail with least possible information

 try {
....
} catch (Exception e ) {
LOG.error("Something went wrong");
 }

There are two simple rules when handling exceptions: always log the exception including the stacktrace and always include any data which might have lead to the stacktrace. I still see it today that people discard all information directly at their fingertips to log out what they think might have happened at that point. Or what they have expected to happen. Together with to wide catch clauses this leads to the problem that you do not really know what happened in production, you just believe you know. Even worse, you might stick to assumption someone else made about the error at the point. So when you write a try-catch-block, always see that the variables used in the try are also logged out in the catch.

Deduct from vagueness

 try {
....
} catch ( Exception e ) {
 throw new CustomerNameTakenException( "The user already exists" );
 }

This is somehow the worst case of the above mentioned pattern. Here not only the wrong information is logged but it is used to create error messages. This might lead to all kinds of wrong behavior. Just because you know that a certain layer or lower level function behaves in a certain way does not make it an interface. Maybe a different exception is thrown, maybe something else went wrong.

As usual, these points are open for discussion. But I believe that these are some general rules everyone needs to apply when writing exception handling code.

Permanentlink zu diesem Beitrag: http://blog.thiesen.org/archives/2011/11/11/code-with-style-exception-handling-antipatterns/

Nov 09 2011

Was hilft wirklich bie Muskelkater

Inspiriert durch die steigende Nutzung von Fitocracy und den dadurch quasi erreichten Zustand von Dauermuskelkater habe ich mich mal ein wenig zu Muskelkater umgesehen:

Fakt ist wohl das Muskelkater durch die Beschädigung der Muskelfasern durch die Belastung entsteht und nicht durch Milchsäure. Dabei liegen die Schmerzen wohl tatsächlich an entzündlichen Reaktionen auf diese Verletzungen. Dazu gibt es folgende Infos:

Metastudien:
Treatment and prevention of delayed onset muscle soreness
Delayed Onset Muscle Soreness Treatment Strategies and Performance Factors
Various Treatment Techniques on Signs and Symptoms of Delayed Onset Muscle Soreness

Hilft:

Sauerkirschsaft
Sauerkirschsaft ist wohl entzündungshemmend, daher gibt es eine Studie die wohl belegt das man bei regelmäßiger Einnahme vor, während, nach dem Sport weniger Muskelater bekommt: http://bjsm.bmj.com/content/40/8/679.abstract

Ascorbinsäure/ASS/Aspirin/Paracetamol etc.
Widersprüchlich, im Endeffekt schwächt wohl Paracetamol sowohl die schmerzen als auch den Effekt von Training ab, daher wohl eher nicht so zu empfehlen. An die Studie für Aspirin komme ich nicht dran, die ist aber auch von 1988 und das scheint jetzt nicht das silver Bullet gewesen zu sein.

Warmes Wasser
Oh wunder, warmes Wasser, also schön in die heiße Badewanne, hilft wohl: http://www.ncbi.nlm.nih.gov/pubmed/21681159

Hilf nicht:

Vitamin C:
Kann man ja mal ausprobieren, hilft aber nicht: http://www.ncbi.nlm.nih.gov/pubmed/16998453

Massagen und Stretching:
Hat alles keinen großen Einfluss, ist wohl beides wegen der zusätzlichen mechanischen Belastung eher schlecht.

Am Besten ist es übrigens gar keinen Muskelkater zu verursachen, bringt nämlich auch nix: Muscle damage and muscle remodeling: no pain, no gain?

Permanentlink zu diesem Beitrag: http://blog.thiesen.org/archives/2011/11/09/was-hilft-wirklich-bie-muskelkater/

Ältere Beiträge «

» Neuere Beiträge