Friday, September 9, 2005


A handy utility/helper class for obtaining instances of EJBs (and InitialContext instances and Home interface instances)

In a recent mailing list discussion I mentioned a utility class called EJBFactory that I've used in the past. It encapsulates most of the ugly boilerplate and error-handling code that an EJB client usually must include in order to obtain references to EJBs. I offered to publish a version of the code, so here it is:

It is not complete; for one thing, as the class comment says, it does not do narrow() ing of the remote references it gets. But that should be easy enough to add, and the more robust, complete version of this idea is in code owned by a previous employer of mine.
Hopefully someone will find this interesting and useful as a starting point for implementing whatever their EJB client code needs. I welcome any feedback about improving it.

Tuesday, September 6, 2005

Private Abuse

The use of private scope qualifier for methods is one of the biggest barriers to reuse in Java.

I was recently searching for a way to dynamically get an instance of a java.lang.Class that represents a primitive type (basically, I needed a dynamic form of what you get when you reference something like java.lang.Boolean.TYPE). I never did find an acceptable way to do it (please email me if you know of one), but someone brought to my attention that there is a method, java.lang.Class.getPrimitiveClass(String) that appears to do exactly what I need. Great! No - the method is private, so I have no chance of ever using it.
This gets to one of my biggest peeves about the state of the Java programming art - the abuse of private, which I see as one of the biggest hurdles to reuse and extension.

A typical response to this position is that "private has a definite use and can often times be preferred as once you make something public then so it must remain for ever," but I take issue with those points.

First of all, they're forgetting about protected scope, which is much more friendly than private and provides the same level of "protection" (the notion of protection in coding is a tricky concept , as I'll get to later) in most cases.
Beyond that, I don't buy the argument about once something is public you can't change it. Very few of us are writing the kinds of code that is set in stone - refactoring is usually an option. Deprecation is your friend, too.
Actually, if you are writing some kind of code that must be set in stone, all the more reason to use protected instead of private. Because in that kind of situation (rare as it may be) you should be striving for more flexibility, not less. Private scope can only add flexibility for code in the same class; on the other hand, for increased flexibility of all other code (the clients/callers and extenders), protected and public provide much more flexibility. When you use private, you are essentially assuming that you know exactly every way in which the code might be used or extended, which is, IMO, rather short-sighted and brash.

The kind of attitude that thinks that way (must make things private because I might want to change them one day or because I know this would never be needed outside of this class) is what Martin Fowler refers to as a Directing attitude (as opposed to Enabling) and I find Directing attitude to usually be counter-productive an frustrating to work with.

Finally, I'll say this: making methods private is often justified by saying "this is implementation specific and could 'break' the code if used externally." But again I find that a bogus argument - if I subclass a class and call or override its protected methods and it does not behave how I thought (so long as it adheres to the documentation or other contract), it is not necessarily the original class author's fault. I would certainly expect testing to happen, which would uncover any false assumptions or mis-use of inherited code. Again, Directing vs. Enabling - I prefer that I'm given as many tools as possible rather than being stuck with the limited set that
some original programmer thought I would need.

OK, one more "finally": Smalltalk, probably the most pure of widespread OO languages, gets by just fine without private methods at all. I've never heard of anyone coming upon a situation where they just NEEDED them and where marking them as "intended to be" private
didn't suffice. Here is an excellent article on the subject
If you read nothing else I've written in this diatribe, read at least that and the Martin Fowler article. They are written by far more effective writers than I, and it shows.

Sorry for ranting - it's late and I was bored. Seriously, I've spent 10+ years thinking about this topic on and off, and my position is very firmly set after all that time.

Monday, July 25, 2005

Code Structure: Multiple Exit Points & Code Standards

On the StriaghtTalking-Java list today, the following question came up:

"What is the consensus with regards to single entry, single exit methods. I was never taught to code to this convention but recently heard that some companies require it. I wondered how people felt about this?"

There were many responses, some agreeing but mostly disagreeing that it was a good "standard" to enforce. Some of the arguments in favor of single-exit-point-ness were:
  • Multiple exit points can lead to more bugs
  • There's too much license in "sometimes it's ok to do x". That's the same as saying "It's always OK if I feel like it on any given day."
  • It is easier to "see" the method structure with one exit point.
My two cents is that code readability wins out over dogma or "standards adherence." Sometimes a single exit point is the most clear structure and makes the code clean. However, I've read and written many, many, many methods that were far more readable with multiple exit points that they were with only one. I also agree that small-grained methods make this even less of an issue, and that exceptions usually throw single-exit off anyway.

To address the "more potential for bugs" argument, I respond with unit testing. A method that is complex or intricate enough to have multiple paths of logic should usually have a set of tests for each of those paths.

In summary: sometimes a single exit point (return) is more elegant, but sometimes multiple returns lead to more elegant code. We might all disagree (and almost certainly do) about how big those two "sometimes" are in relation to each other, but the bottom line is, "Readability/elegance/simplicity trump all coding rules or standards" - it's going to be pretty hard to argue with that.

