Monday 20 December 2010

Fan Boys

1. What is a Fanboy
A Fanboy is someone that holds one particular thing be it a manufacturer, programming language or producer in high regard to the exclusion of all other alternatives without a logical justifiable and measurable reason.

2. Why I dislike Fanboys
I am a scientist by heart and a software developer by profession, this makes analysis my bible and the search for explanation my pilgrimage. Fanboys seek to get in the way of this quest for no obvious reason other than lack of interest in intellectual discovery and experimentation, this to me makes them unworthy of sentience.

The reason I make this seemingly harsh conclusion is that the thing separating us from beasts (I say the thing although there are many) is our ability and intonation towards discovery of facts based upon previously acquired knowledge in the same manner, rather than surviving on our instincts as beasts do we improve upon past breeds by education and investigation.

This is at odds with the fanboys stymied regards for investigation.

Tuesday 19 October 2010

Access properties as if they are constants

Goal
Sometimes it is nice to be able to access properties from a properties file in the same way as enums are accessed within Java. By this I mean that you can simply use the '.' (dot) notation and you get exactly what you expect.

for example with this enum

enum Colours { 
    BLUE(1), GREEN(2), RED(3);
    private int num;
    Colours( final int i ) {
        num = i;
    }
    int getValue() {
        return num; 
    }
}

you can expect that
int iCol = Colours.GREEN.getValue();
will not only compile but also give the correct number to iCol.
Now imagine that the colour blue is no longer to be represented by the number 1 but the number 7 instead, you would need to re-compile you enum in order to get the correct number.

Very Simple Solution
now take this code
enum KFType {
    type( "type", ConversionType.INT ),
    words( "words", ConversionType.STRING ),
    //example in overriding the getter
    special( "special", ConversionType.INT ) {
        @SuppressWarnings( "unchecked" )
        @Override
        T getValue() {
            Integer t = super.getValue();
            return (T) Integer.valueOf( t.intValue() + 10 );
        }
    };

    private ConversionType c;
    private String tag;
    private static final Properties keyFile = new Properties();
    static {
        try {
            keyFile.load( new FileInputStream( "path to props" ) );
        } catch ( IOException ioe ) {
            ioe.printStackTrace();
        }
    }
    KFType( final String t, final ConversionType con ) {
        c = con;
        tag = t;
    }
    T getValue() {
        return c.convert( keyFile.get( tag ) );
    }
}

@SuppressWarnings( "unchecked" )
enum ConversionType {
    INT {
        Integer convert( Object o ) {
            return Integer.valueOf( o.toString() );
        }
    },
    STRING {
        String convert( Object o ) {
            return o.toString();
        }
    };
    abstract T convert( Object o );
}

The disadvantage here is that in order to get any changed values from the properties file the jvm will need to reload the enumerated type which normally means a restart (I think). The big advantage here is that you can now use properties from properties file, or an xml file as if they were code.
I have also shown that you can perform some sort of transformation to the values read from the properties file, here I simply add 10 to the number read but there is no reason why we couldn't wrap text in an http url or something similar.
Look at the output of this
@Test
public void testEnum() {
System.out.println( ((Integer)KFType.type.getValue()) + 10 );
System.out.println( ((Integer)KFType.special.getValue()) + 10 );
System.out.println( KFType.words.getValue() );
System.out.println( KFType.special.getValue().getClass() );
System.out.println( KFType.words.getValue().getClass() );
}


12355
120
these are words
class java.lang.Integer
class java.lang.String

this is when I use the following properties
type=12345
words=these are words
special=100




Monday 11 October 2010

Kindle

Kindle I am probably the last person to provide his verdict about the Kindle, but I don't care here it is anyway. I have for sometime been looking for a good way to read books when not in my house. Being a developer I find that in order to read about a subject area I do normally tend to read several books side by side which is great when at a desk with plenty of space to spread out but not so great when on the move. I was quite surprised by the cost of the Kindle the only other device to come close in my opinion was the sony eReader and that was at least four hundred quid when I last checked. My kindle was £149 and it came with free 3G access to the kindle store plus I could actually browse the internet. It's not great at browsing the internet, but that's not what it's for. One thing it does do very well is that it has an 'Article Mode' that is great when reading wikipedia entries. The most important thing is that I could read it all day everyday when I was on holiday without getting eye strain or needing to recharge it. Whilst I was sat on the beach in the sun reading happily away it gave me great satisfaction to see people trying to read iPads and failing because of the glare from the sun and running out of power at inopportune moments like as soon as they get to the airport tee hee. All in all brilliant bit of kit, if it was any bigger then I wouldn't be able to put it in my suit pocket so I hope this never changes in future.

