Categorie: Java

Jboss AS 5 GA released!

5 December 2008

Today is a historic day for Java, as one of the leading implementations of Java EE 5, Jboss AS 5 has *finally* been released. Originally planned for early 2007 orso and promised to be released almost every quarter.

But today, no more speculation and no guessing. It’s here, and this time it’s for real! Read all about this fabulous release here: http://www.jboss.com/index.html?module=bb&op=viewtopic&t=146773

Download it from here: http://www.jboss.org/jbossas/downloads/

With Jboss officially implementing the Java EE 5 spec now, a new baseline of Java has been set. From now on, technologies like JSF 1.2, EJB3 and JPA can really be considered as basic, standard available techs.

Congrats to the Jboss team, and hoping it won’t take them as long to release Java EE 6 ;)

References:

Jboss AS 5 GA release date

24 November 2008

People have been wondering for some time about the release date of Jboss AS 5. As many of you know, Jboss 5 has been in development for quite some time and its release has been highly anticipated. Arguably, Jboss is one of the most important, if not -the- most important Java EE implementation. The fact that an official release of version 5 of this spec has been so long overdue, has been painful. Of course, Jboss 4.2.x supports most of the Java EE 5 stuff, but it’s just not the Real Thing.

The importance of Jboss AS is due to a number of reasons. Of course there are other Java EE 5 implementations out there, but the number of offerings seem to be declining. On the commercial side of the fence there’s basically IBM’s Websphere and Oracle’s OC4J, and on the open source side there’s Glassfish, Geronimo and Jboss AS 5. For many people, a closed source, commercial Java EE implementation seems to be little attractive. This leaves us basically with only 3 options for the moment. Geronimo may be nice, but nobody seems to be using this. Glassfish should maybe be the default choice (afterall, the Sun Java SE implementation is typically the default choice for many too), but has two main problems:

  1. It can’t be configured.
  2. It doesn’t offer any services.

This basically leaves Jboss AS 5 as the only choice, it it weren’t for the fact that it was always still in beta or in rc. In a way, this left a kind of void in the Java EE world (unless of course configuration and services don’t matter to you, then I suppose Glassfish would be perfectly fine).

Previously, Jboss AS 5 had been announced for february 2008 (see Where is JBossAS GA 5), but this seemed to be too optimistic. A major milestone was reached when Jboss AS 5 RC2 was officially EE 5 certified. A careful guess for the GA release date was then made for early November 2008 (see JBoss AS is now EE5 certified!).

Today however, a definite date has been given by Project Lead Dimitris Andreadis:

December 2008!

(See Jboss 5 release date?)

For those interested, these are some additional interesting resources:

How we won an iPhone dev competition without any prior knowledge

1 September 2008

About 2 weeks ago one of my team members, Robin Eggenkamp, mentioned there would be some iPhone dev ‘conference’ this month (iPhone Dev Camp, Amsterdam), originally at the building exactly opposite of the building where our own office is. Since I’m always interested in anything related to development I agreed to tag along. I expected it to be the kind of event where some talks are organized with a small hands on lab where some expert developer teaches newbies how to get up and running.

Now I’m certainly not a newbie when it comes to development. I lead a team of Java developers working on a rather large 200.000+ loc Java EE enterprise application and in a past life I worked as a win32/MFC C++ developer. Somewhere in between I also managed to finish a CS master. But… the iPhone was new to me. Although I’ve owned Apple computers ever since System 6 was still new & shiny, I’d never touched Xcode, Objective-C or Cocoa before. The closest I ever came was firing up Project Builder on my G3 iMac’s OS X 10.2, but only to test some C++ routine.

Because of the hands-on thing, I did plan to at least read an Objective-C tutorial the night before going to the event, but unfortunately couldn’t find the time to do so. When we arrived at the scene at exactly 10:00 in the morning, the place was already rather filled up. We found a cozy spot at a place in the back and while Robin started to connect his MacBook, I looked around and noticed it was not exactly what I thought it would be. Instead of an organized series of talks, this was a bunch of people sitting behind their computers, hacking away at stuff. The atmosphere seemed top notch though and I had a quick chat with some of the other people. At around 11 there was a short introduction talk and it became clear that the intend was to code something up for the iPhone and demo it at 17:00. The best apps would win a prize, with the first prize being a speaker set and a copy of Adobe CS3 or so.

By total coincidence, only moments after having his MacBook connected to the network, Robin finally received an email that he had been accepted for the iPhone developer program, something for which he had applied a whole month before. That meant we could start with some real development now! Robin had a little bit of experience with Xcode, but had done barely more than deploy some hello world examples to the simulator and tinkering a bit with the code. The fun thing about this was that normally whenever I need to use a new technique for my regular enterprise development, I first get myself a book of at least 600 pages, read the first 200 pages of that, try out some basic concepts, read another 200 pages, try another aspect of the tech, etc before I even attempt to apply it. Now we had to build something in a language we both didn’t know, on a platform we didn’t know, with tools we didn’t know and all of that in the course of a day :P

We started thinking about what kind of application we would try to create for the iPhone and I suddenly got the idea of letting the iPhone connect to a Mac and using data from its acceleratometer to move the Mac’s mouse pointer. I started with formulating some simple milestones to reach that goal:

  • Create local Mac app that moves mouse programmatically.
  • Create local iPhone app that just prints accelerator values to the screen.
  • Setup a connection from the iPhone to the Mac that just sends “hello”. Let the Mac prints this.
  • Integrate the individual steps to become the app we actually want. I assumed we would need some time to calibrate the raw acceleratometer and to find a suitable mapping from the meter’s range to the pixels on the Mac’s screen.

Meanwhile Robin was attempting to deploy his hello world example app to his iPhone using his just obtained certificate. It should have been a trivial thing, but after each deployment attempt a message box was displayed saying something like “0xE8000001, your mobile device has encountered an unexpected error (0x…) during the install phase: verifying application”. We tried many things, but nothing seemed to work. While we were feverishly googling for a solution, precious time on the clock ticked away. It must have been somewhere around 13:00 when Robin finally found out which settings in the project needed to be adjusted in what way. The example hello world app deployed correctly to the iPhone and it worked! Looking at the clock we realized we only had about 4 hours to go and we hadn’t written a single line of code ourselves yet…

Milestone 1 – The local Mac app – moving the mouse

The initial plan was to build the Mac app in Cocoa, but we decided that using Java would be the fastest way for us, basically since we simply know the language and environment. This milestone was easily completed. Using the java.awt.Robot class moving the Mac’s mouse pointer was a breeze.

Milestone 2 – The local iPhone app – printing accelerator values

