A Funny Java Flavoured Look at the World

Saturday, June 24, 2006

The frantic checking in of code before a weeks holiday

I'm off for a weeks holiday so there will be no blogging for me for a week. It is always a bit of a panic the day before you take a weeks holiday.

The frantic checking in of all code

trying to tie up all the loose ends

It's always a big motivator when you can see the finish line and know its just one last push. Of course on the other side there is that thought which says well I don't mind what work the development team gets in because I am not here, it does'nt effect me.

I had to pass my work on to my fellow developer, it's a bit of an awkward situation when you have to pass on some work for someone else to finish. It's always difficult because you first have to understand what the code should be doing and then what the code is doing and finally how to change it so it's doing what it should be doing. Anyway sorry about that if you are reading this.

It was interesting handing the code over because I wrote an email to explain the flow of the program I had written. Doing this gives you a good overview of your code and lets you review it a bit. I was pleased with the way most of it was designed and implemented. So hopefully my fellow developer should pick up the baton fairly easily.

Of course this handing over of work never goes smoothly and there is always the horror story of someone having a file checked out or a file not checked into source control but is only on their local machine. This can be a danger of everyone working on their own machine, you can't always identify the dependencies. This was one of the reason we recently brought in a weekly build at work, so we can test everyones latest code works and compiles with each other's code.

So for the small fan base who read my blog, you too will also have a week off from reading my blog, hopefully the break shall do us both good. Of course a week seems like a really long time at the moment, it will probably only feel like 2 days when I'm actually there before I'm dragged back to work.

It's an interesting time for me to go on holiday with regards to my blog because this blog entry

http://hoskinator.blogspot.com/2006/06/10-tips-on-writing-reusable-code.html


got more people onto my blog than a six weeks month of blogging about other topics. Still it will probably mean that people might bop along to read that from their link in delicious or digg etc and the blog traffic will still be the same.

Friday, June 23, 2006

Design in Construction - Code Complete 2 sample chapters

I have heard of the book Code Complete mentioned a few times on blogs and on Amazon and have even read a review of it a few times. On Amazon used sellers list there is a surprisingly small amount on their and it is priced at about £20, so my guess is that once people buy the book they don't sell it.

Code complete is what I would call a Programming process or Developer book. It's not just concentrating on one language but on techniques and approaches that can apply to Programming in general. What I am trying to get at is that code complete is a book not just about writing code but looking at the other parts of the job that being a programmer entails, like designing architecture, Refactoring, Debugging. Although Code Complete 2 seems to concentrate on more programming than other books which I would put into a similar category like Ship it! Programmatic programmer etc etc.

I have read good reviews and heard good things about Code Complete and Code Complete 2 so I was interested to see if there were any sample chapters available.

it has a welcome chapter which is what you would expect, brief intro and all that

http://cc2e.com/docs/Chapter1-Welcome.pdf

It also has this Design in Construction chapter which is a whopping 51 pages and discusses designing your code before you head on in and start to create the classes

http://cc2e.com/docs/Chapter5-Design.pdf

The first five pages I felt were a bit patronising but then as the chapter starting to go onto more technical or practical stuff I found it more interesting. Having read articles and books on the subject alot of it was hearing good advice again but there were also parts which I hadn't thought about or heard before. Also seeing all the points about design did make good sense and gave a comprehensive approach to designing.

I have to admit I found the chapter very interesting and well written, it was very detailed but without too much waffle. I am very tempted to buy the book.

I like to peruse the contents of a book to try and get an inkling to see if I think it is going to be useful and I have to admit I like the look of the sections

Laying the Foundation
1 Welcome to Software Construction
2 Metaphors for a Richer Understanding of Software Development
3 Measure Twice, Cut Once: Upstream Prerequisites
4 Key Construction Decisions

Creating High Quality Code
5 Design in Construction
6 Working Classes
7 High-Quality Routines
8 Defensive Programming
9 The Pseudocode Programming Process

Variables
10 General Issues in Using Variables
11 The Power of Variable Names
12 Fundamental Data Types
13 Unusual Data Types

Statements
14 Organizing Straight-Line Code
15 Using Conditionals
16 Controlling Loops
17 Unusual Control Structures
18 Table-Driven Methods
19 General Control Issues

Code Improvements
20 The Software-Quality Landscape
21 Collaborative Construction
22 Developer Testing
23 Debugging
24 Refactoring
25 Code-Tuning Strategies
26 Code-Tuning Techniques

System Considerations
27 How Program Size Affects Construction
28 Managing Construction
29 Integration
30 Programming Tools

Software Craftsmanship
31 Layout and Style
32 Self-Documenting Code
33 Personal Character
34 Themes in Software Craftsmanship
35 Where to Find More Information

Thursday, June 22, 2006

Function pointers in Java

I was writing some code this week where I passed in an interface which was used in the internal working of the code. I had seen this used once in the Collections framework where you pass in the comparator interface.

I will let Sun describe the Comparator Interface, here's a link if you wanna read it all http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Comparable.html

"This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.

Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this interface can be used as keys in a sorted map or elements in a sorted set, without the need to specify a comparator."

here is the method summary

int compareTo(Object o)
Compares this object with the specified object for order.

Basically it is used if you want to add a method to sort objects of the same type because the objects will be sorted using your compareTo code.
When you are using the comparator when sorting a collection you pass in the comparator and then when the Sorting code is run it does something like

Comparator.compareTo

so it uses the code you have written in the compareTo method with some other sorting code. What is really happening here is that you have passed a function into a class/method.

Why am I talking about his well it was because I didn't know what doing this was called but I have been using this and creating interfaces to pass into a class to change how the class acts. I didn't really know if this had a name but I refer to it as the Interface Framework Pattern. The reason I call it that is because the class you are passing the interface into then becomes a framework and the interface you pass in, fits into the framework of the class but alters what the code the framework runs.

