Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Thursday, May 03, 2007

Comment On This

So the other day I'm looking over some code, and I see this... (slightly paraphrased to protect the innocent -- in the original, the declaration and the getter were, of course, separated.)


/**
* The name of the user
*/
private String m_userName;

/**
* @return The name of the user
*/
public String getUserName() {
return m_userName;
}

And I thought, "I really hope some of that was generated by the editor"

And then I thought, "This is why other languages make fun of Java"

And I finally ended up with, "Most of what beginning programmers are taught about comments is useless". At least that was true when I was in school.

For the moment, I'll put aside the Java issue, to talk more generally about comments.

First though -- we're agreed the example is absurd, right? In that it repeats that the user name is, in fact, the user name five times. Which is at least four more than strictly necessary (I realize that Java more or less forces some of this duplication).

I realize that this is hardly the worst coding sin you can commit, but when I look at code like that I do think that either the programmer isn't quite sure which parts of his code are most important or that the person is rigidly following an overly formal standard. Neither of which is all that flattering.

About 95% of the time, it seems like you either get no comments, or the kind of useless comments in the example. Given the choice, I'd rather have no comments -- it's less distracting, and you can see more code at once.

However, you can do comments effectively. Here's what I think, which should not ever be confused with what I actually do.


  • The best commenting is clear and accurate names for your variables, functions, and classes.


  • The "No Duplication" rule applies to comments at least as much as it does to code.


  • Possibly more, since no compiler is ever going to catch if your comments fall out of sync with your code.


  • Therefore, under normal circumstances, comments should avoid repeating what the code does.


  • However, limitations on input or output values that are not apparent from the code should be included in comments. If the user name was guaranteed to be under ten characters because of the underlying database, that would be a useful comment.


  • Rationales for choosing a particular implementation are often good comments, as is the code's place within the larger program.


  • If you find yourself commenting inline within a long method to explain what the next section does, odds are you'd be better of extracting that to a well-named method and skipping the comment.


  • There is a cost to commenting -- it takes time to do well, and it can be distracting. It also limits the amount of code you can read at once.


  • The most obvious exception to all of the above is when you are in a situation where people will read your comments without ready access to the source code. Writing an API or a framework, for example. In that case, most of the issue about duplication doesn't apply and you need to be descriptive for the benefit of users who will only see your JavaDoc or RDoc.


  • However, none of that excuses writing a one line comment for getUserName().

Wednesday, March 21, 2007

Rubies in My Coffee

Now two of the big Java IDE's are promoting Ruby language tools as a big thing. IntelliJ has a plugin in early beta, and NetBeans is also making a big deal of their new early beta support. Eclipse has had a Ruby/Rails plugin for about a year or so.

This is weird, weird, weird, that suddenly all the Java tools would feel the need to grow into somewhat ill-fitting Ruby IDE's (Eclipse has always styled itself as more of a meta-IDE, so that's a little less strange). But do we really need all these Windows Ruby IDE's to be attached to big, memory hogging, Java tools. (And in IntelliJ's case, I say that with love...)

I've played with all three now -- I've used Eclipse for Windows-side Ruby editing for a while, and for the last few days I've been going back and forth between IntelliJ and NetBeans checking them out on an existing Rails project. None of the three are going to make me ditch TextMate yet (although I'd say the big tools all have somewhat more developed project support that TextMate).

IntelliJ's plugin really strikes me as Not Ready Yet. For one thing, there's no syntax checking on .rhtml files, which is a big problem. Also, there's a cool Rails project view, that associates the .rhtml files with the appropriate controller method, but there didn't seem to be an obvious way to get to partial .rhtml files. Another minor frustration is that the Ruby syntax layout is not customizable yet, the way the Java one is. It's even hard to keep a separate setup so that Ruby files only have a two character indent. (And there's a good sociology of programmers paper, on why Ruby is canonically a two character indent, not four).

