Sunday, 17 March 2013

Exception.when, for more readable and maintainable code

I recently started using a small change in my Java coding that seems to improve readability, testability, and makes maintenance a lot easier.

Instead of using IF statements everywhere to check and then throw business exceptions, I now modify  my Exceptions and call "Exception.when(...)".

So this...

User user = userService.getUser(userId);
if(!user.isLoggedIn()){
 throw new MyBusinessException("User is not logged in");
}

becomes...
 
User user = userService.getUser(userId);
MyBusinessException.when(!user.isLoggedIn(),"User is not logged in");

It really is a lot easier to read the code when written like this.

The changes to your Exception class are easy too. All we are doing is hiding the conditional inside a static function. Just add a method like this...

static void when(boolean condition,String msg){
 if(condition){
  throw new BusinessException(msg);
 }
}

I am mostly using this with a RESTful system based on JAX-RS, and I have to do a lot of condition checking,which was becoming a nightmare to read with all those IF statements. Now, it reads like a dream, well, rather like proper English, so a perfect DSL.

FYI: I did look into everything I could think of to make it easier to implement, ie: generics, inheritance, etc. But you cannot use static methods in either interfaces or abstracts, and exceptions are blocked from generics. So we are stuck implementing this method in every Exception Class, but I think it is worth it.



Saturday, 20 October 2012

Rooting a Momo11 Speed Android tablet

I just got my Momo11 Speed android tablet in the post.
It is rather flaky, and freezes a lot, so I am looking into it.

First things first...
roll back the firmware to 4.0.4...
but that needs a firmware backup...
which means rooting it.

So first task, root it.

I read around a bit and came across this blog post.
So risking unknown software, I installed ZhuoDaShi.
A bit more random button pressing (it is in chinese),
and it was rooted.

I verified this with Root Checker.

Monday, 8 October 2012

How to generate a 1 pixel GIF with dataURL in JavaScript

I recently wanted to use single pixel dataURL images in a project, but on doing some research (http://sveinbjorn.org/dataurls_css) I discovered I would have to create the images first and then convert them to base64, using tools like DataURL.net or http://boazsender.github.com/datauri/

I thought this was somewhat inefficient.

After a little more research, I found a good post on the subject of generating dataURL images for LESS, but it was incomplete, as although there is a jsFiddle, it never actually generates the data and it turns out there are a few bugs.

Time for a quick bit of work.... drum roll please...

Presenting: Single Pixel GIF dataURL Generator (edit)

Basically, I fixed the bugs, and added some UI to make it more useful.
Credit to Michel Jansen, as without his work, this would have been a lot more painful.

Monday, 10 September 2012

Debugging Javascript with Assert

I just put together a short video explaining my favorite new trick in JavaScript, using an Assertion function to call debugger at the correct point of failure.

I tend to spend my working hours at the moment writing large JavaScript systems, and while step debugging is great for eventually finding the cause of an error, it does take quite a lot of time to drill into a system to identify the bug.

In a large data driven system, I would think nothing of spending a hour or two finding the precise cause of an error.

Assert to the rescue...

JS.ASSERT.is(_.isFunction(displayFunc),true,"runDisplay:unable to find " + displayName);

Simply by asserting that my method parameters, or calculated variables, are the correct type / value, and calling debugger if the test fails, I can now identify the cause of a bug in under a minute. No matter how large the system.

Obviously you will want to reduce the overhead when the system is fully debugged and working, ie: in production, so simply prefix the assertion with a boolean condition. When set to false, the assertion will then never be evaluated.

JS.debug && JS.ASSERT.is....

That's all there is to it, a nice simple trick. But it will have a greater effect on your ability to debug and identify the cause of run-time failure than anything else I have ever seen.

The assert function itself is this:

ASSERT:{
        is:function(exp,expected,message){
            if(!(_.isEqual(exp,expected))){
                if(JS.debug){
                    // if you have got here, you have a serious error
                    // use stack trace to identify the cause
                    debugger;
                }
                throw new Error(message);
            }
        }

You can find it, and more here: https://github.com/rossillingworth/JS.js

That pretty much gives you everything you need anyway, but have a look at the video for a little more explanation.



Saturday, 30 June 2012

jRebel crashes appengine WebApp in Intellij

Just a quick note, to inform you about a problem with the new jRebel plugin ,v.1.4.4, for Intellij 11.1 on Windows 7.

I allowed Intellij to update the jRebel plugin automatically, and instantly my web app stopped working. I tried rolling back to the previous version, and it still failed.

Eventually I rolled back to version 1.4, and it started working again.

Friday, 20 April 2012

The business case for Scala


I will skip a lot of the functional stuff that Scala brings, first-order functions, better event handling, improved multi-threading with Erlang's Actors, comprehensions, etc. These are covered in details almost everywhere.

No, my favorite is simple.

The ability to write new language syntax constructs.

Think that through for a second....

Now that we are using OO and design patterns etc, the majority of our code is becoming a repeating series of boilerplate glue to stick it all together.

In fact, I would guess that 80% of any development project is now about writing and testing boilerplate.

What if you could identify and abstract it all away into your own syntax?

You would effectively have a DSL for your business domain.


For years we have used OO to encapsulate data and the methods to act on it,  but we never been able to do the same for the boilerplate glue, untill now.

I am unsure quite how to scream and shout enough to make you pay attention to the that little details, but it offers as much advantage to any development process as the whole change to the OO paradigm.

If you want to make a difference to your business embrace scala. They will love you for it.

Learning Scala or, a Java Devs new love affair

My last contract has finished and I am waiting for the next one to start, this means I have got some free time, for the first time since my daughter was born just over 2 years ago.

What would you choose to do?

Me, I settled down to the top task on my really rather long list.

Learn Scala.

Having just spent every day for the last week completely immersed in Scala, I am only now coming up for air. So what can I say about it, is it worth it? Will it pay off? Will I still be using Scala in 5 years time?

In a word, YES.

Let me explain...

I learnt and started using functional programming about 5 years ago, using JavaScript. But while I loved the concise nature of the paradigm, it is rare to find a client who will embrace it. Their web designers tend to write small jQuery event handlers, and the backend developers like the object orientated stuff, but neither is willing to spend the time to grok something outside their comfort zone.

Scala is something else. It runs on the JVM, so my clients have already got the technology platform, it is interoperable with Java, ie: you can continue to use everything you already know, so they can maintain their investment, and finally it adds functional programming to Java, which makes development faster/better, so they get more for their money. All in all, a perfect solution.

The downside? You need to be willing to embrace a new way of thinking. Functional Programming is a massive jump from imperative or OO, and quite a large learning curve if you have never learnt it before.

Fortunately, you can make the change in small increments rather than the one large jump required for any other language, and you can keep working.

I already know this one is a keeper. So expect to see quite a bit more about it.