For this milestone we couldn’t shy away from Objective-C anymore and actually had to take the plunge. We first looked up an example for getting data from the acceleratometer and luckily Apple had provided one. The next thing was to build a simple app, barely more than a hello world, that prints these values to the screen. This proved to be a little harder. Objective-C sometimes looks like Java and sometimes doesn’t. What are those square brackets everywhere? It looked like a kind of method call, but I couldn’t really figure out the meaning of the square brackets themselves. And how where we supposed to define properties so we could take advantage of the injection features of interface builder? Using @Property seemed obvious to us, but the compiler kept generating tons of warnings and errors. And how do we organize our code? We had created an AppDelegate, which we connected in interface builder to a mainView that inherited from the Window class. We added two labels that we injected to this view class, deployed our app to the iPhone, and… nothing happened. After feeling a little silly, we actually tried to quickly read some documentation. We learned that the square brackets have no extra special meaning, it’s just the Objective-C syntax for doing a method call. @Property needed to be accompanied with a declaration in the header and another annotation in the implementation file, @synthesize, that’s there to actually generate the getter and setter. Also, when creating a new project Xcode had already created an AppDelegate for us, something we overlooked.

With this new insight we ‘almost’ got our first real code completely working, but a few small things were still not going as planned. We therefor decided to throw it all away and change our strategy; start with an existing iPhone example application and just throw away what we don’t need and add what we do need. Going that route would save us from dealing with some of the nitty-gritty.

It was 14:00 by then and lunch had started. We enjoyed our nice and free lunch and had a chat again with the other guys. It seemed to be the case that we where hopelessly behind, since we still didn’t really had anything. After lunch things started to improve though. Having some idea of the Objective-C syntax now and using some of my almost forgotten C knowledge, we were quickly able to adapt an existing app to just print the 3 accelerator values (x, y, z) to 3 separate labels. Check!

Milestone 3 – Connecting iPhone and Mac

Since we had wasted a tremendous amount of time on the deployment and second milestone, we only had little time remaining. My original plan was to have one thread on the Mac listening to incoming communication, fetching commands and dispatching these to a (blocking) queue which will be read by another thread that controls the mouse movement. For the communication we wanted to dig through the iPhone API a little to see what it had to offer. With only 2 hours remaining, we decided to use the most basic communication method available; a simple BSD socket. At the Mac side we used a simple ServerSocket in Java and at the iPhone side we used the low level C socket()/connect() functions, for which we found a basic snippet of code that needed only a few adjustments. Although absolutely not the best technical solution, we decided to create and close a connection for each message sent.

Sending a basic test string from the iPhone to the Mac worked perfectly, so a little later we were able to send the accelerator values to the Mac. Check!

Milestone 4 – Integration

We had all the separate components up and running and now only needed to integrate them together. The acceleratometer’s values appeared to be in the range of -3 to 3 for all axis, while Robin’s Mac had a 1280*800 resolution. When totally in rest, there was a certain noise margin in the values that we got from the acceleratometer, so we expected that a little calibration was required. To test a little though we started with just multiplying the values we got by 60 and added that to the current mouse position. Surprisingly this already gave fairly good results. The multiplication and the rounding down to whole pixels canceled out the noise perfectly. In a few minutes we ended up with a really simple mapping that was just something like max(0,min(forceX * 15,1280)) for the movement on the X-axis. Sending about 15 messages per second appeared to be enough for smooth motion.

By now we suddenly had some time remaining, so we used that to implement the ability to also do a mouse click. Our initial approach to that was to sent a separate message for a mouse click, but it appeared to be more robust to just add the mouse button state as a fourth parameter to the existing message. At the very last moment there was a little panic when all messages being sent appeared to be empty. Apparently, our string formatting syntax for a boolean wasn’t supported by Objective-C (we used something like “%d,%d,%d,%b”) or maybe there was a difference between a primitive boolean and an Object boolean. We decided not to pursue the issue and simply use the string “false” and “true” (something I normally always stay far from, but with 30 seconds on the clock remaining there wasn’t much choice). Since we had been fumbling with the code for most of the day, we figured that our chances of winning anything where rather slim. Nevertheless we were happy that we had came up with something that worked, and actually worked rather nice.

The demo

It was now time for all of us to demo our application. Among others there was a tips of the days app, an app that retrieved quotes from the Internet, a very cool looking game where you had to touch the screen to cause a kind of bubble on which a moving object bounced to another side complete with sound effects and all and a very impressive looking application that measured your air time when skiing in addition to your speed, path and direction. Unfortunately this last app appeared to be only concept art.

When it was our time for the demo, I told something about the technical shortcuts we had taken, while Robin demonstrated how to use the iPhone to paint a running man in a painting application on the Mac.

Showing the demo
Picture by tizzle. See flickr.

Much to our surprise, our application was well received and we got the first price; a nice speaker set for the iPhone or iPod. We’ll install it in the office :)

Arjan Tijms

Links:

JSF 2.0, a glance

27 August 2008

Having been recently thrown into the deep waters of JSF and Facelets it seemed natural to do an evaluation of where this technology is going. JSF is currently at version 1.2. Version 2.0 is scheduled for release with Java EE 6. So what goodies will this bring us?

The main goals of the revision is to make development easier by integrating into the core system many tools/frameworks which were built on top of previous JSF versions. Ajax support, facelets-like templating, improved development support and better performance are all things that are mentioned in the specifications.

These are the highlights of what is coming:

I’m sure everyone is familiar with Ajax. JSF 2.0 includes Ajax in its life cycle and offers more direct support for its use. The view state can now be partially updated to reflect that only part of the view has changed. Ajax will make use of the new resource handler scheme. This isn’t very exciting in and of itself. A natural progression in the way one would expect this technology to mature.

Facelets is another technology needing to be incorporated into 2.0. Facelets allows us to define our pages in a different way by using XML and templating. The way to write these pages is very close to the the way we already work, which makes it easy to learn. The added usefulness of templating allows us to write less cluttered pages. It also increases code reuse. The popularity of this approach and its obvious usefulness make it inevitable that this would be included in JSF 2.0. This is currently referred to as ‘page description language’ in the JSF specification. While the name is less exciting than Facelets it is accurate and there is no doubt that this is a welcome addition to JSF

Development for JSF is getting some support through the ‘Project_Stage’ feature. This is no more or less than a context parameter. Now many people are excited by this, but I don’t quite seem to share the sentiment. Theoretically this will allow for actions dependent on where the project is in its life. Is it in production, unit test, system test or development? The options are limited, though probably enough. What I am wondering is what it is doing in JSF. While there is a use for a setting like this, indeed it seems common in many disparate projects, it seems to me to be a higher level setting than JSF level. JSF should support it, but not claim it.

