Main

Java Archives

September 30, 2002

My First AspectJ Experience

Even though this is happend about a month ago I just started my blog today so it seems like a good enough topic to do a log entry about.  Let's just say AOP (and AspectJ as the tool) is really kewl.

At my job one of my tasks is to write a GUI to do the editing of some rather complex configurations.  So naturally I had written up my own meta data to do this (more later).  One of the problem I had was that on some of the screens the code I had written to do the layout were sucking up a lot of time just to do the layout of what should be some eimple pages (and even longer for some pages that were not so simple).  While at the same time some of the larger pages were just fine.  

So how does one go about debugging this?  I suppose I could sync up the model in UML and look at the collaboration diagrams, the problem is when you get much past the high level operations UML begins to look like a first gade scribble fest, and that is before you turn on the auto-formatting.  (Perhaps a subject for another future entry about how some things should be left out of UML diagrams because they just clutter things up).  I guess since I wrote this code I should know what was wrong.  But let's face it, nobody outside of training exercises intentionally writes O(exp) code (which is what it was behaving like).  

As it turned out about two weeks earlier I had picked up a book Aspect Oriented Programming with AspectJ while my wife and I were killing time before a Friday Night Movie.  So I decided to try applying the profiling aspect to my layout code (but totally hacked up to get the stats I needed).  All I have to say is that it was incredably cool.  To get the sort of stats I was getting confirmed that it was exponential process: one method was being called 2 million times on my CPU killer test, 16K, 33K and 66K on my check it at each step test as well.  Almost a perfect 2^n cost of computing.  But what schocked me was what was causing those huge jumps... a property listener.  I was re-calculating parts of the layout in response to the addition of a layout element, which was causing other items of the tree to be re-calulated for each addition.  Being basically a binary tree the size growth makes sence as I add one more item.  Without this knowledge I would in all likelyhood be re-writing that code today.

So anyway what I thought was the coolest was that all of this diagnostic code was dropped at every method invocation in my select classes for the areas I was worried about.  It truly was a seperation of concern because I usually do not care how often a method is called or how long it takes.  But when I care I really care.  And applying a 30 line aspect to 15 some odd classes and loading it into MS Access so I can do some SQL queries is a whole lot easier than insturmenting it by hand.

October 4, 2002

Developer Testing

I was going to write a big old rant about developers who refuse to test their code or feel it is QA job or who feel that we need to hire someone to write these junit tests. But it would have been a pointless and long vent that went no where. So let me just say that I am a big advocate of the apporach that XP has to Testing. not jus thte unit test everrything but the whole additude that the developer is the principal responsable agent to chatch bugs. They cannot catch everything, so you have QA people to help there (but QAs real job IMHO should be to test things like scaleability, durability and non-happy-path items the developers tend to developed blinders for, not test-script monkeys). A Developer who doesn't test their code is like a gun without a saftey: an accident waiting to happen.

So waht brought this on? Well testing one's on code can brign greate peace of mind. I am mantianing and expanding on some code that I inherited after a layoff when the previous owner got re-assignemd. Some code changes can have effects across thousands of generated xml files when I intendede them to have effects in a few. To combat this I use a set of validation programs to make sure that all of the XML is internally consistant with what I expect and a diff tool to diff it against a previous know good generation. It is a load off of my shoulders when I can run it agianst the 4,000 some odd generated XML files and find out that, yep, only the 40 files I ment to meddele with were indeed the only ones that got changed. Which reduces the number of files I need to examine by hand 1000 fold.

Testing increases quality and saves time and money. And I sure am liking the saves time part right about now.

October 14, 2002

JView Swing Suprise

Color me suprised! I downloaded Swing 1.1.1 from the java web site and ran it against Microsoft's JView program, and my splash stuff worked with only Java 1.1 level tweaking! I also ran the SwingSet test and was suprised that the performance was fine! (1Ghz and 512MB of ram may have figured intot that however...)

The upshot of this is twofold: first I will be able to comply with the Apache Ant Task Design Guidelines and write the Inform.ant portions to conform to Java 1.1. Second is that Inst.ant can be writting to run on a "stock" Windows machine without having to got to an AWT parallel solution. Just include the classes in swingall.jar and you are good to go. So the odds of seeing a SWT version also fell to near zero as well since I won't be plugging anything but console and GUI, where GUI means swing. Being able to run on JView was the whole point of designing with multiple GUIs in mind, so now I can go with a "write once, debug many times" solution.

October 16, 2002

Response: Rickard's AOP thoughts

Rickard posted some thoughts on AOP and I must say it is amazing how some of those items could be done in non-java without the pre-processors (thought not in the same language). To me AOP is just like OOP and structured programming before it: principally a practice. It is also a practice that is re-enforced and simplified by language constructs.

(However I would like to say that EJB is an example of seperation of concers; as long as what you are concerned about what EJBs are concerned about.)

Here goes. AOP, to me, is two things: first, you get to pick objects apart into smaller parts each of which has a nice clearly defined purpose. These parts can then be assembled to form big objects. [ Random Thoughts ]

As you go on to read further what started registering in my head was *hushed*tone* Multiple Inheritance *gasp*. What it is closer to however, is the OOP pattern composition. I haven't seen this achieved that often except in rather brittle examples. When you think about it though composition is a OOP way to achieve separation of concerns. It was the casting example that made me jump out and say that it can also be accomplished via multiple inheritance. But in that case you lose the possibility of composing the object of sub-classes of the pieces, like a V-8 engine for a Denali v.s. a 3-cylinder for a Geo Metro. At a cursory glacne it appears that using AOP to gain this type of composition also suffers from this flaw. What if I want Unix type User-Group-Other ACLs on some and NTFS every-possible-permutation style ACLs on other objects? You could flatten out the classes and make two ACL type. But this false when that choice varies not based on type of object but arbitrarily per object. For example: some pages kept on client A's extfx system and some on client B's NTFS but both aggregated in the same place. That's why I don't see how (ACL)page has any intrinsic value (other than aesthetics) over page.getACL(), in fact it seems that the latter is better in that sense.