This seems like a good place to point out that I still haven't spent all that much time with any of the new tools, so it's entirely possible I just missed something. For instance, even though the IntelliJ docs say there are Live Templates for Ruby, my installation didn't seem to have them.

There's some nice stuff in the IntelliJ tool -- all the ctrl-N navigation works on Ruby classes and methods. It's very easy to run arbitrary Rake tasks from the UI (although they seem to run kind of slowly) I don't think syntax completion is there yet, but it does syntax check .rb files on the fly I'd like to see this one a few revs down the line.

The NetBeans tool is in their beta for version 6 (you have to download the tool, then grab Ruby support via the update center). I was kind of amazed to be liking this because I fled NetBeans in a huff around version 3 and haven't had any success in trying it since. The syntax coloring and layout seems to be a bit stronger. It appears to be using JRuby not just for internal parsing, but also as the default external engine for running, say, WEBrick. Which makes everything feel a little slow. There is some syntax-completion -- I found it a little hit-and-miss in terms of getting useful alternatives. The project view is nice -- it flattens out all the /app subdirectories, but I couldn't see an obvious way to run arbitrary rake tasks or the test suite. Although there is a keyboard shortcut to run an individual file, and if you try it in a view page, it attempts to open that action in a browser. My app has a slightly nonstandard route configuration, though, so it didn't quite work for me.

I also had some stability problems, mostly with trying to run the server from NetBeans, it either hung or took a really long time to load. Development on this seems to be progressing rapidly -- they are releasing new versions much more quickly than IntelliJ, so all these things could be fixed by Thursday.

Right now, NetBeans would be my pick of the three if I couldn't use TextMate. I'm as surprised as anybody by that conclusion, but it felt pretty good as I was using it. Adding easy test hooks would help. All three tools are still under development (RDT for Eclipse just released a new version, and RadRails just passed to a new owner with new development promised). So, watch this space, I guess.

Update: Looks like NetBeans has a bug in reformatting code -- it kind of messed up some of my source files. Nothing permanent, just kept indenting and not noting the end to outdent so the file kept creeping to the right.

Sunday, February 25, 2007

GWT part 3 and 4

Sorry for not mentioning this earlier, but part three of the GWT series is now up on the IBM site at:

http://www-128.ibm.com/developerworks/opensource/library/os-ad-gwt3/

This one is about remote procedure calls, and I'm pleased with how it turned out.

I just got the proofs for the fourth and final article in this series, about deployment. I expect it to be online Tuesday, Feb 27th at:

http://www-128.ibm.com/developerworks/opensource/library/os-ad-gwt4/

Friday, February 02, 2007

Clearing The Decks

A collection of small things, half-finished posts, and pure whatnot that hopefully will lead to more posts in the future:

  • Got my first Amazon affiliate statement with no less than $1.55 heading my way. Thanks to the person who clicked through...

  • There's a new sidebar, for small links, via del.icio.us. The sidebar has it's own RSS feed, on the off chance somebody is interested. UPDATE: It doesn't appear to work on Safari, which is a problem... Weird, because I did the preview using Safari, and it showed up fine, but not in the actual blog. Until I figure that out, Safari users can still click on the RSS icon and see the items.

  • I had a half-finished post on the iPhone that got buried by the trillions of electrons poured on this story. So, I'll distill it to this: that was one cool demo.

  • I also had a half-finished post on using XML as a scripting language, as in Ant scripts. Distilled: Don't do it. It's hard to read and nigh impossible to maintain. The thing I most like about Groovy is that it lets you actually script an Ant target. Although I think the JRuby/Rake combo is going to be pretty powerful here.

  • Hey, another half-finished post. This one was about the lack of list or hash literals in Java. Which bothers me just about every day that I work with Java.

Decks now cleared. Hoping to get some new content here soon.

Thursday, January 25, 2007

GWT Article Now Online, Part Two

The second part of my IBM Developerworks series on Google Web Toolkit is now online at http://www-128.ibm.com/developerworks/library/os-ad-gwt2/. This one focuses mostly on the Derby database, and features a really quick and dirty database-to-Java conversion tool.