Another interesting feature is the Resource Handler. Resources are anything that could be included in a component that is required for the component to be rendered correctly to the user-agent. Think about images, JavaScript or css files. The Resource Handler enforces a structure on your resources which in and of itself just helps in organizing your project. This will also make it easier for component developers. They know exactly where to put or look for resources without having to know what application is using them. Locale and versioning are handled automatically. Another advantage is that replacing resources runtime will be much cleaner. No restart of the system should be needed.

There are some things about resources I don’t like however. First of all the specification only specifies a structure for webapps. Implementations for other platforms are even invited to do whatever they want. It seems an unfortunate choice since you really want a standard to be standard. Another is the relocatable resource. Now you can tell certain resources where they are supposed to be. Put the tag in the body but tell it to be rendered in the head. I don’t understand the reasoning for this. Perhaps if it is based on some conditional programming elsewhere on the page….but quite frankly your page is probably getting to complicated at that point. If something needs to be in the head (body, wherever), just put it there. I wonder if I am not missing some essential insight with which I will all of a sudden see what a great and useful feature this is.

One argument for relocatable resource is that components may wish to write things in locations which are outside of their direct knowledge. The head of an HTML document is an example. A component, possibly called by other components, could decide it wanted to change the head of a document. This is completely undesirable behavior. If the component is generic it should never bother with anything outside its scope. If it isn’t generic then its use is limited anyway and one could ask why it is even a component. Thinking specifically of style information I would say that this should never be overwritten at component level. Scripts can be included in the body and shouldn’t require anything beyond what exists in the component anyway. Apparently the community desires this functionality. To me it seems a harmful construct which should not be supported.

All in all I think JSF 2.0 will be an improvement of the technology. It has listened and learned from what the community has built on top of JSF and incorporated the features that were most used. As well it improves its internal workings which is never a bad thing from a user perspective. While I may not yet understand all the choices made it is obvious that the changes were well thought out and planned. Assuming the implementation is improved as well then JSF 2.0 will be pretty much what you want from version 2.0.

Jasper Floor

useful links:

Java developers en programmeurs zoeken is een hele kunst

2 August 2008

Hoe vind je een goede programmeur? Programmeurs hebben verschillende hobby’s, houden van verschillende soorten muziek, hebben verschillende meningen over politiek, enz. Je loopt niet zomaar een genootschap van programmeurs binnen waar je de mensen met de juiste kennis voor het uitzoeken hebt. Waar vind je dan die goede programmeur?

Eén ding weet ik wel – dat iemand vroeg moet zijn begonnen met programmeren om er echt gevoel voor te krijgen. Je moet als het ware kunnen denken in nulletjes en ééntjes. Als je als kind met een Atari of een Commodore 64 hebt gespeeld – dan ben jij er als programmeur vroeg bij geweest.

Tegenwoordig wordt je niet meer gedwongen om te weten wat programmeren is. Vroeger, met Basic, kon je eigenlijk niet anders. Vele technische ontwikkelingen hebben die ervaring overbodig gemaakt. Er zijn nu allerlei mogelijkheden om het echte programmeren te omzeilen. De programmeur die wij zoeken deinst er niet voor terug dit soort mogelijkheden links te laten liggen, en écht diep in de code te duiken.

Maar ervaring uit het verleden is niet alles. Je moet ook in staat zijn om je snel nieuwe technieken eigen te maken, en je moet veel lezen om je kennis steeds te blijven uitbreiden. En natuurlijk moet je weten waar je je computer voor kunt gebruiken. Dat programmeurs soms lui zijn is eigenlijk wel eens een goede eigenschap. Ik geloof in het woord automatisering! Laat de computer het werk maar doen.

Terug naar het onderwerp. Waar zijn de developers die we zoeken? Als je dit leest zijn we misschien klein stukje verder… Neem eens een kijkje op onze pagina Vacatures.

Met vriendelijke groeten,

Klaas

Java EE 6 progress page

28 June 2008

On this page I will try to keep track about resources related to Java EE 6. This page started as a progress page in the running up to the release, and now that this release has happened will continue to track resources specifically related to Java EE 6.

Java EE 6 overal (final release done!)

Java EE 6 is the current edition of the enterprise platform that powers quite a lot of (web) applications. Java EE itself consists out of a lot of sub specifications, with JSF (web) and EJB (business) being major parts of that. New for this release will be Webbeans, a specification that integrates JSF and EJB more tightly than was possible before.

Main JSR: http://jcp.org/en/jsr/detail?id=316

Articles:
2009/01 Java EE 6 Platform Draft Published featuring the Web Profile
2009/04 Pruning The Deadwood from Java EE
2009/04 JSR-316: JavaTM Platform, Enterprise Edition 6 – Interview with Jason Greene
2009/10 Java EE 6 Proposed Final Draft Hints at Future Direction of the Platform
2009/11 EE 6 tsunami
2009/12 Java EE 6, Glassfish 3 and NetBeans 6.8 Released: Q&A with EE 6 Specification Lead Roberto Chinnici
2010/02 Resin Java EE 6 Web Profile Implementation
2010/05 DataSource Resource Definition in Java EE 6
2010/09 javaOne 2010 : Java EE 6 Panel “What do we do now?”

Release estimate:

Event Original date actual date estimated date (*)
Expert group formed Jul 2007 07 Oct, 2007
First expert draft Aug 2007 unknown
Early Draft Review Oct 2007 22 Nov, 2008
Public Review Dec 2007 23 Feb, 2009
Proposed Final Draft Mar 2008 06 Oct, 2009 – ???
Final Approval Ballot not originally planned 17 Nov, 2009-30 Nov 2009
RI beta release Q2 2008 Q4 2009
Final release Q4 2008 10 Dec, 2009
Implementation in Glassfish 10 Dec, 2009
Implementation in Jboss 17 Dec, 2010 H2 2010 (Final release + several months)

*) Estimated dates are my own estimates, based on the current actual dates and the original delta between dates. Glassfish release date is based on the fact that it follows the spec daily and even is ahead of the spec at times. According to the release schedule of Glassfish V3, this will be in December 2009. Jboss will support Java EE 6 in Jboss AS 6.0, of which milestone 4 was released in July 2010. With one CR1 scheduled before the final release, it’s expected that this final release will happen in late 2010. In September 2010, JBoss announced the final release to be at 17 Dec, 2010).

JSF 2.0 (final release done!)