Whilst wondering what this was called I read item 22 in my Effective Java book by Joshua Bloch and he has a section called substitutes for C Constructs (I haven't ever programmed in C) and item 22 is called "Replace function pointers with classes and interfaces" and he describes what I had been doing with my classes but in a much better way and with good grammar and no spelling mistakes.

He states that this type of code is basically using the Strategy method to swap strategies or a sorting pattern in the comparators case. Effective Java also recommends that you make the class a Singleton because you it doesn't hold any instance variables. I hadn't done this on mine, so I nipped back and made a few changes.

The examples of the code where for similar type of things. The first was reading in a text file and the second was for polling/watching a directory for a text file.

For the polling a directory example I used the FileAction Interface with the two methods, directoryChecking which returned a boolean and Action. The DirectoryWatcher class was the framework and it was passed in the FileAction interface assigned the value of my concrete class implementing the FileAction Interface. The DirectoryWatcher extended the TimerTask and every 30 minutes set off it's run() method. In the run method I took the Interface and did

FileAction.directoryChecking - this method checked for a certain file.

if the directoryChecking returned true then I would run the FileAction.Action()

Which in this case would process the file. If someone else wants to check a directory then they could right a concrete class that implements the FileAction interface and change the type of file or files to check for and then write a different action and not have to change the framework class.

What I really like about this coding style is that by taking the Interface as a parameter rather than implementing it the methods can be kept private and not accessible outside of the class. Initially I thought about using an abstract class to achieve a similar result but I would have had to make the methods protected so that they weren't visible outside of the package.

Wednesday, June 21, 2006

Java Glossary

I found this really useful site from the Canadian Mind Products it has a Java Glossary. It has a Java section with useful sections like
Java Cheat Sheet
Java FAQ
Java Gotcha's
Scope of variables
installing Java
Generics
Interface vs Abstract
Jar
JDBC
Collections
The site is well thought out with useful sections and useful in a practical way. I found the File section really useful and the Gotcha's was good. I have used this site a few times and came here a few times by just searching for things in google. I like the way it is split up into topics which make it very easy to navigate and also seem quite interesting.
It's a useful reference site

Using the File class

I was doing some work on checking a directory for a file and then processing the file. This meant I had to use the Java's File class. It's a bit wired to start with having an object for a File especially in Java because File can be either a directory or file. I'm not sure whether having the File class be a directory or file is a good idea because it often means you have to check if a String directory path has created a File which is a directory or a File which is a file.

The File class is very easy to use and does have helpful isFile and isDirectory methods but it seems like you have to some extra checks. The advantage of course is that you can pass a directory and file about under the same Class. Thinking about it as I'm writing it probably isn't that much different from having a Directory and File class which extended an Abstract File class, you would still have to do some checking somewhere.

Don't get me wrong I'm not really moaning about it, I found the File class really good to use and it has some useful methods.

I found a really good page on the File class with useful snippets of code and a brief description of the methods you are likely to use.

http://mindprod.com/jgloss/file.html

I decided to make a static helper file with some methods which combined some of the File objects functions together, like making a directory and then a file and making a File instance from a String of directory and filename, checking it was exists, it was a file (not directory) etc. I'm not really sure about making static helper files but in this case I didn't want an object with an instance, just methods. Also the methods didn't hold any variables just took in a variable and returned a different one.

There are a few gotcha's with the file class. Here are the one's I can think of on top of my head

File can be a directory or a file.

If you pass in Null I think the file exists will return true.

You cannot delete a folder if there is a file(s) inside of it.

When you create a file with a new directory it doesn't create the directory, you have to use the mkdir() or createNewFile() methods

The deleteOnExit function only deletes when you code finishes, so I don't think you can use it between methods (e.g. in a junit test). I'm not totally sure when it deletes the file but I found that between my tests in a junit class the directory and file wasn't deleted.

One other bit of functionality that I like with the File class is each file has a deleteOnExit() function. This is good for writing unit tests or so I thought. I found that the folder or file is only deleted when the code exits. So this meant that I had to write a function which checked for and deleted the file and then folder.

Another interesting function the File has is that it can create unique temporary files and it gives each a file a random number on the front of it.

I quite enjoyed my time with the File class unlike some of the other classes in the Java framework this is very straight forward

Monday, June 19, 2006

10 tips on writing reusable code

I have been trying to increase code reuse in the projects I have been doing recently. In my first few years of coding I hardly ever got to reuse any of my code because it was always too coupled together and dependant upon other parts of the code.

So recently I have been trying to write code which I can reuse. It has been interesting that since I have been doing this I have noticed that my library of code is starting to grow. I have started to create more Static Helper classes with useful methods in. I have also been removing the business logic away from any Struts actions or framework work.

To do this I have tried to do a number of things to help this and these are the sort of rules and things I do (in no order) to help me try and achieve this. They are a number of rules and tips I have picked up but can't remember where from

1. Keep the code DRY. Dry means Don't repeat yourself. This is one of the main changes I have tried to bring in. Always try to eradicate duplication and if you find any then move remove the duplication to a relevant place. Sometimes this has lead me to create Static Helper classes or sometimes move it to the class it makes most sense to have it.

2. Make a class/method do just one thing. This is along the lines of the advice of giving the class only one reason to change. This often means creating methods that other methods use but this helps to make the methods/classes simple and less coupled.

3. Write unit tests for your classes AND make it easy to test classes. Writing code that is easy to test is decoupled. If you write code and are thinking about writing a unit test for it then you tend to split up the code into smaller testable chunks.

4. Remove the business logic or main code away from any framework code. Following the rules above will help this. An example I have seen is code that is inside Struts Actions classes, this code is practically impossible to reuse because of all the Struts dependencies that it now linked with.

5. Try to think more abstractly and use Interfaces and Abstract classes. Try to hide dependencies of code behind a more Generic interface/abstract class. The benefit this gives the code is it creates a flexible point in the code where you can then hide future changes behind.

6. Code for extension. Write code that can easily be extended in the future. This is particularly true with the above point. If you write code that uses interfaces then you can extend that interface at a later point.

7. Don't write code that isn't needed. Do the simplest thing possible. Don't waste your time adding methods and classes that might be used in the future. Keep the code simple and focused on what you are trying to deliver. I think I read/heard Josh Bloch say once that "if in doubt, leave it out". Basically who wants to write code that no one (including yourself) is going to use again.

8. Try to reduce coupling. When writing code think about the links and coupling the code is creating, does it need to be linked to those other classes.

9. Be more Modular - make your code more modular, think modular, be modular.

10. Write code like your code is an External API. Imagine the code you are writing is a self contained component.

It wasn't going to be ten until I got to 8 and then thought no one writes 8 tips, lets add two more on. It isn't really a list but it's sort of aims and mental notes I try tell myself when writing code. They are more small bits of code I have written recently that has helped. I would like to hear people's comments and especially their tips on writing reusable code

Saturday, June 17, 2006

Action Class Design Guidelines

We were investigating an OutOfMemoryException this week and as usual the way I investigate such things is to whack them in google and then pick out the useful websites. This is usually a decent method and solves a lot of problems. The problem that occurred to me is that it does take a bit of thinking and problem solving skills out of the loop.

If I had thought about it a bit more I would of perhaps thought (but then again maybe not) where should I look, rather than just typing the problem into google and then following the links that might help you. I suppose when the links on google don't work you then have to use your brain a bit and then think about where you should look. In this case I had been advised by Billy Bob Bain who replied to a blog entry of OutOfMemoryException

I think I would have thought about it and headed off in that direction, if google hadn't made me so lazy.

Of course there is the other side of the argument which is that googling things can take you down very interesting paths and often you will get very useful information, very quickly.

Back to the programming in Struts, firstly I was quite shocked and a tad embarrassed I had never read the Struts user guide but better late than never. This section was interesting about designing Action classes especially the part about using only local variables and not instance variables. The research we had done actually showed us this although it took a while for us to understand the logging and what it meant.

I agree with the part that all the business logic should be taken out of the Action Class. My view on action classes is that they should be just an access point into your business logic code and they should pass on some relevant variable information and then retrieve and pass back the results. Currently we have a few classes where some of the business logic is mixed in the action class. Although in some cases there isn't actually much code in there, I don't think this matters because it means that we can't use any of the code in their again.

Having business logic inside the Action Class is also a bit like some old school JSP's which had html and scriplets all mixed, I think most people consider this a bad idea these days and don't do it, this is the same thought I have with the Action Class code. It also makes it very difficult/impossible to test the code and write unit tests for it.

Finally it means that your business logic code is held prisoner by the Struts framework, so what happens if you want to change frameworks in the future, a lot of messy rewriting and copying across.

I like the error catching remark, not many developers probably write software which takes credit cards but it would certainly make you think twice if you just entered your details to then be confronted with a stack trace error message.

Here is a link to the webpage where this data was taken from Struts User Guide and below is a quote from the document, below is the bit I found most interesting

4.4.1 Action Class Design Guidelines

Remember the following design guidelines when coding Action classes:

  • Write code for a multi-threaded environment - Our controller servlet creates only one instance of your Action class, and uses this one instance to service all requests. Thus, you need to write thread-safe Action classes. Follow the same guidelines you would use to write thread-safe Servlets. Here are two general guidelines that will help you write scalable, thread-safe Action classes:
    • Only Use Local Variables - The most important principle that aids in thread-safe coding is to use only local variables, not instance variables , in your Action class. Local variables are created on a stack that is assigned (by your JVM) to each request thread, so there is no need to worry about sharing them. An Action can be factored into several local methods, so long as all variables needed are passed as method parameters. This assures thread safety, as the JVM handles such variables internally using the call stack which is associated with a single Thread.
    • Conserve Resources - As a general rule, allocating scarce resources and keeping them across requests from the same user (in the user's session) can cause scalability problems. For example, if your application uses JDBC and you allocate a separate JDBC connection for every user, you are probably going to run in some scalability issues when your site suddenly shows up on Slashdot. You should strive to use pools and release resources (such as database connections) prior to forwarding control to the appropriate View component -- even if a bean method you have called throws an exception.
  • Don't throw it, catch it! - Ever used a commercial website only to have a stack trace or exception thrown in your face after you've already typed in your credit card number and clicked the purchase button? Let's just say it doesn't inspire confidence. Now is your chance to deal with these application errors - in the Action class. If your application specific code throws expections you should catch these exceptions in your Action class, log them in your application's log (servlet.log("Error message", exception)) and return the appropriate ActionForward.
It is wise to avoid creating lengthy and complex Action classes. If you start to embed too much logic in the Action class itself, you will begin to find the Action class hard to understand, maintain, and impossible to reuse. Rather than creating overly complex Action classes, it is generally a good practice to move most of the persistence, and "business logic" to a separate application layer. When an Action class becomes lengthy and procedural, it may be a good time to refactor your application architecture and move some of this logic to another conceptual layer; otherwise, you may be left with an inflexible application which can only be accessed in a web-application environment. The framework should be viewed as simply the foundation for implementing MVC in your applications. Struts Action Framework provides a useful control layer, but it is not a fully featured platform for building MVC applications, soup to nuts.

Friday, June 16, 2006

22 per cent of UK employees admit to having illegally accessed sensitive data such as salary details from their firms employer's IT systems

I found a coupling of interesting articles on the Register

This article is about the use of instant messaging at work,

http://www.theregister.co.uk/2005/05/16/akonix_im_survey/

it comes out with this quote
"One in six (16 per cent) of 2,000 UK consumers quizzed in a YouGov survey admitted using IM at work to send or receive sensitive company information or documents."
It is funny when I tell my Mum or Girlfriend that we use MSN Messenger at work. They often say why do you write messages to people who sit right near you, why don't you just talk to them.

The other interesting article I found was this one

Brit workers love to snoop

the article has some fantastic statistics

"Nearly a quarter (22 per cent) of UK employees admit to having illegally accessed sensitive data such as salary details from their firms employer's IT systems. More than half (54 per cent) of 2,200 adults polled during a YouGov survey said they'd forgo any scruples to do the same, given half a chance, according to a Microsoft sponsored survey that points to a culture of internal snooping and casual identity theft in offices across Britain."

"Survey respondents said that HR and payroll information was the most popular target (36 per cent), followed by their manager's personal notes (28 per cent) and their colleagues' data (25 per cent). Given the chance, six per cent said they would pinch a colleague's password."

The survey also says that 33 percent would be prepared to access confidential files in their previous employers if they still had the passwords. The information in the article is not really shocking, it's probably the most interesting gossipy details you can get about your work colleges. Although I don't think I could do it because after knowing things like salary details you would be dying to tell someone else, otherwise what's the point in knowing it.

Extending Properties Files

I developer at work came up with a novel idea regarding a properties file we use in our software. This properties file has to be changed for some properties to be set. This means letting the user change the file, this means that sometimes they can get set with dodgy values.


One of the other advantages is that sometimes when we want to upgrade a user sometimes it easier to reinstall a new version and then copy the their settings like properties files and a few other config files back. There is also times when we have to add things to the properties file when they upgrade etc.


Basically what I am trying to say is that it can be a source of syntax bugs by misspellings, incorrect values etc.


He came up with the notion of have a properties file and then have a custom properties file. Any values in the custom properties file overwrites the value in the properties file. This custom properties file is exactly the same as the properties file except all the values are commented out.


When a customer/user wants to change a value they can uncomment the value and change it. This allows the customers to see what values are in the (default) properties file and always have a value there if they need to go back to the value. It also will mean that we can also easily see the values they have changed, which should help to speed up finding any problems in the properties file. Lastly this should make it easier to upgrade users because we can just replace their properties file and leave their custom properties alone.


It also works well in a programming sense because it is like extending the properties file and overwriting the values they want overwritten and leaving the other values as they were. I also explained to the developer that it fits one of my favourite programming practices or something else.


“closed for change but open for extension”

Thursday, June 15, 2006

Constructor Initialization is the way to go

I read this article tonight on Martin Fowlers blog about ConstructorInitialization.

http://martinfowler.com/bliki/ConstructorInitialization.html

I have recently been favoring making objects immutable by passing in the variables the object needs and then only supplying getter methods for the variables. These objects are usually data objects used to pass around data fields that are related.

It was since using the final variable more and reading Effective Java where it recommends you make objects Immutable as often as possible. I agree with this logical because a lot of the time once you have set the values you don't really ever need to change them again, so why do you need to supply setter methods. Not to mention that setter methods increases the chance of passing in null values.

The article does state this as a reason for using this method
"Constructor initialization is the approach where you try to ensure that you always create a class in a valid state by passing in all the collaborators that the object needs in the creation method of the object."
It does also have the benefit of creating thread safe objects. It seems odd really that so much documentation talks about encapsulation and telling everyone to put getter and setter methods around their private variables but you rarely here of them saying, create the class, initialize it with variables and then don't let them change it, put only getters in. I think they should, I think people should think about whether they will need to change an objects state (internal variables) at a later date and if they don't then don't put the setter methods on there.

I view this decision a bit like making variables private which is hide as many variables as you can, the less developers can see and change the internal workings of your class the less likely they are to break it and find/create a bug.

Requirements documents - are they beneficial?

We have decided in the development team to write a requirements document for new functionality, I say decided by it was a more a case of a senior developer saying he did it and found it useful for a the following reasons

1. You get the requirements signed off by the customer, this increases the chances they are getting what they want and you both have something to work from.

I'm always willing (most of the time) to take on new ideas especially from Senior developers who have learnt through experience (otherwise known as the hard way) so I thought I would give it a go. I also keen to give it a go because the last piece of work I did didn't have a requirements document and it ended up with me having to add bits on the end because I didn't know they were needed.

I have to admit I got a bit confused to start with mainly of the wording and what kind of technical level I should go in. My first draft ended up a bit of shambles, half requirement, half assumptions and have technical solution. I did feel it was a benefit to go through the project and work out exactly what needed to be done and the different things.

I got the senior developer to have a look at the document and he recommended I move bits about and move the solution into a technical spec. He suggested I should try and write the document from a user point of view and what they would expect, this made a lot more sense to me.

I haven't written the second draft yet. The second draft is feeling a bit more like hard extra work but nothing is as difficult as the fearsome "blank page" of the first draft. So is writing the requirements document a benefit. I have to say I think it will be because it will allow me to get to an understanding with the customer as to what they expect from the project and to what I am going to deliver. The requirements document will help to get rid of the fuzzy points of the project and give me something to work from.

I have also found it is has been quite beneficial in terms of planning the work because as I am writing it I am learning more about the project. It's also quite useful to show other developers what I am working, it also gives an easy way for them to help you out by saying how they would tackle the work and perhaps any code they have written (which you might not be able to find easily) which could help on the project.

So at this point I am giving the requirements document the thumbs up.

Wednesday, June 14, 2006

Don't catch and throw exceptions

I found this in the code today

catch (final Exception e) {

Logger.log("DatabaseSearch - createFeature - Exception" +

" whilst creating the xml file to return " + e.getMessage(),

Logger.ERROR);

throw new Exception(e.getMessage());

}

because I have turn PMD back on it told me I was being a fool, to create a new Exception and then throw it. I have to admit I am not sure of the best practise of exception handling because it is usually a bit of an after thought or because the way Java works, it makes you catch, throw an error so I usually do enough just to get the code to compile. I know this isn't right but I usually put down as something I will do later and then usually forget. I have seen a few blogs complaining about this and I think they have a point but on the other hand it does make you do something. I suppose the question is does it make you do something to catch the Exception or enough to stop the JVM complaining. I will leave that discussion for another time.

This is one of the main benefits of things like PMD, Checkstyle, fingbugs, it raises warnings on your code and then explains why. For someone like myself who is trying to write better code. It's really useful to have good coding standards shown to you using your own code and then you get a description on why the code is not to a standard and what rule it is breaking. Sometimes the rules are a bit over the top but even if I disagree it makes me think about my code more.

So back to the

"Caught Exception is rethrown, original stack trace may be lost"

and

"avoid throwing raw exceptions"

Now looking at this legacy code, okay I admit it I wrote it, I have to admit it does seem rather odd thing to do , catch it and then throw it with the same error message. I can see why it was done though because it has allowed the code to log out some useful information like class, method and a message saying "error whist creating xml file". The stack trace would show the information and if the exception was thrown then the error message which is probably the most important thing will still be the same. So after looking at this I think I should listen to PMD's advice and just throw the error rather than catching it logging it and throwing a new exception just like it.

Basically I think you should either catch or throw an exception, you don't need to do both. Pretty basic stuff I know but at least I know why now.

Tuesday, June 13, 2006

OutOfMemoryException and investigation

We were investigating an out of memory exception today, these problems are the worst kind of problems to find, well not so difficult to find but can be tricky to solve them.

It's so hard to find out where the problem is and then when you do fixing them is really difficult. I think it's one of the major weakness of many Java programmers is that sometimes we have a bit of a lazy style when it comes to memory management because we usually trust the JVM to come and help us out and of a jam and Garbage collect all the objects we have left dangling.

We have done some sniffing about checking the Tomcat server logs and seeing how much memory is being consumed. It also brings me onto the subject of load testing, I haven't ever really done any load testing, except for one occasion where we got 20 people from the company to all go through a test script and log times between events/pages etc.

It's funny that we leave this testing until last because after that it is going to be difficult to change it. When you look at code and think how can I optimise the memory usage here, the main things you can come up with are minor improvements. To have a real effect on the memory usage I think you are really going to need a bit of redesigning of the objects used and left dangling.

It's always interesting to look at your code in a heuristic way and it does help to give you a good understanding of the code and look at parts you don't often look at. Plus any improvement/optimization and refactoring of the code can only be a good thing, as long as a bug doesn't slip in.

We were looking at the Struts actions today and we believe that any instance variables in an action is shared between any call that calls that action. This means that firstly these variables are hanging around and secondly two separate instances of the same action could be sharing variables in an unplanned way. This gives us something to investigate and probably create a best practice not to use instance variables in base actions and only use static finals and to pass in the other variables.

I did google OutOfMemory Exception in struts but nothing came up so if anyone has any knowledge on the subject or links to articles please add them in on the comments. I have discussed Java and Memory management on a blog entry before http://hoskinator.blogspot.com/2006/04/is-memory-management-in-java-garbage.html

Pay for certified IT skills up 2.6% in 2005, pay for non-certified up 4.4%

I saw this fact today, which shows you that being certified doesn't guarantee you a higher pay rise, although it doesn't really seem to indicate what the wages were just that the percentage increase wasn't as high.

I suppose I hope getting certified will increase my wage but I think the real benefit is the learning needed to obtain the certification, the knowledge.

here is the quote from ZDNET

Pay for certified IT skills up 2.6% in 2005, pay for non-certified up 4.4% by ZDNet's ZDNet Research -- In 2005 pay for non-certified IT skills grew nearly 70% more than pay for certifications, or 4.4% versus 2.6% respectively, according to Foote. Premium pay for 103 non-certified skills in Q1 2006 averaged about 7.1% of base salary for a single skill, up from 6.8% in Q1 2005.

SCJP 5 - Collections / Generics Resources

I found this very good link to a Generics and Collections tutorial for people studying for their SCJP Java 5 exam. I think Generics and collections can be quite difficult due to the number of tricky facts you have to learn.

Generics in particular is quite difficult because it is quite different from the normal Java code and firstly puts in the odd looking angled brackets <> and then also uses extends to mean interfaces and classes. It also has a number of gotcha's regarding the type of classes that can be passed into a generic method/class. Generics can be quite restrictive which can create some very tricky exam questions, so all the extra information is welcome.

SCJP 5 : Chapter 6. Collections / Generics (Part 1)
SCJP 5 : Chapter 6. Collections / Generics (Part 2)
SCJP 5 : Chapter 6. Collections / Generics (Part 3)
SCJP 5 : Chapter 6. Collections / Generics (Part 4)

I have posted information other blog entries with resource links for generics before, here are the links if you need some more information

http://hoskinator.blogspot.com/2006/05/generics-gotchas.html

http://hoskinator.blogspot.com/2006/05/collections-and-generics-in-java-5.html


http://hoskinator.blogspot.com/2006/04/generics-sample-chapter-pdf.html

Friday, June 09, 2006

Where should you check for NullPointerExceptions

I was tempted to check for null the other day in a method and then I thought that you could really check for nulls in all of my methods. So I thought this must be a bad idea because otherwise it would be more common and what can you do if you find one.

I thought about catching the null -- no if someone has passed in null it's their fault

should I return null value - I don't think passing back a null value is good form

perhaps I should just throw a NullPointerException, yes good plan, so I thought I would just leave the code and let the JVM keep throwing it up until it found somewhere.

I was slightly confused and there isn't much information about it, I have blogged about this issue before, where I chose the wrong idea and caught the null and returned a value. This actually caused another bug until I went back and threw a null or actually didn't do anything and changed the code that called it. Initially I decided to catch the null and pass back a zero. After some good comments I changed my thinking on this, many thanks to the people who commented on that blog entry.

The issue of catching a null did result in a much sneaker bug being put in because I caught a null and returned a zero in a removing fraction function (dodgy I know) but the zero's caused a map with length and height of zero to be drawn. Basically if you passed in zero we didn't want any maps to be drawn later on, so instead of catching the error I sort of hid it, which was bad bad bad.

It does bring up a tricky question where do you decide to catch this null.

Anyway this blog has a decent stab at working out the logic

"Step one is usually removing unrequired optionality; replacing pointers that can't be null with references and removing any, now redundant, checking code. As soon as see a function that takes a pointer and immediately checks it for null you know you can remove the 1 or 0 optionality of a pointer and replace it with the certainty of a reference. Like retrofitting const correctness; once you do it in one place, you can chase back up the call stack until you find the point where the value really is optional. Things like this are simple to do but they vitally important in keeping code under control and understandable. By reducing the amount of things you have to question when you read a piece of code you can make the code easier to understand; no need to worry if this pointer can be null if you're given a reference that can't ever be. "

I like the point the quote is making that basically there is some point higher up in the code where the object/class might be null and this is the place to check it and the lower more simple code just has to assume that in most examples you are going to put in a valid object.

It certainly has a catch 22 type feeling to it and I can't seem to find to much information or best practices for it.

Should you always refactor code?

I read this blog again today Things you Should Never do, Part 1

It reminded me of a chat I had with another developer the other day, he was discussing some legacy code and he came to the conclusion that we should really refactor all of these classes. I have to admit that I wasn't so keen. I enjoy refactoring, watching the code transform is quite enjoyable.

but.... (I know you saw that coming)

I wasn't so sure it was worth refactoring all this code because it did currently work. Although it would improve the code most of the code were a set of seperate actions and refactoring them wouldn't have much improvement on the other code. I think I basically felt that we could use our time more productivily doing other things. I was in favour of a bit like are new junit test writing policy, if you change the code, write a test. Now we also have if you change the code, refactor it.

Of course most of the code doesn't have unit tests for it either. This can make writing a unit test and refactoring the code a bit tricky.

I appreciate that we will probably have to refactor the code when day and it maybe whilst fixing a bug but I had the line of agile programmers

"do the simpliest thing that works"

I was thinking the simpliest thing is to leave the code until we are in there for some reason. On the other hand though I can feel the code will leap up and bite us on the ass at some point in the future but if it does then we fix it and if it keeps working then let it keep working.

It is also a bit over whelming when you have quite a few classes to refactor, it feels a bit like writing the unit test after you have written the code, it becomes too much of an effort, an effort it seems at the time for no reward.

In the end we didn't really have a decision to make because we were busy working on a couple of projects but it got me thinking, should you always refactor code? What code shouldn't you refactor.

I suppose this must be a popular discussion between developers and talking about refactoring is a tricky subject because by its nature the outward benefits of refactoring are making the code easier to maintain, extend and reuse but it should do eactly the same as the smelly code you have removed.

This article talks about the decision in a more detailed manner than me

http://www.symphonious.net/2006/05/28/when-should-you-rewrite/

Thursday, June 08, 2006

Good cop, Bad cop

I was interviewing today at work. I remember when I first interviewed someone, not that long ago, I thought it was soo exciting, what responsibility. Then after the first one they are rather boring.

It is interesting sitting on the other side of the table and asking the questions instead of being on the end of them. It's funny really but you ask a question to usually get a small answer back which shows me you understood the topic of the question I asked. You probably don't really have to know in fantastic detail, just tick the box of knowledge. The number of different answers you can get to the same question is amazing, in fact you almost never get the same answer. The people who don't know the answer but give you a politicians answer of answering the question they want answered can be annoying. My favourite type of answer is people who mention technologies in correctly and trying to throw in keywords.

In today's interviews there was two of us doing the interview. We used the good cop bad cop technique and I got to be the bad cop. So after my partner introduced the company, bit about the job, asked them about themselves then I come in with some juicy technical questions. Things like

"what are your technical strengths and weakness"

"how do you keep up with new technology"

"tell me about a project you are proud of"

I will explain that the position we were interviewing for was an action script developer who is also okay with Flash. I have only basic knowledge of these topics but it's useful to get second opinions when interviewing and if nothing else different people come up with different questions.

We had a bit of difficulty trying to find a flash developer who is a wizard with action script. Most the flash people seem to be heavily into their designing and not so much interested in the action script.

It was interesting that although the interview told us a lot, I think we learnt the most when they showed us examples of their work, a program speaks more than a 1000 words.

The thing I found most surprising today was how long interviews take, we had three interviews and they seemed to take up most of the day.

The question I have always wanted to ask in an interview was

"is a Jaffa cake a cake or a biscuit"

although it says cake I think it is without a doubt a biscuit. If anyone has any advice on interviewing people please add a comment.

Joshua Bloch: A conversation about design

I read this interesting article about API Design and reuse from Joshua Bloch being interviewed by Bill Venners. The article is from 2002 but I think the points are still relevant today.

I have found that the Java developers I have worked with and including myself don't reuse much of their code. The problem usually occurs because the code written is often tightly coupled with the project they worked on to create it. I think Bloch makes good points stating

"Decomposition into subsystems is important, but as important is to have each subsystem be a well-designed, freestanding abstraction"

I think this is something that doesn't occur often enough. If people split the work into small self contained modules/components then these could be reused in other projects. I have found recently that I have been trying to make sure that my methods will have "only one reason to change" this sometimes means creating more methods but it creates methods that don't depend on too many variables or are tightly coupled with code you are currently writing. This also means that if I want to reuse these methods/classes then it should easy.

I often find that these changes happen when I am refactoring and trying to eradicate duplication. This article puts to words what I have been thinking about and trying to do whilst writing code recently. If you write code like this it is also a lot easier to write unit tests for. Writing unit tests can be a good guide, if you are struggling to write a unit test for some code then perhaps the code is doing to much.

I like this question

"Venners: You also claim in your book that thinking in terms of APIs tends to improve code quality. Could you clarify why you think that. "

I have been trying recently whilst trying to write smaller methods with one focus and then use the smaller methods in bigger methods etc. I have been trying to think of my code as a library or code. I have been trying to think about the code as an API, I suppose basically trying to create a self contained component which I can use again.

I don't know why I have been trying to do this more recently, I think it's because I want to be able to reuse more of the code I write and looking back at the code I have written before I can see that it's very difficult to reuse the code because it isn't really very modular and not very cohesive. The code I have written in the past seem to try and do to many things which ends up that lots of the code is too dependant on each other and means I can't take bits out and use them in other projects.

Anyway I found the article really useful as I do most of the articles involving Mr Bloch.

http://www.javaworld.com/javaworld/jw-01-2002/jw-0104-bloch_p.html

Wednesday, June 07, 2006

An Interview explaining the benefits of Agile Development

I'm sure like me you have heard the term Agile Programming mentioned in many blogs. I will admit that were I work we don't really have any system we use. I also find that implementing all the rules of the various systems seems a bit too much like hard work.

It seems to me like the new ideologies are based on best practices (unsurprisingly) but they all are a slightly different flavour and they all seem to miss out important parts like uml modeling, design patterns, no documentation (sounds good).

As you can tell I don't really know what I'm talking about but I'm willing to learn so when I found this link about some people talking about Agile programming and how they use it/implement it then I thought it would be interesting. The link is a page with a number of talks on, they were done in 2005 so it's not that up to date.

There are some talks/interviews where you have to register but there are some on the right hand side which are free. The interview I watched, although there is an mp3 and it's written down if you would like to read it, was

Agile Development & Agile MDA Scott Ambler and Jon Kern
The interview goes over real world experiences with agile development, lessons learned, the value of documentation, how modelling should fit into the development cycle, and more.
it tackles some interesting questions like these
1. What does it truly mean to be agile?
2. What is not agile?
3. The Agile movement has been around for a few years, what are we seeing? Where are we in the state of things?
I have to admit I quite like some of the ideas behind Agile development but don't take my word for it, listen to some people who know what they are talking about.

Debugging code - the hard way

I have spent the whole day debugging, it makes value unit tests (junit) even more than usual.

Debugging is such a difficult job when you can only test the code through the front end and checking the extra logging you have put in. The main problem I have with the code I was debugging was that it was using a struts action and almost all of the code was in the main method in the action. This basically meant it was practically impossible to test the code without using the front end and clicking and then reading the log files.

I have done a bit of refactoring but because it took me soooooo long to actually find where the problem was and then why it was going wrong, I am only doing a bit and to be honest it works and it's an action, which is pretty much self contained so it's not that much benefit refactoring it.

Today was a classic case of "everytime you fix a bug you are in danger of adding another bug" which I blogged about earlier blog entry The bug I am fixing today wasn't in the release a couple of releases ago. We found this out by my idea of setting up a running copy of the last few releases so we can easy test the code the different customers are seeing. Anyway the code works fine there so this at least gave me some clue where to start the search on what might be causing the bug. The code was actually a result of someone fixing another bug.

The bug was also quite sneaky because it was a base class that was changed the bug has filtered up which meant it was very tricky to find.

I find bug fixing can be quite boring and frustrating, especially when you are doing it like I was today by using logging messages. I must have wasted loads of time adding comments, recompiling the servlet and stopping/starting Tomcat and then running the program.

The plus side of debugging is that you do get to know the code in detail and sometimes it's quite nice not having to write to much code. Although I do get the feeling of restlessness and like I haven't really done much that day.

The best reason I heard why you should write unit tests is

"you know how long it will take to write a unit test, how long does debugging take"

Saturday, June 03, 2006

Ship It!: A Practical Guide to Successful Software Projects - sample chapters are well worth a read

I have read about the book Ship it, it has been mentioned by quite a few blogs I have read. Then the other day I stumbled upon one of the authors blog. Anyway I thought I would see I would have a look for any of my favourite free sample chapters and like any book worth it’s salt it had a couple. The book is about development process and is meant not to focus just on one programming language but to develop process useful to different programming languages. I have to admit I like this books because I believe that actually writing the code is a small part of being a developer, it’s the process, designing, testing, building, interacting that uses up more of your time.

The introduction which I’m not usually a fan but I would even say that the introduction is pretty interesting and gives what seems an honest account on what the book is and how to use it.

http://www.pragmaticprogrammer.com/titles/prj/introduction.pdf

One bit I find a bit unusual about the introduction is it talks about using a content management system. I cannot believe that people don’t use one these days unless they are very small and even then you would think they would. It left me a bit unsure what the rest of the book and what it may contain.

But the introduction redeems itself and gets back onto more interesting ground.

The second free chapter is a lot more interesting and useful, it basically seems to be a few useful excerpts from the book, which make a few tips.

http://www.pragmaticprogrammer.com/titles/prj/tips_tech.pdf

The second free chapter I found to be quite interesting and although I have something similar to the List which it recommends using, it’s isn’t probably as useful as the system they are suggesting.

To summarise the chapter recommends to have a prioritised list and you tackle the top priorities (not the easy one’s at the bottom) first. It also states that you should be able to mark them off, so they have to have an achievable target, something you can tick off.

I enjoyed reading the two sample chapters I thought I would have a look at Amazon to see how much the book is, here's a link

I also thought I would look at the content of the book. I like the look of this book and might try and get my company to purchase it for the team (well I can but try). Even if the company won’t buy it, it is only £10.66 on Amazon, which is pretty good value for money

Foreword Preface 1 Introduction 1.1 Habitual Excellence 1.2 A Pragmatic Point of View 1.3 Road Map 1.4 Moving On 1.5 How Should I Read This Book? 2 Tools and Infrastructure 1. Develop in a Sandbox 2. Manage Assets 3. Script Your Build 4. Build Automatically 5. Track Issues 6. Track Features 7. Use a Testing Harness 8. On Choosing Tools 9. When Not to Experiment 3 Pragmatic Project Techniques 10. Work from The List 11. A Tech Leads 12. Coordinate and Communicate Every Day 13. Review All Code 14. Send Code Change Notifications 15. Putting It All Together 4 Tracer Bullet Development 5 Common Problems and How to Fix Them 16. Help! I’ve Inherited Legacy Code 17. Testing Untestable Code 18. Features Keep Breaking 19. Tests? We Stopped Using Them 20. But It Works for Me! 21. It Hurts When I Integrate Code 22. Can’t Build the Product Reliably 23. Customers Are Unhappy 24. You’ve Got a Rogue Developer 25. Your Manager Is Unhappy 26. Team Doesn’t Work Well Together 27. Can’t Get "Buy-in" on Essential Points 28. The New Practice Didn’t Help 29. There’s No Automated Testing 30. We’re Junior Developers, With No Mentor 31. We’re on a "Death March" Project 32. Features Keep Creeping In 33. We’re Never Done A Tip Summary B Source Code Management C Build Scripting Tools D Continuous Integration Systems E Issue Tracking Software F Development Methodologies G Testing Frameworks H Suggested Reading List H.1 Bibliography

Friday, June 02, 2006

Communication helps coding

Two months ago a developer left and then now he has found out he doesn't like it the new place and is now coming back. It's funny how even though you are doing basically the same job that working in one company can be so different to working in another company.

When working with the developer in a small team of 3 it was a very different working atmosphere. People were dished out their piece of work and then we never really spoke to each other until it was sort of finished or we were having a meeting every now and again. It was also made very clear to me that he was the "senior" developer and I wasn't. So he would often disappear to have meetings about architecture or design decisions.

It has a number of odd effects. I often had no idea what the hell he was doing and I also didn't have inkling how his code was designed or how it worked or often what it was meant to do until it was finished and released and then I saw it as a customer would see from a user end point of view.

Then he left and I decided that I didn't really like this way of working, it's if nothing else a bit bloody miserable. I thought I should take the opportunity to try and mould the working environment to be more informal, more enjoyable and to bring a more collaborate working environment.

When the developer (we shall call him developer X) left he gave what we call some Christmas lectures (they are some boring lectures shown on TV at Christmas in England) on parts of the code he had done and telling us how they worked etc.

I thought this was a brilliant idea, so now we have them after someone has done a substantial piece of work so the whole team knows how it works, why it works like that. This also has the benefit of looking at others people's code and learning new tips and tricks.

We also have meetings to discuss how we are going to design parts of the code or perhaps the best way to tackle problems. We also have a tea break at 11am and all have a 10 minute break.

I like the way we all work together now, we have got rid of the "Hero Programmer" and are now a team "X men" of mutant programmers.

The main benefit is that it's more fun talking and interacting with your fellow developers.

Other he is coming back now, I think we have moved in the right direction that he will have to join the group, only time will tell.

I'm in code debt

I'm currently in a bit of code debt. For those of you who don't know what code debt is, it is basically some smelly code and when you come to fix it, instead of refactoring it properly you instead slip in a dirty hack. This generates code debt because instead of fixing the problems you have squashed in a change which basically puts off the refactoring until the next time someone has put in a fix or extend the code. This is quite a good way to explain to boss/management types why you need to refactor code because slipping in a dirty fix is a bit like spending money on your credit card, you are just building up the debt but one day you will have to pay it back (fix the code)

Why am I banging on about code debt, well the reason I am talking about it is because of the state of my unit tests. The actual tests work and I have certainly felt the benefits of them and have more confidence in the code they are testing, not to mention the excitement of seeing the green bar pop up after a successful test.

The Junit tests are pretty smelly with quite a bit of duplication etc. I put some of this down to me being fairly new to writing Junit tests but also I wasn't sure whether you need to keep the code in junit tests neat and tidy, well to an extent. By the nature of junit tests they are sort of repetitious because they keep testing similar code. So in a few cases I have copied the majority of one test into another and modified it.

That was on my first batch of junit tests. I have modified my approach and now create variables like

result
expected result
testStringValue
testIntValue

and use this same variables in all the tests but wiping them in the tear down and reassigning them in each test. I have decided not to go back and change the previous smelly code junits and modify them only if I am modifying the class or don't pass. I'm not sure how far to go when creating junits, how much code to put in them and should they be to the same standards as the code they are testing.

I have had a brief look but haven't found many articles on coding standards or best practices for junits. I think if I keep persevering I should start to create some kind of standards and I think I need to work on improving them. The only nagging thought is that when you are writing junits they don't need to be of the same quality as standard code because you are unlikely to extend them or debug them. I suppose I will have to pay this code debt when I have to change the class and then change the junits.

I would be interested to hear comments of people who write junits and their approach.

How can programmers earn extra cash

I saw this entry on a forum a while ago and put it in my list of things to blog about in the future when if I haven't got any inspiration. This was an entry about moonlighting (doing extra work after work) and whether anyone knew the best way for a programmer to make some extra money in his spare time, here is the entry
"Re: Moonlighting Opportunities?
At 7:55 AM on May 8, 2006, JMJ wrote:
Does anyone have any suggestions on the best way to start doing a little "side" work? I've been doing development/design/architecture and even management for several years. I make a good living but would like to take in a little extra cash by doing some side work for a while, something I can do from home a few hours a week or so.

First, is this even realistic? In my career I've pretty much relied on a cohesive team, but with the advancement of outsourcing this doesn't seem to be so necessary for a lot of people.

Second, what's the best way to get started? I've looked at sites like rentacoder.com, but are these legitimate, and can you really get paid for this? I don't want to be wasting my time, just get paid a little for some quality side work...

Just wondering if anyone has any thoughts on this...thanks! "
The thought of spending your day programming and then coming home to and programming for some extra cash sounds very unappealing to me.

That was my initial thought but funnily enough I had wondered what moonlighting opportunities there are, I think probably all programmers have thought about this at one time because extra money is always good.

Even now though it doesn't really appeal to me but the time I go home I have usually had my fill regarding of programming and work. I usually want to do something different like playing football or TKD, slobbing about in front of the TV, reading, pretty much anything but do more work. Not that I'm saying I don't go on the computer when I'm at home, I do a bit surfing, blogging and sometimes a bit of investigation on new technologies or interesting bits and bobs.

This is very different from work, the ideal scenario would be to get some programming job that was fun and you got paid for it. In real life though I can't really believe this is going happen. I enjoy working but most of the time the work I do at work isn't that sexy or interesting it's standard stuff and sometimes (especially the afternoons) it's a slog. For every interesting bit of work you do at work there must be at least 10 bits which are pretty boring and standard programming fodder.

I found the responces to the question very interesting because I didn't really have a clue.

The first response is someone from http://www.TopCoder.com which is where they will set a coding competitions and then the winner basically gets some cash if these solutions are used. It could be sort of fun but still seemed like work for me but it has some good links on there and I did listen to the Java Posse's podcast when they went to live TopCoder event.

The next response mentioned rentacoder but said they didn't pay you much. A few of the other responses made a very interesting point. Basically these sites didn't pay much because you are in competition with people from India, China and Russia where there general wages are a lot lower. One of the responses mentions that you could earn more working at your local fast food joint as you would writing code for some websites.

Another response states that you should be careful working for other companies when moonlighting because there might be something in your work contract which might prohibite such activities. It's unlikely they would find out but you never know.

The final answer I really like it because it basically says why don't you just find a better job that pays you more, which probably seems like the real problem in this case.

I find it a very interesting question and answers, have a read
http://www.javalobby.org/java/forums/m92015908.html

Thursday, June 01, 2006

The dangers of assuming customer requirements

I have learnt this week, never assume anything when writing an application for a customer. It reminds me of a lecturer I used to have who said

"never assume, it makes an ASS out of U and ME"

Very witty and completely correct. Often when writing applications customers will only offer half solutions leaving a lot of the work for you to guess and everyone knows that if you leave a developer to guess he will do the logical thing, which of course isn't what the customer wants.

Usually when in this situation I correspond with the customer regularly to ask them to decide how they would like things to work but in this scenario I was upgrading an old application and bringing into a new framework. This has resulted in me making some assumptions which after further investigation into the problem have turned out to be slightly wrong. Nobody really knew how it worked until I showed them what I had done and then they would say well it didn't use to work like that.

I tackled the project so that I was expecting change so making the amendments hasn't been to much of a problem and have done it along with the refactoring of the code. The work this week has made me appreciate the small iteration philosophies of many practices (Test Driven Development, Agile, XP etc) and how beneficial it is. Firstly customers needs will often change once they see the program working, so it I think it is important not to go to far down one solution because they might change their mind which may result in having to code the solution in a different way.

Working in a small coding/testing cycle means that you can refactor your code often which allows you to use the insight you have obtained writing the code to become useful. What I am trying to say is that once you have made a solution you now know what you need to do and you can look back over the code and see what can be clipped out and what parts can be brought together.

The main point I have learnt this week is, As much as humanly possible create a clear set of requirements on how the application should work because otherwise you could be wasting your time creating something that the customer doesn't want.

The Java Developers Almanac 1.4

I find this site today, well I found it because it was one of the Java Series books that Sun promotes but this one had a website, which means I can see the goodies for free.

it is similar in some ways to Java Tips, which I have blogged about http://hoskinator.blogspot.com/2006/04/java-tips.html
except that this site is purely just code examples where as Java tips does have explanations as well.

The code examples are split up into packages but it does have a useful search facility where you can search for the code example you are interested in. The obvious down fall is the code examples are for 1.4 and not 1.5 and it hasn't been updated for quite a while.

It gives you just a short concise example of the code you are interested in, I always like seeing an example and then changing and modifying it to do want I want, it always seems a good starting point e.g. you have something that works and then you change

If anyone has any other code example site's like this I would like to hear about them and mention them in the comments if you would be so kind.

it has some good sections on java.sql, java.text and java.reflect and lots more

a few examples of the type of things featured on the site

e332. Breaking a String into Words
e338. Comparing Arrays
e340. Converting a Collection to an Array
e365. Reading and Writing a Properties File
e320. Formatting a Date Using a Custom Format
below is the entry for Formatting a Date using a Custom Format
e316. Formatting the Time Using a Custom Format

A pattern of special characters is used to specify the format of the time. This example demonstrates some of the characters. For a complete listing, see the javadoc documentation for the SimpleDateFormat class.

Note: This example formats dates using the default locale (which, in the author's case, is Locale.ENGLISH). If the example is run in a different locale, the text (e.g., month names) will not be the same.

Format formatter;

// The hour (1-12)
formatter = new SimpleDateFormat("h"); // 8
formatter = new SimpleDateFormat("hh"); // 08

// The hour (0-23)
formatter = new SimpleDateFormat("H"); // 8
formatter = new SimpleDateFormat("HH"); // 08

// The minutes
formatter = new SimpleDateFormat("m"); // 7
formatter = new SimpleDateFormat("mm"); // 07

// The seconds
formatter = new SimpleDateFormat("s"); // 3
formatter = new SimpleDateFormat("ss"); // 03

// The am/pm marker
formatter = new SimpleDateFormat("a"); // AM

// The time zone
formatter = new SimpleDateFormat("z"); // PST
formatter = new SimpleDateFormat("zzzz"); // Pacific Standard Time
formatter = new SimpleDateFormat("Z"); // -0800

// Get today's date
Date date = new Date();

// Some examples
formatter = new SimpleDateFormat("hh:mm:ss a");
String s = formatter.format(date);
// 01:12:53 AM

formatter = new SimpleDateFormat("HH.mm.ss");
s = formatter.format(date);
// 14.36.33