However, this is a red herring over what AOP is providing, in that when following the principals of AOP you can do either to achieve composition. What is important is that you don't litter the ACL code special cases in with the other items and keep ACL code i the ACL. It seems to me that if you cannot keep ACL code in one place perhaps the concerns are not separated properly or they are not separable. Keeping the concerns separated is alot easier when the language and framework are designed with separation of concerns in mind.

Second, AOP is also about what most people would call "interceptors". That is, doing stuff before and after a method call on an object. [ Random Thoughts ]

What came to my mind from this paragraph is function pointers, or as Microsoft calls them toady delegates. Also C macros are quite crafty in that regard. For function pointers you could write a method to do the work around the method and then call the other method, and store it with the other method. But to do it arbitrarily to arbitrary code you would need (1) to make all function call through pointers and (2) some place to store what the previous function was. To accomplish 2 you would need to pass some overhead like a pointer to a stack of methods to know what the next one is, which is exactly what AspectJ and what Rickard's code example do.

It is crucial to remember here that while the object being referenced in client code may implement 10 interfaces, there is no class (beyond the dynamic proxy class) that actually implements all of those. They only implement one interface, and the AOP framework takes care of the routing from this big happy I-got-it-all "object" to these smaller objects. All of that is transparent to the developer though. [ Random Thoughts ]

One object that can accept any message... hmm... doesn't SmallTalk allow any message to be sent to any other object? Seems to me more and more AOP languages are talking the shiniest pieces of other languages and making them their own. Sure you could do it in C, but you wouldn't want to since void * is a great way to fumble the memory heap.

This feels like going through the candy store and throwing out the blue SweetTarts, M&Ms with peanuts, and anything made with dark chocolate. How can anyone like dark chocolate?

October 20, 2002

Productivity is the name of the game

Last night while I was starting to write some of the GUI code for inst.ant I initially tried to code it all by hand, to be as IDE agnostic as possible. However I came to the (not so quick) conclusion that coding guis by hand sucks. So after a brief struggle with my ReplayTV I came back and fired up the GUI editor on NetBeans 3.4 and within half an hour was a lot longer along than I had been all night with coding by hand. After a little more work today I've got some more of the frame working like I want it, and I feel it would have taken me two to five time as long as by hand. The downside of this is that some of the generation stuff is going to wind up in the CVS tree. But after getting so much done I don't care as much as I used to.

It's not that I am a neanderthal and feel that machine generated code is the spawn of the devil. At my paying job I use the NetBeans GUI designer any time I do GUI work. But since the only other guy doing UI coding comes from a MFC background machine generated code is not a problem for him (as long as it comes from a wizard). And if any of the other people I work with have a problem with it (which they haven't yet ) I would just say that "If you want it done your way then you better do it yourself." and laugh as they work self-inflicted 80 hour weeks. Back in the day when GUI meant AWT I would always code my GUIs by hand, but that is because back then GUI editors sucked real bad.

It's amazing though how ingrained the feeling of "if it's not hard I am not really coding" can be sometimes. It makes me remember the time I was in Chemistry class arguing with one of my friends at the time the merits of high level languages over assembly (I was on the side of C++, this was pre-java). He just wasn't getting that time==money, and argued that you could do anything with assembly that could be done in any higher level language because it gets compiled to that anyway, so why not jsut start with assembly? He also had a hard time grasping the concept of showering daily to impress chicks.

But once the light bulb turns on it can become a blinding searchlight. A little less than a year ago a Windows consultant realized that "The power of Java (and therefore the power of .NET) is that it provides a major productivity boost for the programmer." (He directs the rest of the blog entry at dot net granting the same power). A coherent toolkit for the right problem can be like dynamite is to mining ore. Yes you could use a pick axe to build a tunnel, but if you had dynamite you could safely use you wouldn't want to.

(edited after a good nights sleep for comprehension)

October 22, 2002

AOP and polymorphism again

It looks like my ramblings have been noticed. A post where I was discussing how several AOP patterns could be done in non-AOP frameworks and languages (much like OOP and non-OOP) was responded to in a fashion of "My AOP is not like that! AOP is the second third fourth coming of High Level Language Nirvana!" Ok, it really wasn't that extreme but it was really fun writing and editing the last sentence. However I do feel that some of my comments were misunderstood in the response.

Rickard's response focuses entirely on my composition comments, first starting with my analogy of the Denali and the Geo Metro.

When you think about it though composition is a OOP way to achieve separation of concerns. It was the casting example that made me jump out and say that it can also be accomplished via multiple inheritance. But in that case you lose the possibility of composing the object of sub-classes of the pieces, like a V-8 engine for a Denali v.s. a 3-cylinder for a Geo Metro. At a cursory glance it appears that using AOP to gain this type of composition also suffers from this flaw.
It doesn't, not in my framework anyway. You can either specify a default implementation for an interface, or you can specify that a particular implementation of an interface is to be used in a specific composition. This accomplishes what is outlined above. [ Random Thoughts ]