Despite some early critic, JSF is becoming the default web layer technology in Java EE. In a way, JSF can be seen as a foundational technology upon which a very vibrant community is able to build exciting new solutions.

Main JSR: http://jcp.org/en/jsr/detail?id=314
Final release: http://jcp.org/aboutJava/communityprocess/final/jsr314/index.html

Discussion:
http://www.theserverside.com/news/thread.tss?thread_id=49870

Ryan Lubke’s (Sun) blog:

New features in JSF 2.0
Part 1: http://blogs.sun.com/rlubke/entry/jsf_2_0_new_feature2
Part 2: http://blogs.sun.com/rlubke/entry/jsf_2_0_new_feature5
Part 3: http://blogs.sun.com/rlubke/entry/jsf_2_0_new_feature
Part 4: http://blogs.sun.com/rlubke/entry/jsf_2_0_new_feature3
Part 5: http://blogs.sun.com/rlubke/entry/jsf_2_0_new_feature1
Part 6: http://blogs.sun.com/rlubke/entry/jsf_2_0_new_feature4

Ed burns’ (Sun/Oracle) blog:

2007/05 New JSF 2.0 features discussion
2007/06 JSF 2.0 presentation
2007/11 Easier JSF custom components
2008/02 JSF and AJAX
2009/07 What’s New in JSF 2?
2009/09 Dealing Gracefully with ViewExpiredException in JSF2
2009/09 JSF2 Composite Component Metadata
2009/10 JSF2 Facelet Tag Handlers

Dan Allen’s (Jboss) dzone articles:

2009/10 Part 1 – JSF 2 – Seam’s Other Avenue to Standardization
2009/10 Part 2 – JSF 2 GETs Bookmarkable URLs
2009/11 Part 3 – Fluent Navigation in JSF 2
2009/12 Part 4 – Ajax and JSF, Joined At Last

Various
2009/01 JSF 2.0: A Component’s Controller (see driscoll for much more)
2009/05 ICEFaces 2.0 And JSF 2.0 Together
2009/05 JSF 2 fu, Part 1: Streamline Web application development
2009/05 JSF 2 fu, Part 2: Templating and composite components
2009/05 JSF 2 fu, Part 3: Event handling, JavaScript, and Ajax
2009/07 What’s cool in Java EE 6 — JSF 2.0
2009/08 More cool in Java EE 6 — JSF 2.0, Bean Validation
2009/09 Learning JSF2: Navigation
2009/10 JSF2 and POST Redirect GET
2009/12 Is @javax.faces.bean.ManagedBean Dead on Arrival?
2010/01 JSF 2 Gains Facelets, Composite Components, Partial State Saving and Ajax
2010/03 JSF 2.0: Annotations, New Navigation Eliminate XML Configuration

Servlet 3.0

The main underlying technology of the servlet container (the web part of a Java EE AS) is of course the servlet API itself. This technology is foundational to both JSP and JSF. Previously moving at a relative slow pace (there were only very minor changes between Servlet 2.4 and the current Servlet 2.5), some major additions are planned for Servlet 3.0.

Main JSR: http://jcp.org/en/jsr/detail?id=315

Rajiv Mordani’s Blog:

Servlet 3.0 PFD draft coming soon.
http://weblogs.java.net/blog/mode/archive/2008/12/asynchronous_su.html
http://weblogs.java.net/blog/mode/archive/2008/12/servlet_30_jsr_2.html
http://weblogs.java.net/blog/mode/archive/2008/12/rebuttal_of_gre.html

Sun Presentation from Rajiv Mordani about Servlet 3.0:
https://slx.sun.com/files/servlet30-20081218.pdf

2008/10 Servlet 3.0 Annotations
2008/12 More Servlet 3.0 PRD Previews: Asynch Support, Improved Servlet and Filter Registration
2008/12 Servlet 3.0 Public Review Sparks a Debate
2009/01 An Overview of Servlet 3.0
2009/01 Java EE 6 and Servlet 3.0 Overview
2009/05 Servlet 3.0 Proposed “Final” Draft
2009/06 Java™ Servlet 3.0: Empowering Your Web Applications With Async, Extensibility and More
2009/09 Servlet 3.0 Tutorial: @WebListener, @WebServlet, @WebFilter and @WebInitParam
2010/04 Migrating to Servlets 3.0: Thoughts on @WebServlet
2010/07 Java EE 6: Application Security Enhancements
2010/12 JEE 6 and Spring MVC [Async Servlets]

JSP 2.2

Despite a rise in popularity for Facelets, JSP is still an important view description technology for the Java EE platform. The fact that millions of JSP pages have already been written and are still in active use causes this technology to be relevant for some time to come.

It’s rumored that Java EE 6 will see an updated version of JSP; JSP 2.2. However, no JSR has been filed for this and almost no references can be found for it. The Java EE 6 spec document says the following:

EE.6.5 JavaServer Pagesâ„¢ (JSP) 2.2 Requirements
The JSP specification depends on and builds on the servlet framework. A Java EE
product must support the entire JSP specification.
The JSP specification is available at http://java.sun.com/products/jsp.

Parallel to this, there is a JSP 2.1 MR 2 in the works. This will add, among others, parameters to EL expressions so that bean methods can be invoked from the view:
http://jcp.org/aboutJava/communityprocess/maintenance/jsr245/245ChangeLog2.html.

In this blog it is suggested that JSP 2.1 MR2 will be the new JSP version included with Java EE 6, and thus that there won’t be a JSP 2.2 for now:
JSR 245 MR: Part I – Expression Language (EL)

JPA 2.0

JPA, Java Persistence Architecture, is the default ORM implementation in Java. Basically it allows a developer to specify a simple mapping with annotations or in XML from an Object to a relational data base table. JPA is based on existing ORM solutions like Oracle’s Toplink and Hibernate. Although originally part of EJB3, JPA has always been applicable to the entire Java platform, including Java SE. JPA 2.0 will be based on Eclipselink.

Main jsr: http://jcp.org/en/jsr/detail?id=317
Proposed Final Draft 2: http://jcp.org/aboutJava/communityprocess/pfd/jsr317/index2.html

Discussion:
Eclipselink for JPA 2.0
http://www.theserverside.com/news/thread.tss?thread_id=48757

Announcement
http://www.theserverside.com/news/thread.tss?thread_id=46406

Linda DeMichiel’s Blog:
Early (May 2, ’08) Java Persistence 2.0 Early Draft Available
Public (Nov 14, ’08) Java Persistence 2.0 Public Draft
Public (Nov 25, ’08) Java Persistence 2.0 Public Draft: Criteria API
Final Draft (Mar, ’09) Java Persistence 2.0 Proposed Final Draft