Enjoy.

Friday, December 08, 2006

GWT Article Now Online

I'm happy to announce that Part One of my four part series on using Google Web Toolkit is now available at: http://www-128.ibm.com/developerworks/opensource/library/os-ad-gwt1/



This part focuses on creating a GUI front-end using GWT. In case you wonder about the lead time on these things, it was originally written in August, and slightly updated right before it was published.



I think that the future part of the series will appear monthly. The next one is about using the Derby database as your back-end.



I'm pleased with how the article turned out, although I sort of wish I had taken the time to polish the look of the sample a bit -- that's one ugly Web 2.0 application. On the other hand, there's only a limited number of space available in this article (2000 words, and I was already over), and any graphical enhancement needs to be put in code and explained. So it's a tradeoff.



Hope you like it.

Thursday, September 07, 2006

I/O, I/O, It's Off To Work I Go

Welcome to our program, Things I Agree With Totally And Wish I Had Said First. Our hero tonight is Tim Ottinger with his hit, "Frameworks are for the Impatient". It seems Ottinger is puzzled by a library he's trying to use..

Look, this framework is not the game Myst. I did not install this thing so that I could amuse myself for days by running around the file system trying to figure out what it is about...

In the Java world... [E]ven opening and reading a file is cause to go google the library one more time. Heaven forbid you have to manipulate dates or the like. These are small things, and should be very easy.... You shouldn't have to crack open a half-dozen US$50.00 books.

One point of "obvious" is probably worth one hundred points of "clever".
In the immortal words of Arnold Horshack, "Right you are, Mr. Kotter". Hmm. That sounds better if you imagine it in a Horshack voice. Doesn't look like much in print...

The Java io library is a particular nemesis of mine. I've been using it for what, just under a decade now, and the only way I was able to stop looking up the API every other week was to write a utility class that had an API that was actually useful (you know, obscure methods like copyFile, readlines, writeToFile...).

The io library may actually be the purest example of the Java school of OO design, marked by the principles like:
  1. Use an abstraction (streams) that looks interesting on paper, but that nobody ever uses. Ignore the abstraction (files) that is already established. When that doesn't work, add a completely new abstraction (readers/writers) that's completely non-interoperable with the first one.

  2. Make sure the user has to type a lot of words to get anything done.

  3. Make it just as easy to do obscure, complicated things as it is to do typical things, even if this means making it harder to do normal tasks. Doesn't everybody want to randomly access binary files just as often as write some text? (Actually, there are obscure things in the API that are much easier than say, iterating over the lines in a text file).

Don't even get me started on the nio package. Really, don't. I couldn't explain it on a bet.

Sigh. Java is too easy a target sometimes.

Monday, September 04, 2006

Web Apps and Language Wars

I wasn't planning on posting about either web apps or linking to Joel Spolsky again, but this language wars post is just too interesting to pass up. Besides, a jillion people have already commented on this, so what's a jillion and one?