In general I feel that code standards usually go too far, are too dogmatic. A coding standards doc should, IMO, always be called a "guidelines" doc and the first section/chapter should state something like "code readability and elegance" trump other rules. Yes, it requires careful attention and discipline to avoid the "I don't feel like it today" trap - but if programmers don't have discipline good attention to detail, well then "where they put their curly-braces" or "how many exit points they have in methods" are going to be the least of the problems...

Wednesday, July 6, 2005

Java Generics: I'm not alone

My thoughts on the addition of parameterized types (aka, "generics") to Java have been documented well here, on the StraightTalking-Java mailing list, and the Eclipse newsgroups. Bruce Eckel has always been on the same side as I, but until now there was little high-profile support for that position. Now, however, it appears to be gaining momentum. Ken Arnold has posted a blog entry "Generics Considered Harmful" and I'm glad to see it got Bruce Eckel's attention as well as Lambda the Ultimate.
Mr. Arnold and Mr Eckel are more eloquent than I have been about expressing the position that we all seem to share - I particularly like Ken's coining of the term "complexity budget." That is the succinct, easy-to-understand phrase that I have been searching for in my ramblings on the topic.
Bottom line: I'm glad to see some others coming out to express the idea that this "upgrade" may have pushed Java out of the realm of "simple" languages for good. I'm not alone any longer in my distaste for the increasing complexity the language designers are introducing.
Not that the company makes the discomfort any easier to live with...

Tuesday, June 7, 2005

Early Thoughts on Portals/Portlets

I am in the process of evaluating/learning portal and portlet technology for my company. We are a HUGE organization, so there have been several efforts of exploration in various groups within the company. In fact, the "official" company-wide web-app and services framework team has actually implemented portlet functionality into the proprietary framework. I don't like the level to which they have abstracted away everything, though, so I'm making it part of my effort to evaluate their implementation. We use WebSphere Portal Server (we are a huge IBM shop, so it was the only realistic choice).

Thus far, my impressions of Java portal/portlet technology is that it is over-hyped. How many applications really have Yahoo-like requirements? Also, the portlet spec is over 18 months old at this point, but there is no public information about any activity on it. IOW, it appears to be stalled at the 1.0 level, and that 1.0 spec is quite immature. There are several key ideas that the vendors have all solved in proprietary ways that need to be part of the standard API and spec. The authors of the spec are remarkably silent on the progress of a 1.1 or 2.0 version - my educated speculation is that there is little or no progress happening at all.

The user activity I keep seeing (a Yahoo Group, articles, blog entries, etc) seems to be inordinately focused in the offshore population. I wonder if the offshore/outsourcing companies are hearing the hype from management types and trying to find ways to inject portal/portlet into every project they contract now...

Performance also appears to be a major issue. The extra processing required for every single user request is multiple times that for servlet apps, and, especially within our company, that results in apps that can handle significantly fewer concurrent users per unit of hardware than equivalent servlet/JSP apps. IBM claims that latest versions of WPS are significantly better than previous versions, but also seems to acknowledge that it is not equivalent to plain-old servlets and may never be - the stated hardware requirements for running Portal Server are pretty high-end.

Something else: I haven't seen much talk about portal in terms of transactional applications. I can see that having a "main" app as a portlet surrounded by little helper stuff like calculators, mail checkers, stock quotes, etc. would be "nice to have" candy, I haven't seen any examples of highly transactional portlets all coexisting and sharing window space.
Another potential problem is that of screen real estate - you UI designers have a significantly harder job when you're dealing with multiple portlets on every page; it means none of the portlets have as much real estate to work with as they would if they were individual pages or traditional web apps.

I think the portal idea can be very useful for certain applications that have specific requirements about incorporating multiple data views onto one page. I just don't think many applications actually have such needs. When they do, implementing it in plain servlets and JSP can be done, but would require building something like the portlet API and container anyway. It's just that I prefer to build something like that as-needed and specific to what you really need, rather than relying on a huge, bloated, wants-to-do-everything implementation like is provided by IBM, BEA, etc.

As I said, I am still learning and evaluating and planning some PoC mini-projects to explore these topics. Thus, my opinions are young and likely to change at least a little over the next few months

Wednesday, April 6, 2005

The price We've Paid

A few days ago I came across yet another example of why the implementation of parameterized types (sometimtes called "generics") in Java 5 (JDK 1.5) is going to hurt more than it helps. I dread the intricacy, complexity, and sinuosity that quickly results once you've started down this path...
Let me be clear, lest I get a flurry of emails from people who don't get my point: I am not arguing that parameterized types are without merit or use - of course every feature has a place where it will prove valuable. However, it is important to evaluate the cost of a feature when considering it. In the case of parameterized types in Java, the cost is an inordinate increase in syntax and complexitiy and mental overhead. The cost, IMNSHO, is very high - way too high to justify the feature.