Gavin King’s Blog:
A typesafe criteria query API for JPA
Java 6 compiler plugins and typesafe criteria queries

Various:
2008/03 Unidirectional one-to-many and indexed lists problems in JPA 1
2008/05 Orphan removal (early draft)
2009/01 Two Type-Safe Criteria API Proposals for JPA 2.0
2009/02 JPA 2.0: Why AccessType is Relevant
2009/05 Java Persistence 2.0 Proposed Final Draft
2009/07 JPA 2.0 Concurrency and locking
2009/09 Locking and Concurrency in Java Persistence 2.0
2010/08 The Top 5 New Annotations in JPA 2
2010/09 JPA 2 new feature @ElementCollection explained
2010/09 JPA Criteria API by samples – Part-I / Part-II
2010/11 The JPA 2 Enhancements Every Java Developer Should Know

EJB 3.1

EJB is the part of Java EE that provides solutions for managing business code related artifacts, mainly transactions and domain entities. EJB started off in the wrong direction and especially EJB2 has received a lot of critic for being extremely cumbersome and heavyweight. EJB3 however is a complete redesign, using an ultra light approach and a very elegant design. Some say that EJB3 is actually a 1.0 version of a complete new technology. In Java EE 6, few major new additions will be done for EJB. Instead, existing functionality will be tuned and polished.

Main JSR: http://jcp.org/en/jsr/detail?id=318
Proposed final draft: http://jcp.org/aboutJava/communityprocess/pfd/jsr318/index.htm

New features in EJB3.1 by Reza Rahman:

Part 1: http://www.theserverside.com/tt/articles/article.tss?l=NewFeaturesinEJB3-1
Part 2: http://www.theserverside.com/tt/articles/article.tss?l=NewFeaturesEJB31
Part 3: http://www.theserverside.com/tt/articles/article.tss?l=NewFeaturesEJB31-3
Part 4: http://www.theserverside.com/tt/articles/article.tss?l=NewFeaturesinEJB3-Part4

Feedback on Reza Rahman’s articles:

Part 1: http://www.theserverside.com/news/thread.tss?thread_id=48198
Part 2: http://www.theserverside.com/news/thread.tss?thread_id=48684
Part 3: http://www.theserverside.com/news/thread.tss?thread_id=49108
Part 4: http://www.theserverside.com/news/thread.tss?thread_id=49749

Various blog entries and articles

A Sampling of EJB 3.1
EJB 3(1) – So, How Portable Is Actually This Stuff In The Practice?
EJBs in a WAR – Simplified packaging defined by EJB 3.1, Available in GlassFish v3
EJB 3.1 – and Is There Still Room For POJOs?
EJB 3.1 – A Significant Step Towards Maturity
2009/08 Simplest possible EJB 3.1 / ReST (JSR-311) component
2009/10 EJB 3.1 – Asynchronous Session Beans
2009/12 Portable Global JNDI names
2010/01 EJB 3.1 (Asynchronous Beans)
2010/02 Java EE6: EJB3.1 Is a Compelling Evolution
2010/10 EJB 3.1 Timer Service using @Schedule

JCA 1.6

JCA, Java Connector Architecture, may not be the most known of the various Java EE libraries, but is a powerful technology. JCA 1.6′s most visible features are bean validation and extended support for concurrency via distributed work processing.

Main jsr: http://jcp.org/en/jsr/summary?id=322
Proposed Final Draft: JSR-000322 Java EE Connector Architecture 1.6

Jesper’s blog:

2009/07 Announcing JBoss JCA 1.0.0.Alpha1
2009/07 JBoss JCA 1.0.0.Alpha2 is out
2009/08 JBoss JCA 1.0.0.Alpha3 is out
2009/09 JBoss JCA 1.0.0.Alpha4 is out
2009/10 JBoss JCA 1.0.0.Alpha5 is out
2009/11 JBoss JCA 1.0.0.Alpha6 is out
2009/12 JBoss JCA 1.0.0.Alpha7 is out

Articles:
Connectors 1.6 Proposed Final Draft and the availability of Java EE SDK Preview
Resource Adapter Annotations
2010/04 A Look Inside the JBoss JCA Project; New Features in JCA 1.6
2010/04 Boston JBoss User Group – JCA 1.6

JAX-RS 1.1

JAX-RS 1.1 is an additional web services specification that was added to Java EE 6. Like the existing JAX-WS, it allows you to expose an API via the web, but unlike JAX-WS it focusses on RESTfull stateless services as a core principal. Before JAX-RS 1.1 was included in Java EE 6, there was a standalone version; JAX-RS 1.0. This is similar to the situation where there was a Swing version before it was included in Java SE 1.2 and a JSF version before it was included in Java EE 5.

Main jsr: http://www.jcp.org/en/jsr/detail?id=311

2009/04 Overview of JAX-RS 1.0 Features (non Java EE 6)
2010/02 Java EE 6 Web Services: JAX-RS 1.1 Provides Annotation Based REST Support
2010/02 JAX-RS 1.1: What’s New?
2010/06 REST made easy with Java EE 6 and JAX-RS 1.1
2010/07 A Fresh New Jersey
2010/09 JAX-WS and Java 6 EE

UI for the People

3 April 2008

When I first started working with user interface (UI) design the process looked something like this: Take an existing paper template, copy it to the screen and make it work. What were the benefits of such approach? For one we did not have to spend much time on UI design – we simply added fields to the screen where they existed on paper. The other benefit was that people who were already familiar with the paper form had no problem understanding the UI page visible on the computer screen.

What were the drawbacks of such approach? For historical reasons paper forms were rarely ever “designed”. They simply grew over time until they were deemed sufficient for the task they had to perform. Using such forms as UI templates was hardly the smartest thing to do – they were a real pain to work with even in their original (paper) form, and only the most experienced of users could find their way around them. All new employees had to suffer the pains of learning those forms – no matter if on paper or on the screen – through trials and errors.

Then time came for full-fledged UI design. A new profession came into view – usability expert. Developers started to realize that copying paper forms was hardly the best and greatest when it came to user interaction. In all truth paper forms were downright evil when incorporated as-is into software – they simply functioned in a different way. The time came for input dialogs, task wizards, user-centered design – the works. Though an occasional experienced user grumbled a little after being forced to learn how to use the new UI all over again even he/she could see the benefits of the new – smarter – design. Users who were only starting with the new software were downright happy since the new UI was much easier to use than paper forms from hell.

Unfortunately it seems like the process of improving the UI stopped right there. Someone might ask what else could be done to make the UI better? After all the UI of today does everything what it needs to do, and in a sensible and efficient way.