Sunday 22 August 2010

Goddamn UbuntuOne

Ubuntu One promised so much, I could sync my files between all of my machines and pickup stuff from different machines when in foreign countries e.t.c. Shame it fails to deliver! Ubuntu One keep notifying the world of their new features and future proposals which would be very nice, if they actually had the current features working. I have lost count of the number of times the contact system has been down, and the number of times notes and files don't sync up. Now the latest failure is the fact that it sees fit to go tits up and then replace my files with ...u1conflict thus rendering them useless to me. I thought it might be a bit of fun to use git and have the repository on my ubuntuone, hey I know this is not what git is intended for but thought it would be a simple way to clone to other machines in different localities. I was very wrong on this one, very wrong. After the initial ubuntuone sync on a new machine something had gone wrong and the source files failed to be copied over, oh well I thought I'd just do an old fashioned git clone over ssh which failed soon after it started with a simple failed message. When I looked at my file system .git was now .gitu1conflict, as this was a clone I simple deleted the folders ready to try again, this time though git wouldn't connect. So I logged into the original machine only to discover that ubuntuone had sync'd up with the original machine after I deleted the repository from the second machine, so the bidirectional sync meant that I had just lost all of my git projects. I am not a happy bunny!!! I should have kept backups even though they were just simple disposable projects I used for learning new stuff, so annoying.

Saturday 31 July 2010

Alonso, loser

a racing driver that seems unable to win a race without some form of cheating. He whines like a bitch with a grazed knee when someone is in front of him, and then to STEAL the race from his team mate 12 months after an accident that could have ended his carer is disgraceful. To win that race would have meant so much more to his team mate than to him, and after all of the words about helping the team the points gained by that shocking let through make no difference to the GP leader boards. A man that holds formula one with such contempt should himself be held in contempt. Alonso should be ashamed and so should Ferrari

Hooray, He's learnt

I am impressed by the way that Alonso has turned himself around, at least in my opinion. Lately he has been congratulating those that beat him, thanking his team for being good and generally being magnanimous in defeat. Also to be honest with his new opinion he seems to relish the fact that he will be (or rather is) able to compete against these people using driving rather than underhand politics.
Never thought I'd hear myself say it but he's turned around and I find him a much better racer for it, of course he still has to keep doing what he's doing to prove himself but so far so good.

Sunday 2 May 2010

Exceptional Exceptions

Exceptions

Exceptions and exception handling isn't something that should be difficult to do, and nor is it in Java. However the trouble with exception handling in Java is that no one can agree on a sensible method for handling them.

It is for this reason that I have written what I believe to be the most adequate way to handle exceptions, and the reasons for making these decisions.

I feel that the best way to get my point across is with some simple, all be it contrived examples. I am from this point on going to assume that anyone reading this document is familiar with the concept of a try..catch..finally block

Lets start with a bit of background, there are Throwables, checked exceptions, runtime exceptions and errors within java. The easiest way to categorise these and a some what glossy high level view is to say that every exception is a Throwable, so we shall ignore this semantic verb for now. A checked exception is an exception that a method may throw when it is called, by being a checked exception it gives the user of the API a sort of heads up letting them know that they should handle the exception in whatever would be the appropriate manner given the context in which the API was being used in. Then there are runtime exceptions, these aren't listed as possible outcomes of calling a method but they can be caught and dealt with if the API user believes it to be worthwhile, for example if the opportunity for an array to be incorrectly accessed is a possible outcome of a method being used then perhaps some programming logic can be put in place to mitigate the problem slightly, this sort of issue is usually an indication that a better design should be put in place so that, for example, an array is never incorrectly accessed. Then there are errors, it is true to say that these more often than not should never be caught as they tend to be things that are not recoverable such as OutOfMemory which means the status of the JVM can no longer be relied upon.

Good practice when designing an API means that the usage is examined from the perspective of a typical user, I prefer to use Use Cases to examine the problem from the users perspective. For anyone not familiar with this method it simply means putting together a story of the course of events of a user using the particular API call. The useful thing about use cases is that there is a specific section set aside for what should happen as an exceptional case which can then be related directly to the implementation of the solution.