My analogy wasn't perfect, although it serves some purpose. A better example may be a Saturn VUE. You can get one with a 4 cylinder or V6, and you can get 4WD or AWD. A few sentences after the quote rickard had I mentioned that this can be solved by flattening out the hierarchy, as Saturn does. All four possible compositions have their own class. At this level the combinatorics aren't that bad. Now let's consider that each car can have any of 3 stereo systems, 2 interior colors, 7 exterior colors, and about 5 other options. 2*2*3*2*7*2*2*2*2*2=5376 possible ways to have your saturn. Now what if we added a third type of braking system (Anti-Injury Inertial Dampening Brakes)? One of those 2's become a 3 and we need over 2000 more ways a car can exist, and creating one class per car type is expensive in the hierarchy alone!This is what I meant from flattening the hierarchy. (Full disclosure: we are 2 Saturn family, but don't own a VUE.)

Having not seen Rickard's code, I cannot be sure if he is creating a concrete class for each combination, but there are two possibilities I see from reading his posts. The first is that he is only creating the 10 particular concrete instances he would use out of the huge combination space. Which is fine if you can statically prove that those 10 would fit your needs. The second is that he is storing them and the class is actually a proxy, and the cast to (ACL) is casting to a proxy that forwards all requests to the concrete class. Instead of writing or dynamically generating that big old proxy class why not just write one interface ACLable with one method, getACL()?

Neeext.
What if I want Unix type User-Group-Other ACLs on some and NTFS every-possible-permutation style ACLs on other objects? You could flatten out the classes and make two ACL type. But this false when that choice varies not based on type of object but arbitrarily per object.
I don't think that is very realistic. What is realistic is that a bunch of objects in a system are somehow similar and have the same way of handling the ACL interface. [ [ Random Thoughts ]

It wasn't the realism I was trying to address with this example, which was not about how the files are stored but about the ACL itself. In the next section Rickard describes how he solves this is to flatten the hierarchy into 3 cases, which is what I described as well more or less. I could find a more realistic example but apparently they are not in your system. I was trying to describe a composition that was not binary (ACL v.s. no ACL) but had more complexity, in this case trinary (Unix ACL, NTFS ACL, no ACL). The fact that the example dealt with file systems and storage was what was focused on rather than the implications of the different ACL schemes that they have. Both can validate create, read, update, delete permissions but have wildly different ways of coming to those decisions and different data sets to draw from. But this seems to be more the realm on the Strategy Pattern that the Composition pattern, which is another design pattern that can use and abuse polymorphism and late binding. Objects requiring arbitrarily changeable components may not be the case in your system, but when you really need them you really need them.

Well, I really need to get work done today.

October 29, 2002

Eclipse and Ant

If you use Ant with Eclipse , you might want to check out these two new plugins Antview and Planty.

The Eclipse folks liked both these tools so much, they've asked the author if the would consider donating them to the project. It looks like Antview's author has accepted, so the next release 2.1 will include some or all of AntView [ A cup of joe ]

I may have to actually look at eclipse again. Support for ant like what they had in the screenshot was my #1 complaint about it. Now if they just had keyboard shortcut re-mapping.....

October 31, 2002

Loads of Ant 1.5 Goodness

At my work we finally got around to getting Ant 1.5 into the build process and taking advantage of the new features, which are just what we need. As a co-worker said "Ant seems to be writing the solutions to the problems we are having in the build as we develop them." I've only had a chance to put two of the major new features in, and boy are they good ones:

  • filterchain expandproperties
    This has eliminated about 200 lines of build.xml, all of them lines like <filter name="property" value="property"/>. This also eliminates a point of breakage where a config file depends on a new property, and we forget to put the values in wherever they are needed.
  • classfileset
    This eliminated another 100 lines of build.xml. And also helped get rid of about 100 classes from the applet jar we have. And if we create a new dependency to some class in a different part of the code tree? No build file changes! I used to use jini's classdep tool to ge this data but now I can just have Ant do it automatically, as a fileset even!
Given features like this it amkes build maintenence a treat to watch things optimize themselves, rather than haveing a dedcated makefile engineer.

November 1, 2002

Some Sneaky AOP Talk

John Lam was remarking about how OOP and such are mostly used for abstractions now rather than for re-use when he said:

But is it enough? As most of you reading this have experienced, there are limits to what you can do with Patterns, OOP, and structured programming. You find that there are features that cut across your well-designed class hierarchies and object graphs. These are the warts in your program that spring to life innocently enough, but then spread as your program becomes increasingly more complex. It is these warts that make it hard for you to comprehend your software. It is these warts that make it hard for you to extend your software's functionality. [ IUnknown.com ]
That is almost exactly the typical rational for AOP. And he didin't use the words "Aspect" or "AOP" once. If anyone needs a non-hostile justificaiton of AOP to give to someone (say, a boss) this would be a good article to send.

November 5, 2002

Referr Logs are Fun!

The strange things you find in referrer logs: someone did a Yahoo search for "some ones hacked me.how can be free and he does not has hacked me?in farsi" and all they got was my page. I guess that's better than ANT & Install & Errors.

December 4, 2002

Belated Solicited Opinion of NetBeans

Well, my mis-adventure with marketing folk has prompoted Oliver to write about their experience with NetBeans, so maybe I sohuld post my opinion that I was unkindly solicted about. First I'll start with the nits that anny me:

Startup Time
Yes, it is dog slow. Apparently they have a guilty consince about it since it was mentioned in the first e-mail without any real provocation. Seriously, what is it doing at start up? Re-hashing the file indexes or something? It is slow and it grinds my hard drive. And it's not inadiquate setup either, I got 512MB, 1Ghz, and -Xmx256m. Once it starts it's fine, so I just usually surf the web when it's starting up.
Bad Attitude about Bugs
I have one case and point for this one: using F12 on an ant build does not give the same support as if you used the built in java compiler. It worked in 3.3, the bug was know and a fix known before 3.4 shipped. But it didn't make the code freeze so it got shipped without it, jsu so they could make a date (that already slipped a week). The analysis in the bug said that it only affected users who were using keyboard only, and they could get the same effect with the mouse. The truth is that it's a lousy excuse not to include it because it's plain old anti-user. We are talking about funtionality that existed in a previous release that was lost in a future release, and it was wll known how to fix it. I have to agree with oliver that the atttiude towards some bugs needs to imporove, and featuritus should take a back seat to fixing bigs that break existing functionality.

So those are my problems, now a marketing type survey might be interested to know what I see in other competing products like, say Eclipse, that might send me to that camp...

Dating the New Girl
No doubt Eclipse is the new toy in town, and as in High School there is someting to be said for dating the new girl (or getting asked out by the new boy, to be gender neutral here). Having the latest and greatest is nice, but even cars loose their new car smell, and it's just another car after a while
Built in Code Quality Checks
The code quality checks in Eclipse are nice, especially the context sensitive import searches. Much nicer than anything NetBeans has. Because it is integrated into the errors list clicking on it behaves like you would expect it to... it focuses the cursor there, and you can use the next error hot key to get there too. NetBeans+Checkstyle (the closest thing) is not integrated into F12 next error, it only highlights the line green. It also doesn't focus the cursor, and the green highlihgt does weird things when you edit it (like being half there). And it isn't sensitive to edits in the source file, so you have to work from the bottom up usually. I can also only check one file from the IDE at a time, rather than being able to click on the explorerer and check an entire folder at once. This would be somehting I would like to see improved in NetBeans. [See my entry on PMD, it addresses this issue]

But given all of that I prorobly won't be going over to Eclipse 2.1, even with the new ant integration features, why?

Performance is a Red Hearing
The performance thing is over-blown, So Eclipse uses native widgets, the java backen still gets over-loaded and all the widget re-paints still get bogged down in the event displatcher. And I've seen more non-startup slowdowns in Eclipse than in NetBeans, especially when I do somehing little like change a propject preference, sometimes it takes 3 minutes for the chagne to take! That's because it insists on re-compiling all 2000 java classes in the project I have loaded, all of them, from scratch, just because I added a new jar library! Anyone who thinks Eclipse is better performing than NetBeans must be working in small projects, or is micro-benchmarking, or believes anything marketing says.
Swing Editor
The NetBeans Swing Editor blows the one Eclipse has out of the water. Why? Eclipse doesn't have one! Not that I can find anyway. To extend the anti-Swing bias to the tools provided is inexcusable by Eclipse. Swing apps don't all look ugly and perform like crap and now that people are starting to code more rich clients since Web Interfaces are intrincically limited, more and more rich clients will be written.
Ant Integration
Elipse is getting better with bringing in AntView to 2.1, but it still doesn't have the holy grail of ant integration I am looking for: I want to take one (or more targets) and make a toolbar button or keyboard shortcut to execute them. And I want multiple targets for each build file, not just one. And Ant runs noticeable slower in Eclipse than in NetBeans. Incramental compialtion may enable some cool beans stuff but it is not being used for the cannonical builds on the build machine so I want to use the cannonical build while I develop. One thing Eclipse 2.1 has I wish NetBeans had is code compleation for the ant tasks. That's probobly feature #2 that would be nice (better checkstyle suport is #1, with all features not breaking previous funtionality being feature #0).
These last two items will in all likelyhood keep me with NetBeans, despide concerted effort to drive me away or lull me over to something else. If Eclipse could do those better than NetBeans then I would take a nice week-ling test drive of eclipse rather than the day long one I did a couple of weeks ago.

December 10, 2002

PMD for NetBeans/Forte

I think I found the missing piece from my entry about what NetBeans needed. Enter PMD, (the acronym stands for many things. It has what I was looking for: F12 (next error) integration, and intelligent line positioning (meaning I can delete the emtyp constructor and F12 or clicking on the error takes me to the correct line, even thougg it is 3-4 lines higher now). You can even write your own custom rules and plug them into PMD. But no product is perfect, some of the parameters (like how deep it should go before freaking out over deep if statements) don't seem editable, and there is no "use spaces and not tabs" rule. But it's still in beta.

This is a project that should be added to the netbeans master auto-update when it reaches FCS even though it's not a netbeans-owned project, it's that good.

December 20, 2002

Eclipse does Swing!

And I saw it with my own eyes, I even got a screen shot!

eclipseswing.png

Well.... April Fools (in December none the less). I just used the Eclipse 2.1 M4 GTK version and set the GTK theme to metal. So if what was keeping you from using Eclipse was the "Oww My Eyes It's Purple" UI then here you go!

Note however that Eclipse still is missing a good a usable a functional any Swing GUI Editor. What's even funnier is that I can't find one for SWT or JFace either! As long as you only want people to write server side and JSP type then what Eclipse has is fine, but if you want people to write real GUIs with it, tools matter.

January 11, 2003

Users Group Presentation on Ant

For those of you who may be remotely interested, I will be doing a presentation on Ant at the Pikes Peak Java Developers Group in Colorado Springs on Tuesday. Even if you aren't going feel free to peruse the slides and send me comments on them. And be as brutally honest as you desire.

January 16, 2003

Netbeans does SWT

AndI got the screenshot again, look!

netbeansswt.png

Well, April Fools again, at least this time it's a bit closer to the date than last time. What you are seeing is a feature of NetBeans that is not aggressivly documented, if you open up ide.cfg and add a line "-ui com.sun.java.swing.plaf.windows.WindowsLookAndFeel" in there. And BAM no more "owe my eyes it's purple."

One piece of code in there that is not april foolery is the Ant code competion, sceduled for the 4.0 release of netbeans, which is... ummm... going to be relased in June, really! Actually looking at the scedules it looks like it's achieveable, feature freeze in about a month and three to four months of what I like to term "quality time" with the code.

Ray mentioned that he didn't like the "swingy" look of NetBeans, and this does a good job of getting rid of it. The same option is available in NetBeans 3.x as well. You are not limited to Metal or Windows, there are other look and feel options such as Kunststoff and Metouia. But since the client I am writing is supposed to look best in Windows, I use the Windows look and feel so the GUI designer uses it by default.

January 20, 2003

PMD/NetBeans config

My little nit on PMD got some notice,

...the "deeply nested if statements rule" can now be configured to trigger only after hitting a certain depth:
http://pmd.sourceforge.net/xref/net/sourceforge/pmd /rules/AvoidDeeplyNestedIfStmtsRule.html
It's a bit of a pain to configure, since you have to edit the rulesets/design.xml file and change the "problemDepth" property, but, anyhow, it works :-)

Well, it works for stand alone running, but inside of netbeans it is not configurable...

pmdconfig.png

That cell in the table is un-editable, so I cannot change the depth. It's sitting there, taunting me and laughing at me! (OK, maybe not, I should reduce the caffine intake and get some more sleep). It's really funny it tells you what the optuion is but it won't let you chagne it. I've even tried looking for the pmd module configurations and for those rules.xml files but i cannot find them for the life of me. So I just don't care about that rull and throw it out.

However, the ant task looks to be editable (at least according to t he docs), so it is integratable to a build process easier. I could just create an at task shortcut to run it, and we can keep the rules files in the source control tree, so we get consistent results.

January 22, 2003

NetBeans 4.0 and Swing Themes

Well, for those of you who are running on non-windows platforms and noticed that my tip about adjusting the look and feel won't (legally) work on linux, enter the Netbeans Themes feature "Ouch my eyes it's purple" not bad enough for you? How about "Run for the Hills it's EarthTones!"

nbtheme.PNG

The themes page describes how to do it, but the Readers Digest version is to drop an appropriately formatted themes.xml file into $HOME/.netbeans/dev/system/. It's not perfect, as you can see the window titles in the embeded windows don't catch the theme, they still got the "ouch it's purple" look to it. And this is currently living in the dev tree, so who knows if the code will make it into the "Real" 4.0 fork. Time will tell.

January 23, 2003

NetBeans listens

It looks like one of my previous issues about NetBeans is getting some resolution, that of a bad attitude about bugs, at least in this anectotal case.

I posted a feature request for NetBeans 4.0 (Issue #29467) to add code comletion to Ant Build scripts. I saw that they added it for XSLTs so how much more difficult can the stock Ant 1.5 tasks be? It took about a month from open to working code in the 4.0 dev codeline. It seems to work in the limited bases I have tested it in. I won't use it for day to day work because I have an alergic reaction to beta-quality code I can't or lack the time to get inside of and fix easily.

Granted, if I got requests for changes like some people have I might have a bad attitude about "community" requested features too. And I am seing some more responsibility taken WRT quality and releases. NetBeans 3.4.1 is about a month late. Why? There were several bad bugs identified in teh release candidates that were put out that were deem worthy of stopping work and fixing. One of the decisions in software development is deciding that whether or not it's fit for public consumption as a release. Depending on the scale of the use the threshold of bugginess moves, but it looks like NetBeans is taking the road less traveled and saying "Too buggy, the release date be damned!" rather than releaseing a 3.4.2, then a 3.4.3, etc. etc. Not that I've had any personal experiences with that kind of a release schemdule ;).

January 30, 2003

JUnit Exception Handling

Gherhard Froehlich was wondering if there was a better way to do positive JUnit exception testing than something like this:

public void testAddService() {
    try {
        setUp();
        TRACER.trace("--- Testing addService() ---");
        ssgConnectorProvisioning.addService(serviceData);
        TRACER.trace("--- End of test ---", "\n");
    } catch (Exception e) {
        if(e instanceof SSGConnectorException) {
           TRACER.exception("Test OK, because Exception was controlled", e);
        } else {
           TRACER.exception(e);
           fail(e.getMessage());
        }
    }
}

There is, the thing to do is to take advantage of the fact that java will only use one exception block, and it will match the first one that is an assignable class of the exception, so you could do this...

public void testAddService() {
    try {
        setUp();
        TRACER.trace("--- Testing addService() ---");
        ssgConnectorProvisioning.addService(serviceData);
        TRACER.trace("--- End of test ---", "\n");
    } catch (SSGConnectorException sce) {
        TRACER.exception("Test OK, because Exception was controlled", e);
    } catch (Exception e) {
        TRACER.exception(e);
        fail(e.getMessage());
    }
}

Let's hope he get's this via a Moveable Type pingback. (I've wanted to see if I have it working or not).

Update: I was kind of myoptic when I looked at the post Gherhard had and realized it was missing something this morning. Charles Miller also noticed it last night: the test should fail if no exception is thrown. steve tried to trim it down to a single catch:

public void testAddService() throws Exception{
    try {
        TRACER.trace("--- Testing addService() ---");
        ssgConnectorProvisioning.addService(serviceData);
        TRACER.trace("--- End of test ---", "\n");
    } catch (SSGConnectorException sce) {
        TRACER.exception("Test OK, because Exception was controlled", e);
    }

fail("We expected a SSGConnectorException");
}


Except in this case the test will fail if the exception is throw! (a false failure). And this also assumes SSGConnectiorException is the only exception thrown. If your tests are written so that only one test is done per test method (a good practice IMHO) you could fix this by putting a return statement in the catch block or moving the fail inside of the try block. Otherwise (such as cases where the exception is just a set up for the real test) you will need two fail statements or catch statements or continue the test in the catch block.

Java String Tricks

Raible:

if (request.getParameter("checkbox") != null &&
request.getParameter("checkbox").equals("true"))

With StringUtils.equals(String, String), you get a little less coding:

if (StringUtils.equals(
request.getParameter("checkbox"), "true"))

If you're using Struts or some other library that already depends on commons-lang, why wouldn't you use it? Possibly performance reasons, but I doubt it causes much of a hit.

Actually, the latter implementation will perform better. It has half the hash lookups and HotSpot can inline the method invocation. [ crazybob ]

Actually, even easier than that....
 if ("true".equals(request.getParameter("checkbox")))
The string class already does the null check inside of the equals call and requires no exteranl library. I got this from an old C trick where whenever you are comparing somethingto null you put the null on the left side. If you accidentally type an assignment then the compiler will crash because a constant is not a valid LValue for an assignment.

February 4, 2003

SWT Claims: Show me the money

Yesterday Jon Lipsky posted a nice real world comparison of Swing v.s. SWT. A Sun emplyee also had a rather lenghty comparison It looks like people are starting to verify some of SWTs high claims.

One of the biggest problems I have with SWT is that the implementation is not cross platform, but is a sperate undertaking for each platform. This leads to wildly differnt user experiences! The applicaiton I am baseing this statement is Eclipse 2.1 M4 build, under both Windows 2000 and Redhat 8 with the GTK build. The first thing I have to say is that the performance and user responsiveness is so different it's like I am using two differnt applicaitons. On Linux doing multiple ctl+clicks on the source tree takes about 2 second per click for eclipse to repsond to. I can get way ahead of the appplcation, and this leads to ghost un-selections because SWT gets confused. And then a tree update from a mass "organize imports" has massive flashing on the tree. Blech! But on windows it responds just fine. But both platforms still freeze updates to the GUI when doing large operaitons, like compiling the 1023 in my current project when I change one seemingly innocent preference about code quality checks. (As an aside, responsiveness is so importaint that Sun dedicated a entire chapter to it in their Java Look and Feel: Advanced Topics book.)

Another area is that by using the native widgets you immediately upen yourself up to inherent differences of user experience. Like adding jar files to the extrnal library list: on Linux you get a tree control where you can do multiple selections across directories. Windows gives you the standard one directory look. And on windows I can click a column top to get that column to re-sort automatically. Not so on linux, you got to use some wierd triangle menu to change the sort. Stuff like this is why a look and feel that is consistant across platforms is so good. If you don't need to behave the same across platforms then why aren't you writing it with kylix or C#? You get all the native widget goodness you need out of that. If you're going to whine about native performance use native coode then!

And then there is the unproven marketing hype, such as this gem:

The real question isn't about what results expert programmers can get using Swing vs. SWT, but rather what results *average* programmers will get using Swing vs. SWT. In this light, Swing doesn't compare to SWT. [ a comment on jason]

The though of threading your own event queue and disposing of your own object is going to make the *average* java programmer run away in fear. And then manageing all of the paltform specific GUI nuances is going to eat up whatever time they may have saveed assuming they have saved any. Since the person who wrote this is a vendor for an unreleased SWT GUI Builder the perhaps he will be able to show me the money. Then we can judge for ourselves when the product is released. It's got some stiff competition with existing mature tools such as the GUI builder in NetBeans, it'a like codeing a GUI in visual basic, except for the part where you write the visual basic, which is to say it's nothing like visual basic, but I digress.

February 13, 2003

Where's the $$ in Java

Yesterday while browsing around a new weblog I found I came across this statement/question. I must admit I have a similar question. What areas of java pay more or are in more demand? And I wonder that not in the traditional role (architect/VP/Sr Developer/Jr Developer) type thing, but in a specialized knowledge type thing. Crowbar seems to indicate that developers who develop Swing apps are paid less just because of that skill. I certianly hope not since I've been kind of backed into that role through chance, but fortunately the stuff I did is provable magic and not simple VB form builder stuff. Another local guy got loads of contract work just because he let his contract handler know he was playing around with web services. It's not like he only knew how to spell "Whisdel," he actullay had some good knowledge to back it up, but sometimes it makes wonder if Buzzword Bingo is the way to job security. That and the experience we had with some (not all) of the contractors we used to use proved that just because you can monkey around with J2EE middleware doesn't mean you are worth one tenth of the money that is spent on you. So I throw this question out to the blogshpere... Where's the $$ in Java at?

February 21, 2003

JTree Woes (or why src.jar is a ture gift)

Nothing is worse than inexplicable behavior. Obscure behavior is close, but decidedly better.

So I've got this bug in my GUI code relating to changing names in a JTree, basically the structure of the JTree stays the same but the length of one of the names of one of the nodes expands significantly at times. The problem is that the new text is not displayed! (or actually, only 4 pixes of the new text is displayed, for another obscure reason).

My natural inclination is to blame my own code, so I dig into the debugger and stop it durring a swing rendering of the tree (two moniters would sure be nice for this). The first rendeering is perfect. The preferred size on the second (larger) rendering is also perfect. WTF? So after a few failed attempts to move stuff around I think to look at the rendering Graphics object, and lo and behold the clip is set to the first rendering size! This has me really confused, becuse I never have to handle passing around the Graphics object and I have become used to trusting that the rigght clipping is set up (that's a magical black box labeled "Efficient dirty region rendering" in my world). So then I (properly) conclude the causal factor is outside my code. Too bad, 'cause I still have to fix it.

This is where I am truely thankful that Sun ships most of the Java code that comes with the JDK in src.zip. I can crack open the implementation classes and look around and find what the real culprit is: JTree is caching the preferred sizes of the tree nodes when it is drawing it, and it's called an optimization. When you are using straight GDM code on a 200Mhx Pentium MMX running Windows 95 I suppose that optimizations like that make sense, but that is, like, so last millenia.

The problem is that this is a faulty optimization, because it clearly isn't keeping up to date or allowing for a hook to change the size of the widgets. Fourtionlatly my diging around also gives me anoter clue: when JTree.setLargeModel is set to true these cachings are ignored. I've always wondered what that property did! But the documentation is so... vauge. It was a real.... bummer. Six hours of head scratching work and the A-Ha moment comes and all I have to show for it is one measaly line of code.

There is still one last mystery in this though: this fix requires largeModel to be true and for rowHeight to be set to a non-zero value. Using the Windows Look And Feel sets this row height automatically, but not for Swing, and for the life of me I cannot find that code in the Windows Look and Feel code. So I just set the value to a previously rendered value when I am done with my data load thread, and it's all good on Linux. So a total of three lines changed (the second change was quite long, and I had to wrap it onto the next line).

February 26, 2003

NetBeans.org Want You to Click My Links!

Download NetBeans!

NetBeans is embarking on a community based marketing push as of late, as seen on their Move the needle! page. Actually it started, like, nearly a month ago. I was going to do this a month ago, but I'm actually starting to do some interesting stuff at work. But do me a favor, click on my main blog page and click on the netbeans link.

So what's in it for you if you click the link above? Nothing, unless you actually download netbeans and use it. What's in it for me? Probably a book I won't read and will just sit on my bookself in my cube looking importiant. It's not like I'm selling out, anyone who has been reading my blog knows that currently NetBeans is my IDE of choice, and that I have looked elsewhere *cough*eclipse*cough*, and NetBeans is currently the pair of sneakers that fit most comfortably.

Also, I am going on a short vacation tomorrow. I can tell this because my mind has basically already turned off, I'm even going to leave my laptop at home and jsut bring along my game boy. Once I get back (or sooner, it's that or work) and my brain turns on I'm going to add links for the other tools I actually use.

March 5, 2003

Java Language Triva...

Here's an interesting snippet.....

String s = null;
boolean valid = s instanceof Object;

So is valid true or is valid false? The answer may suprise you: valid will be false. Why? Well, static type analysis may be tempting to use, and the fact that every reference type must be an Object is another tempting conclusion as well. But nether of these can be used because of the defniniton of the null object reference. C++ doesn't really have this, becuase the convention is to use 0 or NULL to "null out" a pointer. But when you build a construct into a languate you have to be explicit.

Java defines two unique properties for null, first that it is castable to any other type. You probobly knew that already. But the second unique property is that any evaluation of the instanceof operator with a null object will result in a false result. So the null object can be cast to any object but it has no type. Meditate on that one for a while...

This isn't totally useless trivia either, I use it all the time to eliminate redundant null pointer checks. Cosinder this code snippet...

public void tweakElement(org.w3c.dom.Node n) {
    if (n instanceof org.w3c.dom.Element) {
        // do random tweaking here
    }
}

What if the user calls tweakElement(null)? How will it behave then? Well, the same thing as if they pass a org.w3c.dom.Attribute: it's a no-op. Since the null check is built into the instanceof check I can go along in the tweaking code block assuming that not only do I have an Element, but that I have a non-null object as well. It's not a substitute for != null, but if you are checking class at the same time it's already done for you.

March 8, 2003

Use The Source, Duke!

As a continuation from my Problems with JTree I cam a cross another gem for the Obscure Java Nuances list: How do you override an existing keybinding on JTable to make it do something else?

Here's the real-world use case, I'm createig a frame that shows a long list of tabular data that the user may want to drill down on to get more specific info that what is available in the table columns, you know, like multi-paragraph data? So I gout the double and right click menu stuff wokring and while playing with it I came to the conclusing that a user using the keyboard to navigate the table may want to uset the enter key to bring up the dialog. Very standard situation UI... use the keyboard to navigate to the widget in question and press the enter key to interact with it. Simple enough?

So the obvious first course of action, use the NetBeans GUI editor to listen to keyboard events on the table and act when I see the enter key. Should be a 2 minut hack right? Worng. The listener will never see the Enter key typed action because of Input Map, Action Map, and the standard key assignments for JTable. In the spreadsheet work that JTable is based off of enter means "go down one row" rather than "do the default action." Which is all fine and dandy except for the fact that like any good UI I am perverting teh default compnent sets for my own purposes.

InputMap and ActionMap aren't a problem for me, I've used them before and it's merely a hassle writing a few more lines of code. Add the action, bind it to to the VK_ENTER KeyStroke, compile run and... WTF!? It's still going to the next row!? Drop in some code, so I see what I am overriding in the Input map, nothing, look to see what other actions are mapped in the InputMap, nothing at all. A quick internet search using the Google(tm) search engine service reveals that people are more interest in doing the oposite of what I am doing. At this point I heard a Alec Guinness whisper to me "Use the Source"

It never ceases to amaze me how when you are looking for the question to a very specific answer how much more information you can get from looking at source code for something that you may not understand than from reading all of the documentation in the world. The reason for this I assume is that no one can ever document every possible question a developer may ever have. However when you do something non-standard that should be a clue that you should document it.

Deep in the bowels of the basic plaf implemenation of the JTable UI in a method that hasn't been used since Java 1.2.2 I find the answer in a comment...

// We register all actions using ANCESTOR_OF_FOCUSED_COMPONENT
// which means that we might perform the appropriate action
// in the table and then forward it to the editor if the editor
// had focus. Make sure this doesn't happen by checking our
// InputMaps.

It turns out that all of the default key bindings for a JTable are stored in the InputMap for when it is an ancestor component and not the focused compnent. On deeper reflection it makes sense when you think of the cell editors and such. But without that information it is difficut, ney impossible to make that logical leap since it is at it's core a design decision.

So where is this documented? In the JavaDocs? No. In the JTable tutorials? No. In the default key bindings for JTable? Even though it would make sense no. Thank goodness that Java ships the source to exposed classes, or else I never would have made the leap. When all else fails... Use the Source, Duke.

May 9, 2003

Independent Developers and the JCP

Share Me Technolgies recently wondered How Many Independent Developers Join JCP? Well, I used to be a member, back before I got married, but not any more. Here's my experience:

First, as an individual you don't have to pony up $2000 to $5000 if you want to join as an individual. It's something on the order of $100 (this was back in Y2K, so things may have changed). But they will ask to make sure you are truly joining as an individual and not for your company as a way to save money. That's one of the biggest reasons it's not publicly listed. And it's not like a magazine subscription, don't forget to renew or cancel (unless you want some cratchety lady calling you up and berating you when you say "oh I thought I'de just let it expire").

What do you get when you pay? First you get earlier access to some of the specs that come outt of some of the JSRs, but it's not like a public draft, these are under NDA so you can't tell anyone or do aonything public with them. These are the community drafts. And that's all you get ... unless you get involved in a JSR.

JSRs are where the real action occurs. The loweset level of JSR involvement (that can be termed involvement) is as a member of the expert group. Basically all that does is it means you get even earlier access to the JSR drafts (and are under an even tighter NDA for them) and you get to talk on a mailing list to the spec lead who is responsible for delivering the spec (they usually write it as well). Getting in on al call for experts can be pathetically easy or incredably difficult, it depends on the spec lead. And then there is no process check or balance immediatly requiring them to listen to the experts in the group, so some groups have more sway in the spec and some have essentially none. The only real check and balance is political pressure ant the final approval vote.

Beyond that unless you are willing to pony up massive ammounts of time there really isn't much more for independent developers in the JCP. That's why I just let my membership expire.

June 14, 2003

Swiss Army IDE Problem

The approriately names BileBlog was spewing some bile about IDEs lately...

There's also the gui editor issue. I despise it, and will gleefully delete it from my plugins dir once it shows up there. It's such a shame that market forces demand junk like this. To be fair though, I have some sympathy to it being added as a lot of big companies demand bloated shite like this, so it makes sense from a business perspective. Although it's particularly amusing seeing the various comments that have been made about it. A whole bunch of 'well I never use swing but I tried it and blahblah' rubbish. Serious swing developers I suspect are likely to scoff and stick to using their own hand rolled magic. Still, I'm sure java needs yet more ignorant mediocre inexperienced developers dabbling in swing eh? [The BileBlog ]

There's a couple of things I want to address in this little bit. But Wow, in four short days he's spewed a lot of bile that really chaps his hide about java in gerenal. I've probobly got enough for three posts off of this.

Issue #1 : IDE Bloat. Yea, I've noticed this alot lately. All the IDEs need to have some fangleled spangeled tool to do the latest programming fad. Well based on what was said at JavaOne I'de say it's only going to get worse. The 20% that can do without it are probobly using Emacs or TextPad anyway. But if sun wants that other 80% to come over (you know: those other 7 Million developers they want coding in Java instead of VB) They live and breate by and IDEs slick add on tools. And they want it all in the same program.

The type of slick progams they want are stuff like the new Project Rave (and hardcore developers will yawn, principally because it's not for them). Be ready becuase if Sun is serious about those developers they will have to cater to their whims. We're talking about the corperate IT guys who only write software for their department and other such "internal use only" tools that extist because of VB. What's going to happen is that if developing something is not easy they'll put it back on their never ending stadk of stuff to do and work on something else or (more likely) use some other tool.

It's like dating: You'll generally go for what's available and (given a choice) you avoid stuff that's difficult to deal with (or go without). And if it dosen't fulfull your needs you're likely to move on. Sun wants Java to appeal to the lowest common denominator by being flexible, without attachment, and easy!

June 16, 2003

The Follies of IDE Selection by Checklist

Back on the issue of IDE bloat. Sometimes corperations pick IDEs by commitee. And that leads to the check list syndrome. Group A requires Feature A and Groups B, C, D ad infinatum. Add in another common feature of "corperate standards" where development "needs" to standardize on one IDE. So what usually winds up getting picked is the IDE that can meet the biggest check list. In the interest of not losing revenue the IDE developers try to fill all of thoese check list items as is inhumanely possible. But the problem is that the IDEs become a Jack of all Trades, and are sadly the master of none. More often than not what winds up getting picking is an IDE that no one is happy with. But it was done in a very egalitarian fashion, meaning that everyone's equally screwed in that case.

Situations like these remind me of the early days at my current job. We initally had some big fuzzy discussions about coding practices and build environments and one of the things that came up was IDEs. One person with alot of clout (that immediatly eliminates me) insisted we all use Visual Cafe because it integrated with WebLogic. At the job I had just before this one I tried to use what was a current copy of Cafe for a week. I had liked it before, but then again this was after not using it for two years while I was experementing with Linux in College (don't we all experement with stuff in college? Since I didn't experement with drugs I had to experement with something...). Anyway, I quit rather quickly because of it's horrible JDK 1.2 integration. That, and it crashed alot. I voluntered that information but it was freely ignored. Weblogic Integration was the most importaint thing (perforce integration was second) and thus the standard was Cafe (I didn't use it, I stuck with NetBeans).

This was before WebGain crashed and burned. In the year since I had abandonded it Cafe hadn't seen any major changes (despite the new major version number since WebGain bought it). A year and half later I walk into a phone confrenece where he's whining about Cafe crashing again and about what a piece of crap it was. I had to have a chuckle to myself because that's exactly what I had told him over a year earlier. It was still a piece of crap, but the piece of crap integrated with WLS.

Moral of the story? Trust experience over a marketing checklist.

June 17, 2003

GUI Design Tools are Not Just for the Weak

Now on issue #2 that I see with monsuier BileBlog's rant on IDEs. The most relevent poriton of that previous quote is as follows.

Serious swing developers I suspect are likely to scoff [at IDEA's GUI designer tool] and stick to using their own hand rolled