Here is a question to think about: What is the real benefit of using computer software? Depending on who you talk to you might get a different answer:

“Computers are fast and they perform better.”

“You can undo and redo changes with ease.”

“Computers connected via network let you share data with other members of your organization.”

And so on.

All those answers are valid, but to me the greatest benefit of using computers in office work is capturing the business logic. A good UI not only serves as a tool but also embeds the knowledge of business it was designed for. When a bank clerk tries to enter alphabet letters into a field called “Amount” an error message appears: “Amount is a number – enter digits!” This simple input validation step captures certain amount of knowledge of the banking industry. And this is just a simple example. Whole scripts can be created to control financial securities trade. There is software that controls robots in car factories. Each of those programs encapsulates the knowledge of how to do something.

So what can be done to make the UI better? Here are some thoughts. How about not only give people the tools to use, but also the knowledge on how to use them? A simple hover pop-up box with information on what clicking the selected button does could teach a new user how to use the UI in no time. Providing the user with a list of possible work flows (for example a list of step-by-step wizards) could explain to him/her how the business works. Not to mention including links to examples right there, on the page the user currently works with.

It is a well-known fact that people don’t read FAQs, manuals, etc. Anything longer than a sentence scares users off. That’s why “sprinkling” the interface page with small bits of helpful information – not like “in order to open a banking account you have to …”, but more like “e.g. click this, click that, enter this …” – might be a better choice for information injection. Some good examples from among the existing software are examples at the bottom of the Linux manual (man) page, or at the bottom of Ant task descriptions. Once people get used to the UI they might not need those examples anymore, but such small bits of info should cut down the overall learning curve.

Such approach would make the UI not only a tool, but also a teacher. After all people are only people, and they do make mistakes, no matter how experienced they are. Mistakes can be made when using the software, but also when explaining to another person how to use the software in question. I’ve seen this happen: people running from cubicle to cubicle, looking for answers, when the only experienced person on the floor was out for lunch.

For developers with a bit of imagination it shouldn’t be too hard to see how expert systems – and possibly AI – could be incorporated into the business logic to make a complex task execution automatic. After all computers evolve much faster than people, so the computing limits we face today might not be there tomorrow.

It is important to remember that human society is changing and that computers play greater and greater role in it with every passing day. It’s old news that more and more human-performed tasks are represented in computer software. Creating a smart UI – UI that teaches users about the business it was designed for – is a step in the right direction.

Marcin Citowicki

Experiencing working overseas

16 October 2007

Working in a team with members located in different parts of the world is common today, but it’s maybe not that common for a company to bring the freedom of work regarding time and place to such an extend as M4N does.

I have been dreaming of a job with some flexibility in time. It turned out that M4N can provide me with more than I had dreamed about: located in a part of the world (Beijing) 6 hours earlier than the central office (Amsterdam), I can work at any time as long as I can make 16 hours per week, at any place with an Internet connection. M4N uses quite a few methods and tools for me to work as in a virtual local office: project management and issue tracking is done through the Trac system; an Intranet website and an office Calendar facilitate communication and coordination. I’m in the development team and the project version control is through the SVN system. For all these systems, I can use them just as the local members do. You may point out that communication with the team members could be a problem. Well, it is true that that we can not have actual face-to-face discussion or a real-life meeting, which is inconvenient, but we communicate through text or voice and video chat with MSN or skype. In fact, most often than not, team members in the same office use text chat too in order to keep the office in silence.

My working day can be like this: one o’clock in the afternoon, I make some tea and start the computer, then start MSN or skype. Working on my local computer with Internet connection, I program on my local computer but use the remote database in the M4N central office. Around 4 to 5 o’clock, my colleagues go on line. I chat with my team members of the projects now and then. Around 11 o’clock, I commit my work for the day and go off work.

M4N has quite a few distant employees like me. She has cut off the place and time boundary of the traditional cooperation, I feel so lucky to have the opportunities to enjoy the most freedom I can get from a job so far.

Hongqin Chen

JDK6 Web start Cache location

8 October 2007

For a web start deployment of an application it is sometimes
necessary to be able to get the location of the cached and downloaded
jar files which come with the web start deployed application.

I needed to be able to specify some files to the external javac class path
to compile some dynamically generated jasper reports on the client side.

There are a lot of forum topics about this, but no copy-paste solution.
So even with a "year behind" policy on the java jvm I had to fix
this by myself :P 

The jdk6 broke this because they updated the JNLPClassLoader in jdk6
to extend the URLClassLoader which is hooked to the java cache api.
This is all nicely explained at:

http://java.sun.com/developer/community/askxprt/2006/jl0410.html

But now the URL to the jar files returned from the  JNLPClassLoader are URLs
pointing to the external http location.
In jdk5 these were pointing to the cached version on the  filesystem.

To get the cached version of the files in jdk6 we use a JarURLConnection to get
the jar file from the URL, The jar file returned is cache entry of the already
downloaded file, but its name is not preserved by the cache.
It is something like "~/.java/deployment/cache/6.0/55/65eff4b7-3af949f2"
So we copy it to an temp file which has an jar suffix and we are good to go
to include it in a class path.

I hope this will help some other wondering developers which are still in
need for a workaround, below is the full code version;

 /**

 * Fix jasper compling class path.

 * This is needed for webstart, because then the jvm classpath doesn’t contrain the client libs.

 * @throws Exception

 */

private void setJasperBuildPath() throws Exception {

String reportBuildPath = “”;

 // All jars have an manifest

   Enumeration<URL> e2 = Thread.currentThread().getContextClassLoader().getResources(“META-INF/MANIFEST.MF”);

   while(e2.hasMoreElements()) {

 URL u = e2.nextElement();

 String urlString = u.toExternalForm();

 

 // only do needed libs

 if (!(urlString.indexOf(“jasper”)>0 | urlString.indexOf(“itext”)>0 | urlString.indexOf(“showplanner-1″)>0)) {

  continue;

 }

 

 // index of .jar because the resource is behind it; “foo.jar!META-INF/MANIFEST.MF”

 int jarIndex = urlString.lastIndexOf(“.jar”);

 

 // skip non jar code

 if (jarIndex<1) {

  continue;

 }

 

 String jarLocation = null;

 if (urlString.startsWith(“jar:file:”)) {

  // jdk5 webstart cache AND development

  jarLocation = urlString.substring(4,jarIndex+4);    

 } else {

  // jdk6, uses java caching api in urlclassloader which is extended by the jndiclassloader in jdk6

  // we should get the same file from the cache, we copy because of classpath needs .jar suffix

  JarFile cachedFile = ((JarURLConnection)u.openConnection()).getJarFile();

  File tempFile = File.createTempFile(“cached-”, “.jar”);

  tempFile.deleteOnExit();

  copyFile(new File(cachedFile.getName()),tempFile);

  jarLocation = “file:”+tempFile.getAbsolutePath();

 }

 reportBuildPath+=jarLocation+File.pathSeparator;

 logger.info(“Adding to report compile path: “+jarLocation+” made from: “+urlString);

}

   System.setProperty(“jasper.reports.compile.class.path”,reportBuildPath);

   logger.finer(“Set japser com: “+reportBuildPath);

}