Example

As an example lets imagine a simple system in a hotel lobby that is used to lookup the room that a person is staying in by using their name as the search criteria. The Use case might look something like;

  1. type name of guest
  2. hit search*
  3. system displays the room number
Immediatley at point 2 we can think of an exceptional case, when the guest is not present in the hotel, this would result in an API that looked much like
public Integer getRoomForGuest( String guestName ) throws GuestNotFoundException;
Now behind the scenes the getRoomForGuest method may be accessing files, or a database or some other magical method of storing guest against room numbers, the point is that the user of the API shouldn't care about the fact that a FileNotFoundException or a SQLException may occur as this betrays the inner working of a method. Imagine the system is upgraded in the future from using a file system so that now it uses a database, if the API used to throw FileNotFoundException or IOException it would surely now have to throw a SQLException. Therefore through having a checked exception that is tighly coupled to the underlying implementation when the method implementation is altered the developer would have to alter every location where this method was called, and if the API was being used in another company their code may stop working which could result in them having to re-design/implement a new solution and this added cost could convince them to stop using your API. A friend raised the point that this could cause an exceptions true cause to be lost, I took it for granted that if anyone catches an exception they will as a matter of course add it to any exception being thrown as the "cause". Another point to raise here is that we should throw any exceptions that we really can't deal with. In the example above you could safely assume that an adequate response to not being able to find a person in the directory due to a FileNotFoundException or other IOException would be to say the person could not be found to the user. However many real life calls are not this simple, for example a with a different call it may be acceptable to inform a user of FileNotFoundException and other prescribed obviously solve-able exceptional cases but any other IOException that occurs should be considered more serious. In this case I would make the method call throw CallSpecificException (not the real name just an example) and IOException. The idea here is that the caller of our method would catch the specific exception and most likely tell the user but anything else would be dealt with differently most likely throwing to a higher authority in keeping with the idea of escalating exceptions that our caller can't directly deal with. Read on this idea should become clear.

I hear many people argue that we should not use checked exceptions instead make everything a runtime exception. I find this a little ...well...foolish, you see by having checked exceptions an API designer can give a hint to its user that here is something that could go wrong, or be out of the ordinary and you should think about how to handle it. The designer of the API is surely going to be more knowledgeable about the types of things that can go wrong during the operation of their code. If we were to replace these checked exceptions with runtime exceptions then the API user now has to either instinctively know what could possibly go wrong within someone elses code, which might be closed source and undocumented which means the only hint of what exceptions may occur is the method signature which now no longer has any mention of exceptions, this is why it seems a nonsense to turn everything into a RuntimeException.

Throwing and Catching

Another issue with exceptions seems to be when should they be caught and when should they be thrown, some people believe code should catch every Exception and some people believe you should catch nothing!!!Crazy surely we want to deal with exceptions that are pertinent to the code which has caused it and throw or escalate any exceptions that we weren't expecting and hence have no clear knowledge on how to recover from.

Lets look at the first option, catching every exception. By deciding that you want to catch every exception must mean that you intend to write code that can suitably handle every possible exception, that's fine until it isn't, that is to say in the typical mundane run of the mill processing, exceptions that you expect could happen are dealt with exactly as expected. However programs have a tendency to change like the shifting ice of the North sea, and with this change comes brand new exceptional cases that were not part of the original design. So where does this leave us? We are now catching an exception that we don't know what to do with, so our program responds by logging the problem and continuing as normal. The problem could be a simple one for example couldn't find a config file or something that any user should be able to rectify, or worse it could be a catastrophic failure that could be avoided if only the right people were notified, for example an upstream service has failed preventing a circular queue from being processed and thus will start to wrap around after X number of failed calls anyone handling a large throughput can understand just how serious a problem such as this can be. Many people still believe that the best, and sometimes only thing to do with exceptions is to log something exceptional occurred and continue. This denies the intent of exceptions they are not all meant to indicate that something went wrong in the program but merely that a path other than the norm should be pursued within the use case.

