If you consider yourself a well-rounded Java programmer you know threads. You must also know or heard about threads in Java 5. Or, the overhaul of threads in this version (and Java 6). This is a complicated topic but whether you like it or not, you must update your skills and learn about concurrent programming in the newest versions of Java.
I just started doing so. I actually feel pretty weak in this area. But I started erasing this gap and I hope to be “up to speed” soon. I ordered Java Concurrency in Practice (supposedly a must have), I ordered Thinking in Java, 4th edition (it is a great book – no, you cannot find the latest version online), and I read about threading online as well, links below.
Like I said, threading is a complicated topic in programming, but if you consider yourself a good programmer, you must master it.
ReferenceConcurrency in JDK 5.0, developerWorks tutorial (need subscription, PDF version)
Introduction to Java threads, developerWorks tutorial
Java Concurrency in Practice, excellent book on threads
Thinking in Java (4th Edition), excellent book on Java with a very good chapter on threads
Java 5 SE, in my opinion was a great release. While reading a blog post, Java 5 – The Gems and the Duds, the author gives thumbs up to the concurrency package, generics, CachedRowSet, and annotations; he gives thumbs down to autoboxing. And he’s not sure about varargs and enums. Very good post. I generally agree with the author. But…
I happen to like enums. I have used them several times already and they did a great job for me: made the code easier to understand and the code more robust (type safety). What are they good for?
I have used enums to encapsulate the different types. Pre Java 5, we used to have a lot of String constants defined. What that does it puts a lot of unrelated things together. It’s hard to see where each particular constant belongs to. There is also no type safety, as the constant can be substituted with any value.
No more. I can now define an enum. It nicely encloses related types. It gives me type safety. They make your code more readable. They make your comparisons easy — you can use == with confidence.
A simple example,enum DayOfWeek {MON(1), TUE(2), WED(3)… /* need to define a constructor in this case */ }
In code, you would no longer rely on integers 1-7 or strings for days, you would get a DayOfWeek param and you would be sure that you actually get the right value. You could also define a utility method inside the enum, getByDayNumber(…) and get the day that way.
In my opinion, a great addition.
ReferenceJava 5 – The Gems and the Duds, The Art and Craft of Great Software Architecture and Development blog
Enums, java.sun.com article
Are you using them?
I only found out about them recently — they’ve been available since JDK 1.4. I think they’re vastly underutilized…. But they can be really helpful in debugging situations and don’t incur any performance hit.
You can enable them in your JDK by adding “-enableassertions” to default VM arguments (type “jre” in filters in Eclipse and edit it there).
Then in your code, whenever you have a feeling “this can never be null or false” add the assertion, as inassert thisField != null;
and you’re done.
Assertions are a great debugging tool.
Java 6 is around the corner. One of its most exciting features is scripting, I think. There are two sides to it: client-side scripting, and web scripting (I’d like to see an example), as explained by the author of the article below. Examples of client-side scripting are in the article, Scripting for the Java Platform.
In any case, this JSR gives us many options of using other languages inside Java. That’s cool.
ReferenceScripting for the Java Platform, Thomas Kunneth
I came across a good list of tools (most of them Eclipse plugins) that provide reports based on your source code. All free. Cobertura is a code coverage tool that looks very similar to Clover (which costs a lot) and it’s free.
This list is taken from an article by Mike Clark on StickyMinds.
Checkstyle: A highly configurable coding standard checker with a default set of standard and optional checks. (http://checkstyle.sourceforge.net)
Cobertura: A code coverage analyzer that identifies areas of code that aren’t covered by tests. Unfortunately, code coverage metrics are often used as instruments for programmer (and tester) abuse. When used properly as constructive feedback, these metrics can help improve your testing skills by identifying aspects of code that often go untested. (http://cobertura.sourceforge.net)
JDepend: A static code analyzer that generates design-quality metrics based on Java package dependencies, including identifying circular package references. Disclaimer: Your humble author wrote this tool. (http://www.clarkware.com/software/JDepend.html)
ReferenceCode Craft: Staying Out of Code DebtStickyMinds.com, by Mike Clark
If you’ve been working with Spring MVC, you already know this. Whenever you create a new Controller you end up injecting the services or DAOs (if you’re not using the service layer) that you’re going to use. It gets to be a little cumbersome and repetitive. It could be improved. How? By defining a Spring aware factory.
First, the problem. There are several problems or inconveniences. First, you’re injecting the same service or DAO everywhere. If you’re checking if it actually was injected, then you’re duplicating that code. A violation of best practices. If you’re not used to inversion of control, it tends to be confusing. You’re asking yourself, where did this object come from? Any time you write a new controller, you also have to write some more XML and you don’t get syntax checking (that’s my number one complain about Spring). You’re braking the DRY principle: Don’t Repeat Yourself.
Is there a solution to this? Yes, there is. A nice one, actually. I got the idea from Hibernate Quickly, which I’m currently reading. You create a Factory (best practice, anyway) and you use that to retrieve your services or DAOs. No injection, no Spring. But how do you read the beans from the Spring XML files? The factory will implement ContextAware interface. (You have to also configure the Factory as a bean in the XML file for this to work.) Once you do that, you have access to all of the beans you defined. Nice and easy.
Here’s an example bean that you’ll end up with:
public class AppServiceFactory implements ApplicationContextAware {static Log log = LogFactory.getLog(AppServiceFactory.class);/*** Set by Spring when initialized.*/private static ApplicationContext appContext;public void setApplicationContext(ApplicationContext applicationContext) {log.debug("Setting application context [" + applicationContext + "]");appContext = applicationContext;}static ApplicationContext getAppContext() {if (appContext == null)throw new IllegalStateException("Application context should have been set");return appContext;}
private AppServiceFactory() { /* singleton */ }
public static AccountService getAccountService() {String serviceName = "accountService";AccountService service =(AccountService) getAppContext().getBean(serviceName);validateService(service, serviceName);return service;}
static void validateService(Object service, String name) {if (service == null)throw new IllegalStateException(name + " has to be configured.");}
// ...}
What are the benefits fo doing it this way? It’s a whole lot easier to understand. You’re asking the factory to give you the DAO or a service. It’s easier to debug. It follows the DRY principle — you’re not re-injecting the same bean all over the place. It’s easier, and faster: You define the controller in the XML config, you create it, and just use the factory in the controler. Don’t need to inject anything, no extra configuration for other controllers. You’re following the DRY principle. The service is retrieved and set in only one place. If there’s any validation you need to do, you’ll do it in one place. It works nicely for me.
What is JavaServer Faces? Do you know what Struts is? No? Then you must have been on a vacation for a while, huh? Anyway, Struts and JSF are competing technologies. They’re basically implementations of MVC (you have to know Model View Controller).
I’ve done several examples with Struts and I must say that it’s OK. I’m not a big fan of Struts.
JSF, on the other hand is different. It has the better things out of Struts, it is easier to use, and it’s a standard. Plus, JSF will be included as part of J2EE 1.5 coming out next year. I must say I’m a big fan of JSF and I think it will be big over the next couple of years. Learn it, compare it, and use the better one.
There is a lot of coverage on JSF lately. Here are two articles I really liked that talk about Struts and JSF. One is from the creator of Struts, Craig McClanahan, The Best of Both Worlds: Integrating JSF with Struts in Your J2EE Applications. The second one is probably the best intro to JSF you’ll find, JSF for nonbelievers: Clearing the FUD about JSF by Rick Hightower.
Did you know that you could write a JSP tag without writing a single line of Java code? I didn’t. I was surprised today when I discovered that. I’m going to show you how easy it is. Let’s take an anchor tag (<a href=”">link</a>). If you don’t get to write it very often, you might forget the exact syntax. Why not write a simple tag? This would make things easier.
Here is a simple tag, link.tag:
<%@ attribute name="address" required="true" description="Location"%><%@ attribute name="title" required="false" description="Label"%><a href="${address}">${title}</a>
That’s it! You’ve got yourself a jsp tag. Here is an example, link.jsp, of its actual usage.
<%@ taglib tagdir="/WEB-INF/tags/" prefix="tags"%><html><body><p><tags:link address="http://aol.com" title="aol.com" /></p></body></html>
How about that? That’s one cool feature of JSP. Read some other cool stuff about JSP 2.0 here.
Another cool feature is the use of JSTL, which is a pre-defined tag library for common tasks. What tasks? Access to request parameters, access to beans, logic, and other. If you use JSTL, your JSP pages are without Java code. You use a simple scripting language EL (Expression Language) for that. After all, JSP is a view. It should not have any Java code. Period. If you are considering JSP, or if you want to move to JSP, use JSTL. It will make your life much easier. Plus, you’re not going to fall into the trap of doing most of your business logic inside your page. JSTL gives you a seperation of layers by default.
Here is a link to very good JSP 2.0 article, Faster Development with JavaServer Pages Standard Tag Library (JSTL 1.0), by Qusay H. Mahmoud.
Do you think J2EE is complex? Do you think having many different frameworks, different APIs, and many different specifications help or hurt it? Do you think not having a single, one-way avenue for an inexperienced developer helps? I don’t. In this article, Simplifying Complexities of J2EE, Debu Panda gives you several arguments why J2EE should be simplified. I agree.
Are you looking to learn J2EE? J2EE Learning Guide is a collection of links to J2EE articles, tutorials, books, products, and more. I got this link today from del.icio.us/tag/j2ee . It’s amazing how many different links are on this site. Take a look and enjoy.