private void copyFile(File in, File out) throws Exception {

   FileChannel sourceChannel = new FileInputStream(in).getChannel();

   FileChannel destinationChannel = new FileOutputStream(out).getChannel();

   sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);

   sourceChannel.close();

   destinationChannel.close();

}

 

 Willem Cazander

 M4N.NL

Java best practices 5 – Code to Interface, Access by name and Instance Data

7 October 2007

In this 5th and final installment of my series on best practices in Java I’ll wrap up with the last 3 items from the list I compiled in the first installment. Today we’ll be looking at generalizing parameters to counter the “Coding to a class instead of to an interface” bad practice, discuss why “Selecting ResultSet columns by index, instead of by name” is not always a good idea and finally we take a look at some of the usage patterns that are involved with the “needless use of instance variables”.  

Coding to a class instead of to an interface

One of the advantages of Java is its pervasive OO model. I’m aware that on the one hand not everyone thinks OO is the best thing since sliced bread and at the other hand some languages take object orientation to an even higher level. But let’s not digress, suppose you’re a Java programmer and that your team has decided OO is in fact a Good Thing.

A classic mistake people often make when starting to program in an OO language is not actually making use of the explicit features OO offers. Of course, the paradigm entails more than just putting “public class { … }” around your existing code. For people just coming from a procedural language, it may be a little understandable if they did just that. I have however seen people that have been programming in Java for 6, 7 years, even calling themselves ‘Sr Java programmer’, and in fact still do little more than just putting “public class { … }” around their otherwise procedural code.

Not using OO manifests itself at many levels in a software design. A particular devious way, and the one about which I’ll be talking here is “Coding to a class instead of to an interface”.

One of the (well known) benefits in an OO design is that a subclass can be used wherever code expects a superclass of that type. To actually reap this benefit a programmer has to be careful when e.g. crafting the signature of her methods. The parameters being used should not just be -a- superclass, but in fact the most general one that still captures all functionality that the code -actually- uses. For flexibility concerns and because of the fact that Java only supports single inheritance, an interface (aka a ‘pure abstract superclass’ in some other languages) is often the most preferred one.

As an example, consider the follow code:

public void doStuff( ArrayList<Integer> list ) {		
	list.add(1);
	// do stuff
	list.get(0);	
}

Using the ArrayList in the method’s signature severely limits the usage of the doStuff method, as only ArrayLists and their subclasses can be passed in. In this case it’s an unnecessary restriction. Nothing in the method uses anything that is specific to an ArrayList, making it a bad practice to require it.

A better practice is to use a superclass or an interface here, but which one? ArrayList has many, including superclasses AbstractList and AbstractCollection and interfaces List, Collection and Iterable. The choice between the superclass and the interface is easy here; the superclasses are merely default implementations of parts of the (complex) interfaces, so we’ll go with the interface. Looking at the method’s body we see add() and get() is being used. This means Collection is actually too general (it doesn’t have get()) so we’ll go for List:

public void doStuff( List<Integer> list ) {		
	list.add(1);
	// do stuff
	list.get(0);	
}

We can generalize this one step further by generalizing the generic parameter:

public void doStuff( List<? super Integer> list ) {		
	list.add(1);
	// do stuff
	list.get(0);	
}

Some readers might ask why the more intuitively List<Number> can’t be used here. Indeed, we could try to define the method as taking a List<Number> or a List<? extends Number>, but the first definition would exclude the possibility for passing in an actual ArrayList<Integer>, while the second definition would disallow the add() method (as someone may otherwise be passing an ArrayList<Float> in, and would find an Integer to be between the Floats after the call to doStuff).

In a way one could informally say that ‘coding to an interface’ for generic arguments works the other way around than for regular parameters in the OO model; instead of specifying the most general type and silently accept subtypes (e.g. specify List, accept ArrayList), you specify the most specific type and ‘silently’ accept more general types (e.g. specify <? super Integer>, accept <Number>). Of course, the latter is not completely silent as the Java generic syntax forces you to explicitly state your willingness to accept super types.

Selecting ResultSet columns by index, instead of by name

In Java a ResultSet represents a table of data that is typically obtained as the result from executing an SQL query. The two primary ways to retrieve data from such a Resultset’s columns is by using either the column’s index number or the column’s name.

Although certainly not everyone would agree with it, I think retrieving data by index from a resultset in Java business code is often a bad practice; it leads to code that is less readable and less maintainable. E.g. consider the following code fragment:

formatItem( allNews.getString("title"), allNews.getString("summary") );

Accessing by index it would look like this:

formatItem( allNews.getString(1), allNews.getString(2) );

With the former statement it’s fairly clear what’s happening, while with the latter we have a lot more guessing to do, especially if we are not also the writer of this piece of code. In fact, writing code in such a way has many parallels with the bad practice of using cryptic variable names (e.g. names like aa, bz, x, etc). While writing, it may be somewhat clear which variable holds what, but when reading it later on the meaning becomes incredibly hard to grasp.

As mentioned, there’s also a maintenance problem with this code. Suppose the Resultset is generated from this simple SQL query:

SELECT
	description,
	summary,
	text
FROM
	news_items

Now, later on someone may decide to add an extra column, say “author”:

SELECT
	author, 
	description,
	summary,
	text
FROM
	news_items

Especially if the query is shared it may not be obvious that somewhere there is some code with a dependency on the column order. If this new column is thus added before “description”, the Java statement given above will silently use the wrong columns.

SQL is not Java, but compare this with a Java class definition with some simple fields:

class NewsItem {
	String description;
	String summary;
	String text;	
}

When adding an additional field, nobody in his right mind would worry about code that might access a field by the order in which it was defined (although this is technically possible using reflection) and thus the new field would be added at a random location in the class definition.

Proponents sometimes argue that accessing Resultsets by index has several advantages; namely performance, the ability to select an unnamed column and the ability to distinguish between columns with equal names.