The next option is to catch nothing, i.e. throws Exception should be written at the end of each method signature. I see this as lazy coding, and not the good kind of lazy that leads a developer to automate repetative processes, but the bad kind of lazy that turns into a birds nest that someone else will have to unravell at a later date. The only thing this kind of coding goes to serve is to provide fodder to the WTF Blog. So should we never throw exceptions at all? Simple answer of course we should throw exceptions, but only when the design intends it to. Consider the throwing of an exception to be the escalation of an exceptional case, everything is being executed within the stack and the higher up this stack the more prevalent the process. What I mean by this is that in general the higher up the stack we get the more likely we are to want to shout about an exception happening, by thinking about this process it must surely seem obvious that if your code can't immediatley address the exceptional case occuring then it should let a higher authority know about it. Take the earlier queue underrun issue, you API deals with a small portion of the overall system that relies on the queue, your code doesn't know how to deal with this problem so it should escalate the issue by throwing it.

No one should see a Stack trace

This is both true and false, if no one was ever to see a stack trace there would be no need for them. In fact seeing a stack trace is very useful in solving the issue. I think this mantra has come about due to the fact that most developers are lazy when it comes to putting in simple handling code, we see it all the time an NPE occurs on some web server somewhere and the user gets shown a stack trace. The trace is useful to a developer (usually) but pointless to someone who is simply trying to buy something from the site. It is incredibly easy to redirect the user somewhere to say there has been a problem please bare with us while we try to fix it whilst at the same time sending the stack trace to someone that knows how to deal with it. The fact that this doesn't always get done is simply laziness.

...or at least only see a meaningful stack trace!

Not all developers were created equal, not all developers know how all parts of the systems they work with function, not all developers have the necessary skills to fix all problems a system can and will encounter during its normal operation. It is for this reason that 1st, 2nd and 3rd line support even exist. What might mean something to a 3rd line guru might as well be a foreign language to a 1st line and sometimes vice versa. By throwing specific checked exceptions at an appropriate level the correct trace can be sent to the person (or system) that can handle the exceptional case in the most appropriate manner. Working on large international systems it makes sense to have context sensative logging that will send stacks from a US system to the US support rather than to an Asian support desk or the user.

Conclusion

We all want to make systems that are good, that we can be proud of and say I don't think anyone could do a better job, it is for this reason that some forethought must be put into what exceptional cases are going to occur that I can deal with and anything my code can't deal with should be escalated. It is lazy to catch all exceptions with a catch (Exception... that simply logs what went wrong and continues.

Monday 1 February 2010

a sign of things to come

I love Sun Microsystems always have done, they gave us java which has allowed me to accomplish so much with computers. I used to feel all warm inside when I drove past the Sun building on the M3 near Fleet, and I even loved their little Sun Spots as a bit of academic fun. However now good ol' Larry has his mits on it I just don't feel the same about it. Even the oracle icon leaves me feeling ... well nothing really it evokes no emotional response what-so-ever. Now I have tried to register a copy of Glassfish v3 and got this, simply by requesting my id. This shouldn't happen, have the people at Sun lost their pride, or have the lovely people from Oracle already taken their soles to dark place? Who knows, who really cares other than geeks like me.

HTTP Status 500 -


type Exception report

message

descriptionThe server encountered an internal error () that prevented it from fulfilling this request.

exception

java.lang.NullPointerException

note The full stack traces of the exception and its root causes are available in the Sun GlassFish Enterprise Server v2.1 logs.


Sun GlassFish Enterprise Server v2.1

Wednesday 6 January 2010

British people annoy me

I am really really really fed up of people moaning about Britain being the only country to suffer with snow. I was at a bus stop the other day and a woman was telling me about how the rest of Europe was fine and functioning as normal in the weather. The reason this angered me was because I happened to be standing in the bus stop with a few friends who had that day come over from the Nederlands and they said it was the same over there and Germany too. I hate it when people make up there minds about something like this and tell anyone who will listen that their opinion is fact, when it blatantley isn't, 5 seconds of searching and I found this article that PROVES the bogus reporting. http://www.dutchnews.nl/news/archives/2009/12/snow_causes_traffic_problems_i.php Imagine my surprise when the news channels (in the uk) also do all that they can to sensationalise the whole situation, for example a woman was reporting infront of a massive 6ft snow drift by the side of the road, however as the report wrapped up the camera did a 360 view and (a)where she was standing was the only area that still had snow and (b)the 6ft snow drift had been man made by people clearing the road of snow and dumping it all in one place. Why can't people be honest!
 
Stack Overflow profile for Richard Johnson at Stack Overflow, Q&A for professional and enthusiast programmers