Do we really want to have to write (or worse, read/maintain) this kind of code on a daily basis?
-------- Original Message --------
Subject: Re: (De)serialization and Type Safety?
Date: Fri, 25 Mar 2005 07:05:48 +0100
From: Philippe Marschall <xxxxxxx>
Organization: EclipseCorner
Newsgroups: eclipse.platform

What to do? Are these all ignorable warnings, given that I know I'm > putting a Map<String, List<String>> in at the other end? Even if so, I'd > still like to be able to write warning-free code Well it depends what you want, if you want type safety and get rid of the warning, something like this might work.
public Map<String, List<String>> readFromSteam(InputStream is)
throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(is);
Map<?, ?> currentLists = (Map<?, ?>) ois.readObject();
return this.copyToNewMap(currentLists);

private Map<String, List<String>> copyToNewMap(Map<?, ?> oldLists) {
Map<String, List<String>> newLists = new HashMap<String,
for (Entry<?, ?> each : oldLists.entrySet()) {
String key = (String) each.getKey();
List<?> oldList = (List<?>) each.getValue();
List<String> value = this.copyToNewList(oldList);
newLists.put(key, value);
return newLists;

private List<String> copyToNewList(List<?> oldList) {
List<String> newList = new LinkedList<String>();
for (Object each : oldList) {
newList.add((String) each);
return newList;

Friday, February 4, 2005

Struts: At what point does it pay off?

The topic of Struts recently came up on the ST-Java mailing list and my thoughts about it got rather lengthy, so I thought they'd be better served here than just in a Yahoo message.
The following question was posed:
I admit I don't know much about Struts, but I am wondering whether it's a bit "heavy weight" (for lack of a better word) for a small system (i.e., in terms of how rapidly you can do development in it) and/or whether there's a big learning curve involved in coming up to speed with it. Got any thoughts or experience you can relate that might alleviate those concerns?

It's hard for me to be completely unbiased in answering that, because I am already intimate with Struts. But, I'll try...

There is definitely a "tipping point" below which you may not want to invest the time into Struts. Like so many other things in our chosen art, where exactly that point lies depends in large part on the person/people doing the work and the nature of the relationship you/they have with the Goal Donors and Gold Owners (tm).

I would say that the point where learning and using Struts becomes worth it is likely lower than some people think/say it is. It is not as heavy as I've seen/heard some people say. And for apps with simple needs, it is simpler to use than for apps that have complex needs. IOW, in some ways simpler apps don't need as much design, maintainability, cleanliness, etc (ie, the things Struts brings you to); however, in other ways simpler apps mean less need for the more advanced Struts stuff that makes learning/using it more burdensome. Does that make sense, because it's Friday and I've had one of those weeks...?

Bottom line, if you need a small app that is low-volume, only a few pages, and pretty much will never need sophisticated logic (besides, for example providing CRUD for a simple data model), well then Struts can be too much. But I see it like buying some big-ticket power tool for your garage or shed: yes it is difficult to justify the cost and storage required to get one just to cut a few 2x4s for that small project. But once you've made the investment to have one, you can use it again and again for both small projects and large ones that come up. And the small ones become trivial and the large ones become a lot easier.

When I said "I will never do a web app with plain old servlets+JSP," I should have made it clear where my "tipping point" is - perhaps 5 pages with simple DB calls and no "business logic." Because, yes, even I wouldn't use it to, for example, make a utility app that does soemthing small like store my contacts list in a DB and give web access to them. I least I don't think I know, now that I think about it, I probably would, because with Struts and its rich set of taglibs I can crank out a couple of JSPs and Action classes that do that kind of thing just as easily as if I tried to use straight servlets and/or JSP and scriptlet - And since scriptlet makes me want to throw up, I'd choose the Struts/taglibs approach if for no other reason than to hold my lunch :-)

I recently introduced Struts to the team I work on for use on a new project (re-write of an existing atrocious web app). The 3-4 people I'm working with on the project, none of them had any experience at all with Struts, although they each had worked on J2EE-based web apps. With my past experience to guide us, we have been able to get up and running in a pretty good amount of time, and that includes adopting Tiles (which I had not used before) and the latest Struts version (1.2.x - I had only used 1.0 before). Everyone, including the page design/HTML "guy" were able to pick it up pretty readily, with me providing abbreviated insight that is proably more efficient than having to scour all the documentation and mailing lists. It has gone very well so far, and now we can cank out new functionality with realitve ease.
The moral of that story is that having someone along for the ride who has done Struts before is probably a big advantage. I am not claiming to be anything special as a mentor or guide or teacher - it's just that having past experience, on the team, close at hand, made a noticable difference. My teammates have said that repeatedly over the past 4-6 weeks.

Of course, I am a "framework" guy - I enjoy using well-desinged ones, I enjoy trying to extract them from my own work - so I'm probably naturally inclined towards things like Struts that are nicely abstract and pluggable. But I'll tell you, in the past year I've also had to work on a plain servlets+JSP (with lots of scriptlet - YUCK!) application, and I was neither as happy nor as productive as I am on this new one where Struts is the Path of the Beam.