To start countering these arguments; for general business code the difference in performance between selecting by index and name is most probably unmeasurable. It’s the same kind of premature optimization that we encountered when looking at native arrays vs a Collection based alternative; the typical business code that retrieves a handful of values from a Resultset is not going to notice any difference here.

The ability to select an unnamed column or distinguish among equally named columns is more often than not a way around a bad practice in SQL. Instead of employing yet another bad practice to cover up an earlier one, it’s better to just fix this earlier one. E.g. by using the SQL clause “AS” in the original query.

Does this mean all methods for accessing results by column index should be deprecated? Of course not. For code that simply needs to iterate over all columns in a resultset, index based getters are most suitable. Other specialized code may have some specific use for them too.

However, in pure business oriented code these cases may be rare. In the code example above (a very common case in business software) accessing by index is surely a bad practice.

Needless use of instance variables

When discussing the ‘coding to a class instead of to an interface’ bad practice, we mentioned that this was one symptom of not using OO correctly. Another such symptom is the “needless use of instance variables”, which we too often see in code being written by people with a procedural background.

If OO means little more to you than putting “public class { … }” around your code, then instance variables in Java are the equivalent to (file scoped) global variables in procedural code. Many people agree that using global variables, even when limited to just the file scope, is not very often a good idea.

During auditing sessions I encountered classes consisting of 2000~3000 lines of code (which is actually a bad practice by itself), with in excess of 100 instance variables. In such a situation it becomes totally unclear which variable is effected by what method; a mess that looks and feels quite similar to the ‘global variable hell’ in some other languages.

In unraveling this mess I often encounter a number of patterns, some good, some bad.

A good practice for using instance variables is when those variables actually represent state that needs to be stored inside the mentioned object. It just may be the case that if there are many of these variables, grouping them into separate classes is recommended. E.g. consider a subscription class with 15 instance variables for personal user data and some 15 other for company data. It may be a better idea to group the first 15 variables to a separate class called User and the second 15 to a class called Company. Other than that, there’s nothing wrong with this usage of instance variables.

A truly bad practice for using instance variables is when these variables have no meaningful value outside of any method. In other words, they are actually just local variables that for some reason were declared at class scope. It’s a mistake sometimes made by beginners who seem to think that a declaration of a variable is somehow equal to actually instantiating an object and thus ‘optimize’ their code by declaring the variable as instance data. E.g.

class Foo {

	int temp1, temp2;
	
	public int multiplyAdd( int nr1, int nr2, int nr3, int nr4 ) {	
		temp1 = nr1 * nr2;
		temp2 = nr3 * nr4;
		
		return temp1 + temp2;		
	}
	
}

In the above example, temp1 and temp2 should of course be local to the multiplyAdd method.

Another bad practice for using instance variables is ‘inappropriate caching’. Of course it highly depends on the specifics of some piece of code what is actually inappropriate. It may be appropriate to instantiate some helper class that all methods are using as instance data, whenever that helper class is expensive to create. It’s however often not appropriate to use such caching when we’re dealing with stuff that is already cached at some other level or that represents some resource which needs to be closed after usage and is actually expensive to keep open. A Database connection in a Java EE environment is often a prime example of such inappropriate caching using instance data. E.g. :

class Bar {

	Connection connection = null;
	
	public void init() {
		connection = SomeFactory.getConnection();
	}

	public int doFooStuff() {
		Statement stmt = connection.createStatement();
		// execute some query and do foo stuff
	}
	
	public int doBarStuff() {
		Statement stmt = connection.createStatement();
		// execute some query and do bar stuff
	}
	
	public void close() {
		connection.close();
	}
}

In a typical Java EE AS, DB connections are already cached at the AS level (through a connectionpool). Caching a connection in instance data introduces far more problems than it solves. A typical usage pattern of a class such as Bar in the example above is to instantiate it, keep it around for some time, and call any of its doStuff methods when necessary. The problem with that is that it keeps the connection open for a much longer time than strictly required. Many application servers impose a limit on the number of simultaneously opened connections, so it’s often much better to close the connection as soon as we’re done with it. An additional problem with this pattern is the fact that the user of the Bar class needs to manually close the connection. This is not only an extra burden but also leads to the possibility of the user forgetting it and thus causing a connection leak.

Using instance data for ‘pseudo state’ may be another bad practice. With ‘pseudo state’ I refer to data that enters an object through a method call, is being used by several other methods that execute during this original call and which loses its usefulness for the object after this original call returns. Due to the fact that multiple methods make use of such data, it may be tempting for a programmer to simply store this data in an instance variable and let all methods refer to that. Sometimes this may indeed result in code that is more readable, but when used carelessly we’ll find ourselves again in the situation depicted by the “global variable hell”. Consider the following code:

class Kaz {
	
	public int data;
	
	public int doComputation(int data) {	
		this.data = data;
		increase();
		multiply(4);
		
		return this.data
	}
	
	public void increase() {
		data++;
	}
	
	public void multiply(int factor) {
		data*=factor;
	}	
}

In this example, an integer value is passed into doComputation() which assigns it to an instance variable upon which increase() and multiply() operate. After the call to doComputation(), the integer stored in data has no meaningful value for Bar anymore. It actually was a ‘shared local’ variable, where local doesn’t refer to a single method, but a small group of methods. Some people argue that this usage is exactly what instance data is for and that the alternative (passing the date value along to the different methods making use of it) actually degrades the coding style to procedural. Yet other people argue that instance data should only be used for data that has a meaningful value for the object as a whole.

In the example given above we have the additional problem that invoking the increase() or multiply() methods by themselves requires knowledge of the internals of these methods. If the method is long and complicated, it may not be obvious at all what instance data functions as ‘input’ for the method. E.g. to invoke increase() by itself we would need to do something like this:

Kaz kaz = new Kaz();
kaz.data = 4;
kaz.increase();
int result = kaz.data;

Indeed, a usage pattern that has a strong resemblance with invoking functions that depend on global variables in procedural languages. Naturally, most people would instantly say that the above is madness. Nevertheless, more often than not these patterns appear in code as the result of the ‘pseudo data’ practice. A programmer initially starts out with a class like Kaz, making only doComputation() public. After a while however there emerges a use to call increase() directly and instead of refactoring the code, the insane usage pattern of needing to assign directly to kaz.data before invoking increase() appears in the code.

Well, with this we arrived at the end of this series on best practices in Java. I hope it has been useful to people. Undoubtedly I’ll write a follow up sometime in the future. If there’s one certainty in my job, then it’s the fact that people always find ways to code using exciting new bad practices ;) In the meantime, please take a look at some of the other blogs my team-mates and I have written.

 

Arjan Tijms

 

best counter