Spolsky is riffing on what language or platform you should use for an enterprise web project. He makes a few points (note, I'm paraphrasing him here -- these are his points, not mine):

  1. There are 3 1/2 platforms that are proven to work in the enterprise web app space (Java, C#, PHP, and maybe Python.

  2. Within that group, there's no difference large enough to offset expertise, so pick the one that you know the best.

  3. Rails is not part of that group. Even though it's fun.
I suspect you know which one of those three points has gotten the most attention. Obviously the Rails people are ticked off, which I think is a combination of Spolsky taking his point too far, and Rails partisans taking his point even farther.

Look, I love Rails as much as a person can love a framework. I wish I had been smart enough to put all the pieces together myself (another post for another time...). My Rails experience has been uniformly positive. Nevertheless, if I wanted to pitch Rails for a mission-critical enterprise application, I would expect to have to justify the choice. Using Rails is still a risk, relative to the others, it's still newer, people are still trying to work out optimal deployment, it still doesn't have the library support the others have. Where I would differ from what Spolsky is saying is that I think it might be a justifiable risk even in a mission-critical enterprise application.

Scaling and library support is not the only source of risk. There's also the risk that your code will get bogged down in a huge ball of intertangled display and logic code (PHP). Or the risk that your developer time will be slowed down enough that it delays deployment (Java). Or the risk of deploying in a system that is owned by Microsoft (guess...). Choosing one of the "nobody ever got fired for choosing X" languages is a safer choice. Which doesn't always make it the best choice.

(And yes, I know that Spolsky ends his essay by mentioning that one of his apps is written in a custom in-house version of VBScript. Red herring. He's not saying that Java, C#, and PHP are the only languages to use ever, just that they are the only languages that currently have the ecological support to be guaranteed safe in a "death before failure" scenario.)

I'd argue the following corollary: I agree that, all else being equal, expertise trumps any difference between these platforms. That's a little circular, of course, because how will you get experience without using a tool? (I know about apprenticeship as a junior member on a larger project, but it's not always feasible.) Almost every project or team spins off low-level applications -- bug trackers, vacation trackers, internal chat rooms. Things that are not high-priority, but are still useful. So, when putting those together, I think it's a good idea to range far and wide and try new things that might pay off in a future project (I almost wrote that you "have the right, no, the duty" to do that, but I thought that might be a little over the top). Me, I'm going to try out Python/Django next chance I get...

Friday, September 01, 2006

Java Closures

Here's a nice item being proposed for Java 1.7: closures in Java. On behalf of all those people who actually do create entire classes just to be able to use map and other functional styles in Java, may I say, please, please, please put this in Java. (This seems a good place to link to Joel Spolsky's wonderful programming fable "Can Your Programming Language Do This").

The proposed syntax looks like this:

public static void main(String[] args) {
int plus2(int x) { return x+2; }
int(int) plus2b = plus2;
System.out.println(plus2b(2));
}
Line one of that syntax creates a closure object that takes and returns an int using what is basically Java method syntax. Line two assigns that closure to another variable using the syntax int(int) to specify the types of the signature. Line three shows that you can call the closure object as you'd expect, although notice that, unlike most Java calls, there's no receiver object specified, and it's not using an implicit this -- it's purely a function.

The proposal also specifies an alternate syntax for creating short closure objects -- I don't like this one as much:

int(int) plus2b = (int x) : x+2;

This is all nice, and I know I'd use it pretty much daily. Unfortunately, though, I wonder if the strict typing will wind up making the closures less useful than, say, Ruby blocks. I assume there'd be some way to tie this into the generics system so that methods that might take blocks with different type signatures would be able to convince the compiler that everything is okay. Let's see... if I wanted to do a new method of List collect, it would be something like this.
public List<V> collect(V(T) closure) {
List
<V> result = new ArrayList<V>();
for (T obj : iterator()) {
result.add(closure(obj))
}
return result;
}

int plus2(int x) { return x+2 };
List fred = list.collect(plus2);
Is that right? If so, that's certainly a lot better than we have now.

I have three quibbles and an enhancement.

Quibble 1: Like generics, what looks nice for int(int) is going to look a lot less pleasant when the signature is, say, OrderLineItem(Order, Product) or even better List<List<OrderLineItem>>(List<Order>, List<Customer>, List<Product>), which I could easily see as a real world case.

Quibble 2: Do do this right would require including support for closures up and down the standard library -- all through the util classes, all through SWING, JDBC -- there's all sorts of places in the library that would be cleaned up by being able to take closures. I suspect that's unlikely to happen quickly.

Quibble 3: The proposal says "We are also experimenting with generalizing this to support an invocation syntax that interleaves parts of the method name and its arguments, which would allow more general user-defined control structures that look like if, if-else, do-while, and so on." I'm thinking this is more of a Smalltalk or Objective-C style? That would look odd within Java.

What I really want, though is a method literal analogous to a class literal. Something like...

Integer(MyClass) closure = MyClass.someSillyThing.method;
MyClass obj = new MyClass();
Integer x = obj.closure(3);

or even better:

MyClass obj = new MyClass();
Integer(MyClass) closure = obj.someSillyThing.method;
Integer x = closure(3);

And yes, I realize that's basically Python bound and unbound methods. The tricky part in Java is that there might be more than one overloaded method called someSillyThing, and so I'm assuming that whatever closure object I'm creating would be able to get the right one based on the declared type (or, alternately, I suppose, dispatch properly when called). That should be doable, though. And then my Java code can look even more like Python...

Good stuff. I hope something like this gets in.

Thursday, August 31, 2006

Languages I Use

Continuing in the getting to know you kind of vein, I thought I'd ground some of what I say by talking about the three programming languages that have made up the bulk of my professional and hobby work for the past five years or so -- Java, Python, and Ruby.

Java: I've been programming Java since either just before or just after the 1.0 release... can't quite remember at this point. I think I've covered most of the major Java libraries (although I've done very little EJB work). Basically, Java is the station wagon of programming languages. It's not elegant or efficient, but it gets you where your going and you won't offend anybody along the way.

Far and away the best feature of working in Java is the tool support, especially the IDE support. If you're doing something in Java, odds are somebody has done it before and there's an open source .jar file somewhere that will help. Plus, IntellJ IDEA makes working in Java almost as productive on a time-basis as working in a scripting language.

Java is, of course, famously verbose, and there's the constant sense of telling the compiler things that the compiler should already know. (The 1.5 language features improve this somewhat, at the cost of moving some of the verbosity elsewhere). Java's original design goal was basically to get C programmers to do object-oriented stuff without scaring them away, and at that it's a success, but that does lead to oddities like having both basic types and object wrappers for them, and keeping the ridiculous C-style switch statement.

There's also the "Java style" of OO design, enshrined early on by Sun, and followed by many third-party libraries. To oversimplify, there's a lot of design made complicated by the desire to make less common tasks as privileged in the API as more common ones. For example, the need to spell out what are basically boilerplate properties in a web.xml file or a Struts config file. Swing has several features like this, including the event system and say, supporting multiple listeners for a button click.

Python: With Python I suppose you have to start with the whitespace thing, although I know that anybody who actually works in Python is sick of hearing about it. I wrote what I hope was a spirited defense of it in the Jython book, and I'm not going to repeat myself. What I like most about working in Python is the conceptual consistency -- objects are like classes are like modules are like dictionaries. I find that to be a very powerful equation, and it makes Python code more predictable to me. I also think the syntax is very clear and readable. (I particularly like the list comprehension syntax.)

On the down side, although there probably is more Python libraries than Ruby ones floating around (although I'm not as sure of that as I was even a year ago), there's no central repository so they are harder to find. It is true, though, that Python style quirks are more likely to bleed into my programming in other languages than vice-versa -- I write a lot of Java code that really looks like it wants to be written in Python.

Ruby: I actually got into Python, Ruby, and XP at about the same time. I started on Ruby because a number of the early XP gurus were excited about it. And while I know I'm supposed to pick a side or something, I actually like Python and Ruby both quite a bit. There are some particular bits of Ruby syntax that I think are particularly well done, for example the way that accessors are handled. I even like that you can leave parentheses off method calls if the line is unambiguous, although a little of that can go a long way. Blocks make the language very flexible, and very easy to build non-redundant code in.

There are a couple of pieces of Ruby syntax that make me nervous, like the syntactic sugar for hashes as the last argument of a method or the way you don't have to specify that a block is needed in the signature of a method. To be fair, I haven't experienced practical problems with these features yet. Ruby has a lot of syntax sweetener compared to Python, which is sometimes good (elegant Ruby code is very elegant) and sometimes bad (I've had some trouble following Ruby examples if they are very magical). Because Ruby has been the focus of a lot of XP/Agile writers, the testing tools and general XPish support is very good. For a long time, I thought that general library support lagged Python, but that's becoming less true daily. And of course there is also Rails, about which more at another time.