Main

February 01, 2006

The application must be too fast

I would assume that the only reason our NSBCs would create this code is to slow down the application. It's the only logical reason.

public static final String VALUE = "123";
.
.
.
int val = StringConverter.getInt(VALUE);

Where "StringConverter" is a utility class that will check the string for null and convert it to an int if it's a valid int, otherwise return 0. It's a very useful utility if you don't want to have to catch NumberFormatExceptions and do null checks every time you convert strings (like say, user input) to integers.

I blame myself, I kept telling them not to use Integer.parseInt w/o any error checking everywhere.

January 31, 2006

WWANSBCD

After months of complaining about code written by a bunch of not-so-bright-consultants, I've decided to approach the problem differently. Don't just tear my hair out.. sit down and try to reason the solution the way the people who wrote the code must have been thinking.. Put myself in their shoes, so to speak. Here it is.. WWANSBCD[0]


  • Problem:
    Our system has users, users have roles and every now then we like to look at their roles and see them as more than just a bunch of numbers.
    Solution
    Take the list of role ids associated with each user and add role descriptions to the same object. If it's a string it's a role name, if it's an integer, it's a role id. Easy! Correlation? That wasn't specified in requirements.
  • Problem:
    Some roles can only be assigned if other roles are also assigned, in other words, there is some dependency.
    Solution:
    Create a JavaScript that makes sure checkboxes for roles that are dependent on others always stay checked... keep track of them by index in the list in which they're retrieved[1]
  • Problem:
    System design calls for using of business rule objects to validate information entered by the user.
    Solution:
    Create a IsValidString business rule object which checks for null string therefore satisfying the requirement for using a business rule object.
  • Problem:
    System design calls for using descriptive javadoc comments as documentation.
    Solution:
    Copy-paste the same comment all over the place without changing anything
  • Problem:
    System design call for using constant values for often used values.
    Solution:
    Define a constant value for 0. Name it ZERO. Use it in if statements.
  • Problem:
    Presentation code should not use classes from persistence package without going through EJB layer.
    Solution:
    Copy-Paste the code from persistence package into a common package and use it from there.

There's more.. oh is there ever more.

[0] What Would A Not So Bright Consultant Do, what else?
[1] And by all that is holy, don't change the order-by statements on the SQL that retrieves them from the db!

January 26, 2006

To JAXB or not to JAXB

I really like JAXB. If you have to work with xml it makes the marriage of Java and xml a lot easier.. there are some quirks in how the data structures are formed and sometimes it creates an awkward chain of object but that really flows out of how xml is structured.

That said.. there is something that really bothers me about using JAXB. It appears that the ease of JAXB is a little, well.. too handy.

How's that you ask? Well.. when programmers add a compilation of an xml schema to the build file just to have the ability of easily creating an xml document in one utility class.. well that's really a problem. I mean come on.. it's not that hard to create xml in Java, is it? Is it really necessary to generate 30+ datastructures (with every build nonetheless.. what is up with that, not like the schema changes often since it's not even ours) then only use three of them just to avoid writing a few lines of Java? Especially since this is only used in one SOAP call?

So that's what bothers me most about JAXB.. at least today. It's too freaking easy to abuse. Of course, I still wouldn't exchange it for the "old way" of doing large quantities of xml in Java for the world.. but really, it shouldn't be used just because you can.

January 24, 2006

How to make potential hackers happy

Error messages spotted today on a login page (not all at the same time, obviously, just with different tries):

Invalid user name
Invalid password
User account was deleted

I'm sure the developer/designer meant well..

November 16, 2005

When pointless error messages attack

Something that always annoyed me in bc, the ever-handy calculator language present on all unix systems.. all I can ask is why? Why? WHY?


[lyra:~] kasia% bc
bc 1.06
Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 
2+2
4

(interrupt) use quit to exit.
quit
[lyra:~] kasia%

In case it's not self-evident, bc traps ^c and spouts out that stupid message..

(Yes, I know it has nothing to do with Java, but I use my Java category for all programming-related crap)

November 15, 2005

When "technical" writers don't do their homework

As evidenced in Information Week a few days ago where Aaron Ricadelo (whoever he is) gushed all about ajax and php being the newest and greatest:

Scripting languages such as Ajax and PHP are challenging Java and making it easier to quickly develop and prototype Web-services app

How embarrassing for him.. ajax is not a scripting language and XML consumption is hardly specific to PHP, hence, ajax technology can be used with any server-side language. Seriously, do some research, don't just regurgitate press releases.

I wonder how many middle managers read that and sent out "We gotta get us some of that ajax-php technology!" emails without realizing they might already be using it with Java or .net.

November 08, 2005

The brain works in strange ways

Either that or sometimes it just doesn't work.. from bad-ideas-in-our-code selection of the day:

Static constant to represent the SQL string "COUNT(*)".. which in itself while silly (not like we need to centralize that in case the sql changes) isn't necessarily a "what the hell" type of thing.. but when you add that the same class file, written by the same programmer, hard codes the number of results returned by a query.. well, that makes you wonder about their brain patterns, doesn't it?

September 28, 2005

The most useless unit test ever

This is an actual unit test I ran into today.. I've made minor modifications to the code just to make it appear less like taken straight out of some application (although it is) and perhaps make it more fun to read.. but other than that.. the test is exactly as I found it...

So what's wrong with it? If you have to ask you'll never understand... or at least not before you program for a few more years, go off.. code something.

But it has comments! Yes.. yes it does. A lot of them and every single one utterly useless.

How did I run into this gem? It continuously fails on my daily unit test run, I finally decided to investigate why.. and well, the reason is obvious. It checks for a hardcoded value that was likely deleted long time ago.. as you know, test databases get wiped on regular basis and stuff.

It's obviously not finished! You say.. actually hasn't been touched in ages in an actively developed project.. so I have to assume it is meant to be this way.

Why am I not posting this to daily wtf? I'm not sure it's actually submission worthy.. It's just well.. so.. oh well, that, er, yah.

So what does it actually test? As far as I can tell.. JDBC works like a charm, good job Sun!

August 01, 2005

Ah, those gotos..

Nothing riles up programmers more than a good "goto" discussion as evidenced by today's daily WTF [0]. I sometimes use labels in Java to simplify code.. every now and then that produces the following discussion;

someone: "Hey, that's a goto! You can't use a goto!"
me: "why not"
someone: "they're evil!"
me: "why?" [1]
someone: "Everyone knows that?"
me: "Okay, I must be stupid, why is this bad?"
someone: *mumble* *mumble* *run away*

Perhaps that wasn't verbatim, but it gets the idea across. Often, programmers will scream about something they don't completely understand [2]. I think the best argument against such knee-jerk reactions I've ever seen went something like this..

me: "would you use a return statement in a middle of the method?"
someone: "oh sure! I do that all the time, makes flow easier!" [3]
me: "How about something like this:"
public void someMethod() 
{
   if(something != something_else) 
   {
      goto end;
   } 
   else 
   {
      do_something_else;
   }
   end:
}
someone: "err.."

Of course the above was not Java, but the example is meant to illustrate the fact that maybe a "goto" isn't such a horrible, evil thing when applied correctly.


[0] .. and reading it daily really makes you appreciate your co-workers quite a bit more!
[1] Don't forget, we're talking Java here, there is no unconditional branching in Java
[2] Many will say that about me and often they will be right!
[3] Amusingly enough, that's something I don't like at all and avoid doing.. but try not to preach about, it's often style over substance.

July 13, 2005

.. and the dumb question of the week award goes to..

Me! For asking my boss this morning

"Hey, can we make synchronous soap calls"?

I'd like to thank my mom, my absentmindness and of course all that wine I drank last night.. I wouldn't have been so dumb without you.. thank you.. thank you..

I bet he's asking himself right now why he hired me...

July 04, 2005

Agile Programming..

.. because there aren't enough buzzwords in the world of developers. If I do agile programming with ajax will the universe fold on itself?

What is this love of buzzwords technology geeks appear to have?

Iterative development has existed for years.. but now we have a manifesto, some bad principles (documentation is more important than that) and we can box it up with a pretty ribbon on top!

Agile Development! Something for management to get excited about.

Dilbert would be proud.

June 29, 2005

The good, the bad and the annoying: being female at JavaOne

There are probably a 100 females at this entire conference, but I only speak for myself, so no need to agree with me if you're one of them.

  • I feel like a leper in many sessions.. people squeezed in chairs but nobody sits next to me until it's absolutely necessary. I know I'm female.. but honestly! It's not contagious!
  • Random people who think I want to be hit on just because I'm sitting somewhere and resting/relaxing.
  • The ladies room is nearly always empty and quite clean -- that's nice.. maybe I should just hang out in there instead of the lounge.
  • The most annoying of all: random people taking pictures of me.. what the hell, I'm not a conference attraction.

June 28, 2005

JavaOne: vaguely unrelated to the keynote I'm watching

Ask any JavaOne alumni (I hate that word) and they will tell you: only the first general session is actually worth going to.. everything else is boring, repetitious or just a sales pitch. Granted, maybe not "any" alumni but only the more jaded, cynical ones.. but still it's something that you might hear often from one of the thousands people milling around the hallways with orange "alumni" badges.

Personally, I've concluded that watching the keynote from the stairway outside the hall (where I'm sitting right now typing this) is a lot more exciting than in an uncomfortable chair in a dark hall. I'll add a picture of all the like minded people later when I can find my usb micro drive adapter. I think it's in my suitcase.

Whoever is the person writing this weblog is right.. my other JavaOne entries totally suck.. and I'm not ashamed to admit I'm using my blog as a personal notepad.. so pffft. I do wish that people put up "about me" pages or at least mentioned their name somewhere on their weblog so I don't have to refer to them as "whoever is the person.." when linking to an entry.

Things that JavaOne needs more of: power outlets.

Edit: well, I totally screwed up that picture.. don't ask.

June 27, 2005

JavaOne Notes: xml performance

The whole session (well, the half I sat through anyway) can be boiled down to "don't use dom, use JAXB, it's more efficient".. duh.

JavaOne Notes: Mustang and Dolphin

Disclaimer: my notes aren't meant to be complete -- they essentially reflect the parts that I'm interested in.

  • Version number change. There will be no release 5.1 and release 6.0 becomes release 6 (Mustang) and the next release will be 7 (Dolphin)
  • Mustang - third quarter 2006, Dolphin - first quarter 2008.
  • Release cycle: 18-24months for feature released, no more maintenance releases and update (bug fixes) releases will now be every 2-3 months.

Mustang JSRs:

  • 202: class file update. Primary change: split verification adopted from J2ME platform verifier checks compiler generated assertions instead of generating and checking assertions itself.

  • 199: compiler API (just what it sounds like)

  • 269: annotation processing (ToDo annotation, cool!)

  • 260: Javadoc Tag update

  • 221: jdbc 4.0. Drivers will now just be in a jar file, no more explicit class loading, the manager can just get a connection.

  • 223: scripting - mustang will include the Rhino javascript engine (finally, a connection between Java and JavaScript)

  • 105: xml digital signature

  • 173: Streaming API for xml

  • JAXB 2.0

  • JAX-WS 2.0 ( &181 &250)

Mustang builds are available online: http://mustang.dev.java.net.

Smaller features:
@SuppressWarnings("deprecation") - (yay!)
classpath wildcards (finally)
dtrace
improved OutOfMemory handling -> more explicit messages and a stack trace
improved performance

Dolphin
JSR277: Jar files: sharing, isolation, versioning, native code, composition, dependencies (sounds great).

JavaOne Notes: Fireside Chat with James Gosling

Disclaimer: my notes aren't meant to be complete -- they essentially reflect the parts that I'm interested in.

  • There will be no partial Java distributions to minimize size (ie: java w/o swing, etc)
  • JAX-RPC becomes JAX-WS. Heavy use of annotations, analogous to Indigo (MS)
  • DOM is not going away and it will not be deprecated
  • We will not likely see OSX JVM from Sun directly due to JVM porting for an OS (as opposed to an architecture) is more expensive
  • The Hip^h^h^hGosling oath: First do no harm - deprecated methods will never go away (to preserve compatibility), some may be undeprecated

June 24, 2005

Packing for JavaOne

I'm off to JavaOne this weekend.. too many sessions, too little time. Am I the only one who wishes there were more hours in the day for this one?

I'll be sure to boo Dennis Miller.. if I make it to the bash.

.. and if anyone has a copy (or knows where I can get it) of the Cisco vpn client for osx, let me know? It would help me out as I really will not drag two laptops with me.. [update: got a copy, thanks a lot!]

June 13, 2005

Eclipse: convert tabs to spaces

If you recently upgraded from Eclipse 3.0x to 3.1x (as I have) and enjoy using spaces instead of tabs (as I do) then you might have discovered (as I have) that the option appears to have vanished from editor settings in preferences.

It took me a while (about 5 annoying minutes) to find it..


Window->Preferences
Java->Code Style->Formatter

Hit "edit"

Under "General Settings" uncheck "use tab character"

Apply.

If you were using the default formatter, it will ask you to save it as a new one.

That was obvious, wasn't it?

June 08, 2005

Obscure code of the week

Not so much obscure as just.. well.. bad.. or more of the "what the hell" category.

(context: in a catch exception block, e being the Exception being caught)

object.setResponseError(new Integer(e.getErrorCode()).toString(),e.getMessage());

*blink* For just one line of simple code, it sure grabbed my attention.

May 31, 2005

Are null objects equal?

This is really more a philosophical question than a programming question, but one that has been sitting in the back of my mind for a couple of weeks.

If two objects are null, are they equal to each other[0]?

I can see three possible answers:

(a) They're neither equal nor unequal.. because two null objects cannot be compared in the Java world using the good old Object.equals() -- but of course that's only because you cannot call equals() on a null object, so that in itself is not a good enough reason.

(b) They're unequal because we cannot determine any function of equality (usually when we equate objects it's because of some attribute(s)) -- this one breaks down as well, since lack of attributes can be treated as an attribute itself.

(c) They're equal because they lack attributes and all things considered equal, they are identical in the fact that they're null and since Java considers two empty strings as equal (somehow that one is easier to swallow) then it falls within the Java view of the world.

I may be the only person in the world who has a problem just coming up with a simple answer to this one[1], but my gut feeling says it's (c) with a little bit of a mixed in: If the objects are of the same type then they're equal, otherwise it's undeterminable. Which means, two null strings are equal, but a null String object and a null String[] object are not[2].

[0] By equal I mean the Java view of equal, meaning: they're either the same object or their attributes match based on some object-specific function.
[1] Feel free to think me an idiot for even wondering about this.
[2] Of course, there's no way you can tell what an object isn't when it's null.. but it's the intentions that count and this is purely academic anyway.

May 04, 2005

Why doesn't oracle support boolean data type?

It's a well-known limitation of Oracle.. but I've never seen a decent explanation as to why exactly they do not support it? I know it's optional in the SQL spec.. and I know some other commercial databases do not support it either.. but one would think a giant like Oracle would do at least what MySQL does (alias to tinyint) and spare me the fight at the office over its implementation. (I want the standard, int (constrained to 1, 0) others want a char 'y' or 'n', bleach).

So anyone know why?

April 30, 2005

Variable length redux

When I posted this entry I never expected it to turn into a long discussion. It was really more of a rant born out of frustration when trying to read someone's code. I don't have much to add other than what is posted in the previous entry, but I thought Burt's (who is a former co-worker, a good friend and an excellent programmer anyone would wish to have on their project) comment deserves to be in an entry all on its own. He explains much better than I why this is even an issue. For context, read the previous entry and all the comments first.

Golly.

This is not a religious war - this is clearly a difference of opinion between people who have different ideas of what clarity is.

There's several key aspects of clear programming that some of the people here are missing:

1. Methods should NOT be 10 miles long. If you need a long variable because you don't reference it until 50 lines later or you don't know what type 'rval' is because the method declaration is 5 pages back in your editor, the problem is with your method, *not* with the choice of name. And in fact, something like rval *is* very clear. After looking at 50 methods all where rval is returned, it becomes pretty damn clear that when you set 'rval', you're setting what is returned. If some uniquely named thing is returned from every method, there is an order of magnitude more effort identifying what is returned.

2. Formatting *is* important. As Mats mentioned, the human brain is great at pattern recognition. If this causes you a bit more effort when you modify code, too bad. Code is read MANY more times than it is edited - Paul, are you suggesting that we should the tradeoff of legibility vs. ease of writing should be made in favor of ease of writing? Shame on you!

I'd say that formatting is even more relevant than the length of the variable name. The clear organization of her example was more important than the length of the variable names - but the shorter length of the variable names enables such clear organization more than variable names such as preparedStatement, jdbcDatabaseConnection, queryResultSet and objLongAss. In addition, your brain's time to process will be proportional to the length of the name, as will the effort to match the pattern. Which is quicker? Finding 'rval' in ( ps, rval, conn, rs ) or finding 'customerObject' in ( customerQuery, customerObject, connection, customerQueryResults )? Furthermore, there is an inherent loss of clarity when you have to break a single statement into multiple lines because you are doing something like

PreparedStatement selectCustomerPreparedStatement = c customerDatabaseConnection.prepareStatement(selectCustomerSQLString); ResultSet selectedCustomersResultSet = selectCustomerPreparedStatement.executeQuery();

3. The aptly-named Aristotle there was 100% spot on. If I'm writing a loop, give me an actual reason to use a giant variable name as a loop index. Since the loop should fit on the screen, i.e. be no more than 5-10 lines, it should be pretty damn clear that i is the loop index - I really don't need something like intLoopIndex to tell me that. If you're finding yourself scrolling back and forth to check variable names and types, you've gone past the point where it's time to refactor a chunk of code into another function/method.

5. Don't knock the C programmers. There's a lot to be said for typing efficiency, and there's a reason why many unix commands are 2 characters or so. Frankly, I am less concerned about there being a slightly longer learning curve for people than I am about treating senior developers as fools, and I am greatly concerned about the effect of 'point-and-click' programming on the capabilities of developers.

6. WHAT THE HELL HAPPENED TO COMMENTING YOUR CODE?! Yes, the code should be clear. But it is your responsibility as a developer to write clear comments! The clearest variable name in the world will still not tell you WHY something was done. I (fruitlessly in many cases) look to the comments for purpose, not to the variable names.

Anyways, I agree with Kasia 100% on this, though I fear it's a losing battle given the vast preponderance of 'helpful' IDEs these day - observe pbw's comments about the editor 'fixing' the code formatting. Great, just what I need, yet another tool that thinks it's smarter than I am.

April 26, 2005

A completely and utterly irrelevant coding practice that drives me nuts

Long variable names. Hm, not quite.. unnecessarily-long variable names (there are very legitimate reasons why someone would sometimes use a long variable name.. that is not what I'm bitching about).

An example of that would be.. say, this completely-fictional-but-reality-based code snippet:

Connection connection = getConnection();
ResultSet resultSet = null;
PreparedStatement preparedStatement =
connection.prepareStatement(some_query);
SomeLongAssObject someLongAssObject = new LongAssObject();

//blah blah blah

return someLongAssObject;

I see code like that and my blood boils over. Yes, I know I'm anal and there is nothing really wrong with writing code like this.. except.. well.. it's hard to read! It's sloppy and, let's not forget, badly formatted.

Same code as above as refactored by the queen of anal code:

Connection        conn = getConnection();
ResultSet         rs   = null;
PreparedStatement ps   = conn.prepareStatement(some_query);
SomeLongAssObject rval = new LongAssObject();
//blah blah blah
return rval;


Now isn't that better?

April 09, 2005

Code Coverage: so that's what I've been missing!

I know, I know.. every single comment I'll get to this post is "what? You've never used a code coverage tool before?".. but it's true.. I've never actually used a code coverage tool before.. It just never came up on any of my projects and none of my previous co-workers ever mentioned even the possibility of using such a tool... but.. well..

This so completely and utterly rocks. I've been using clover on our project at work and it's really very, very cool. I can tell exactly what's been tested properly, what hasn't and what unit tests I still need to write. The reports clover generates are quite easy to read and go down to source code level, so you can easily tell what's not tested yet (or what is just error checking).

Another tool I've looked at before we settled on clover is Emma. It's not as nice as clover (the reports are harder to read) but it works well and, best of all, it's open source.

Both tools work just fine as ant-tasks.

(I'm averaging at around 80% coverage on my unit tests for those curious).

January 21, 2005

Favorite bug tracking tools?

I'm in the market (so to speak) for a new bug tracking tool.. there are only a few requirements and it doesn't have to be open source or free, just good!

  • Web based
  • Tiered security
  • Not hell to administer (don't want a full time employee just for this!)
  • E-mail notification
  • Decent reporting
  • Integration with source control would be nice, but since we haven't picked a tool for that yet, it's not necessary.

I'm currently looking at:
BugZero
Scarab
ProblemTracker

December 10, 2004

Ten tips for new programmers

1. If your new employer buys books, take advantage! Read them!

2. Work extra hours to finish a project that's off-schedule, it will come in handy when it's time for a performance review.

3. Always document your code, you never know when someone else might need to read it.

4. Keep daily notes on your progress, it comes in handy when you need to take a few days away from a project.

5. Take advantage of any training your employer provides, it makes you a more valuable employee.

6. Start your work day early, you can get more done in the morning before the office fills up with coworkers.

7. Don't abuse company resources, that next raise may depend on it!

.. and finally ..

8. Keep your personal items at work to a minimum, it's easier to carry out when it all fits in one box.

9. Label your office supplies, that way you can claim them as your own when it's time to pack your box.

10. Accrue your vacation days so when you get laid off you have extra paid time.

November 23, 2004

Dealing with database portability and auto increment

It appears every relational database has its own way of dealing with automated identifiers. Most databases, for instance Oracle, allow you to create sequences which can be used in conjunction with triggers to create a sequential ID when inserting rows of data.

MySQL has its own way of dealing with this problem which stems from its lack of triggers in all but MaxDB versions. In MySQL there is a special column attribute "auto_increment" which will increment the value of the identifier upon insert. Behind the scenes, it is really quite simple, MySQL performs a special lock on the table, selects a max value on the column and adds 1. The downfall (or for some, it may be a benefit) of this implementation is that ID numbers can be reused if data is deleted after the database server has been restarted (since MySQL stores the information in memory). With the Oracle approach, the ID numbers will not be re-used unless the sequence is renumbered - not something that would be done often.. well, in most cases.

PostqreSQL somewhat combines the two approaches. It provides the ability to create sequence but there is no need to triggers (as you would use in Oracle), instead you can use nextval('sequence_name') as part of the table declaration, much like auto_increment attribute in MySQL.

For insertion purposes all these approaches work in a similar manner: you insert a row with a zero or a null ID and the database does the work for you. The difference is in how you can retrieve the ID once a row of data is created.

There are a couple of ways this can be handled:

1. Handle it in the code using abstraction and writing separate implementation for getting the identifier based on the database type.

2. Create your own implementation of incremented Identifiers: for instance a table which stores a separate value for the last id for the table/column.

The drawback of the first approach is obvious: writing more code to implement each separate supported database. On the other hand, it utilizes built-in database functionality and simplifies insertion.

The second approach has its drawbacks as well, which brings me to the whole point of this entry. I have seen this solution used in many open source projects to simplify database compatibility code and find that to be clunky for a few reasons:

  • A select statement must be made before each insertion.
  • The table needs to be write locked for the duration of the transaction to prevent another process from grabbing the same ID and creating duplication
  • Manually inserting data into the database becomes a hassle (you're faced with two sql statements for a row of data instead of one)
  • You're not utilizing the features of the database which are optimized for this purpose.
  • The whole process is likely slower

I find the extra effort spent on writing abstracted database persistence code to be well worth the hassle you avoid while later debugging and supporting the application.

Teaching students about their environment

Being an active contributor to technical forums I am often faced with surprisingly simple questions about basic programming environments from computer science students. Students are often lazy and why should it surprise me that so many don't bother to learn the basics, right? Maybe, but too often it is ones who are otherwise bright and not at all lazy. So what is the true problem?

Thinking back to my own basic programming classes I think I can see the problem clearly. I cannot think of one professor that explained the programming environment in class. The books tend to skip over those parts as well.

What is the number one problem students have with their Java projects?

Classpath.

Something as simple and basic as that, it's just not explained in class. Is it too simple and ought to be self-explanatory? Perhaps, but I wouldn't expect a first year CS major to grasp the concept of classpaths without at least a basic introduction, why are CS professors expecting it? Sit a student in front of a tool like eclipse and I guarantee their eyes will glaze over and a simple concept like a compiler will not occur to them on their own.. command line? Forget it.

With the development environments getting more and more complex each year and the command line being something of the past (unless you're a unix geek like me) I think CS programs should look into providing classes in basics of development environments. Using tools like source control, IDEs, etc. It would help the students understand programming better and give them a better start in the workplace.

October 20, 2004

Why use a debugger?

I got into an argument today with someone over using a debugger. According to this person "debuggers are for lazy and sloppy programmers". My first reaction was "what?".. then "bullshit!"... then.. some time later and after a somewhat heated exchange (I have a temper, what can i say?) I finally understood the problem.

He thinks people use a debugger to understand the structure of the code.

Okay, perhaps some programmers do, okay, perhaps many programmers do. I don't. I can read code, thank you very much, and I do not need to single step through it to understand the flow. I use a debugger to quickly find problems. In a debugger I can examine the run-time values of variables, indeed, change those values and do other useful things that greatly speed-up fixing of code.

"You should program defensively and make sure your code can output information during run time that will help find out problems"

Of course you should, and I do, unfortunately I work in the real world where majority of the code i work with was written by other people and even though my performance review called me "refactoring queen" that is not my primary job function.

"Use print statements!"

Life is too short, see above.

"Reading the code to find the bug makes you learn the code by heart"

Oh, of course it does, and you can also stare at it for hours and not see the problem until you examine it at run time for a big "doh!" That is unless you're perfect, sadly, I'm not and I do make dumbass mistakes on regular basis.

"Linus Torvalds doesn't want you to use a debugger on the linux kernel code"

Great, good for him. Linux kernel was not written by my co-worker who is in love with abstraction. I guess I won't be working on it anytime soon, bummer.

It's no more lazy and sloppy to use a debugger than it is lazy and sloppy to use a high level language instead of assembly. It makes my job easier, makes me fix bugs faster and makes me a better programmer.

October 12, 2004

Remote Java debugging with emacs

With the retirement of the sun server I used to work on at work (RIP cortez) I have moved operations to all-linux-all-the-time, which also means using Subversion (no more ClearCase!), emacs on linux - not sun, JBoss not weblogic and newer JDE (2.3.3).

It was when I tried to debug something today that I discovered I was used to a rather ancient version of JDE on my sun box. Attaching a debugger with that version required writing a JDE extension and setting up some cryptic things in .emacs. None of that works anymore, particularly since jde-db-init doesn't even exists as of 2003 or so.. obviously I was used to a very ancient version of JDE.

Thankfully, setting up the newer one to attach to an external process proved to be very, very easy.

in .emacs:


  1. Location of source:
    jde-sourcepath ( "/home/ktrapszo/src" )

  2. Debugger socket:
    jde-db-option-connect-socket (nil, "28380")

    Default socket is 4444

That's all it takes to setup JDE to attach to a remote process with jdb. Easy!

Of course, the second part of that is running JBoss in debug mode.

-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:server=y,transport=dt_socket,address=28380,suspend=n

Easy, more reading: JDEE page

July 12, 2004

ClearCase to Subversion

As noted here I am working on a conversion of a ClearCase repository to Subversion. Since there appear to be no resources for this available I wrote a simple perl script that handles the conversion in a relatively simplistic manner. In short, it checks out each version of a ClearCase file and checks it into Subversion, therefore creating the history. It's simple but effective and it worked quite well to convert our entire repository (some 30+ hours for the whole thing..).

Anyone who wants it, it's here, but please make sure to read the documentation, particularly the limitations before you attempt to use this thing.. and by all that is holy, run a test run and backup!

June 02, 2004

Clearcase -> subversion

I'm researching switching our source control tool from the feature-rich and appropriately expensive Rational ClearCase to the open source and apparently quite nice and stable now, Subversion.

It appears that conversion scripts from CVS to Subversion are a dime a dozen, however I've been having a hard time finding any information on converting from ClearCase to Subversion.. I suppose it wouldn't be particularly hard to make a script to convert all our history.. but I'm more interested in finding out about pitfalls and things to watch out for from people who have done this before.

Anyone have any info?

April 22, 2004

Hey, a sane coding style

I whole-heartedly concur with all that is good an geeky.

In my own code, I tend to also add an additional line under a comment for readability.. like so..

// This is a comment
//

Hungarian notation? Hate it, despise it, don't like it. It makes for long, clunky variable names that become cryptic instead of helpful half the time.

[via jeremy]

April 14, 2004

Named code blocks in Java

I didn't realize I was starting a religious discussion with my post about multiple return points from the same method. I suppose I could have been clearer (one sentence is pithy even for me, but it was posted in a state of relative upset) and specified that I meant Java. Maybe an example of why this upset me so would have been nice as well, but little late now. Let's just say it involved, reflection, setting a debug level and execution ending before debug code was reached.

In my mind (but go ahead, disagree, keeps things interesting, I'd hate for everyone to agree with me), there's really no excuse for using multiple return points in a language like Java. Number one argument to my proposition appears to be "code readability".. this provides me with an impression that not enough programmers realize Java supports this wonderful thing called code blocks. That you can name! If you wish to avoid convoluted code, they're your best friend.

It's really quite simple, and even more so with my easy to follow example:

private boolean testSomething(Object this)
{
    boolean rval = false;

    DONE:
    {
        this = doSomething();
        if(this.isThat())
        {
            rval = false;
            // Exits the code block completely
            //
            break DONE;
        }

        // more code..
        //
        
        // some more code that will only execute if you didn't
        // call 'break' or 'continue' above'
        //
        rval = true;

    } // end of code block.

    return rval;
}

This is incredibly handy in keeping code clean and easy to read. In a gist, each code block has to have one label and one entry point, may have multiple exits.

April 13, 2004

Writing readable code that's easy to debug 101

Multiple return statements in one method are bad, m'kay?

March 18, 2004

Getting more info out of ServletException

This is probably obvious to everyone, but it took me looking at javadocs to figure out how to make tomcat give me more information than just a generic "ServletException" with no context, no message and a useless (in this case) stack trace.

Thread-45[1] dump e.getRootCause().printStackTrace();

Where e is the exception, RootCause is a java.lang.Throwable

java.lang.NoClassDefFoundError
        at xxx._jspService(_xxx_0.java:262)

Much better than

javax.servlet.ServletException
        at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:508)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)

November 10, 2003

Java and perl

Together at last using Inline::Java

Here's how.

Not sure what I'd use it for but it's cool regardless. Perl, it's what's for dinner.

September 29, 2003

Source control -what a pain

I've decided.. I just dont' like CVS.. I really don't. Sure, it's a great tool and I'm certain it works wonderful for something like say, open source projects -- unfortunately I'm finding out that in real life it's just a pain, pain, pain.

Real life? Well.. something like a development team where you really don't want the headaches of merging in code every time you make a change. Unfortunately, CVS isn't very kind to those who like exclusive checkouts (yes, I know.. C is for concurrent). Configurable but still a pain in the ass.

My main problem is that I am essentially addicted to refactoring code... I'm anal about formatting (well, really we all should be but that's another rant) and I simply cannot stand duplicated code and 1000 line-long methods. So I refactor.. a lot. You try and merge that in!

And no.. RCS is not an option for various factors, not the least of it being developers on windows machines (eek).

So now I have CVS that is built on top of RCS that I want to act as RCS and the one project I found that makes it do that has not been updated since 2001.. Subversion is also not an option, cool as it looks.

Rant over.

September 22, 2003

If you really want a mini to haul a trailer..

Philip Greenspun apparently forgot that there is such a thing as an appropriate tool for the job.

Java an SUV? Perhaps.. but then php is a Mini - admittedly a very cool car that will get you to your destination, but do not attempt to haul a heavy boat behind it.

July 21, 2003

Javascript, JSP and common code base

I'm not exactly a JSP veteran so this may sound like a very stupid question.. but how do other, more experienced developers deal with common JavaScript methods?

Now with JavaScript being object oriented it makes it relatively simple to write common functions.. and so far my solution has been to simply put them in includes files that get included in the JSPs themselves.. There has to be a better solution..

I searched and searched and searched and nothing jumped out at me that would solve this in a more elegant manner.. so I pose this question to the Java folks in the blog land out there.. how do you do it?

And uh.. thanks for reading this completely useless blog post :)

July 01, 2003

Java I/O.. yah, it sucks

To quote from an eloquent entry:

I've said it before, and I'll say it 'till I loose my voice: I fucking hate Java I/O. All I want to do is get all the contents of whatever's in a stream, a reader, buffer, or whatever the hell else I have a handle on. Can I just call something like the below:

String contents = new File("somefile.txt").getAllMyShit();

Of course the fuck not! I have to keep track of byte arrays, char arrays, or some stupid ass shit in a while block. I just want the God damned content, I don't care how the JDK gets it out of there.

I always thought there should be a method on StringBuffer, perhaps called loadFromFile(), that takes a File object.

Re: Gender bias in the tech recession?

John Mitchell writes:

As I've been walking around, sitting in sessions, and generally being a nuisance, I've been struck by the fact that there seems to be a noticeably larger percentage of female developers at the show than in previous years.

Yes, this could be explained by the fact that there are fewer total people here this year so perhaps it's just more striking to my less saturated brain but.... What about in the overall technology world? Given the relatively small percentage of female developers floating around, are they getting laid off less than male developers?

No, John, there is no gender bias.. it's all very logical. See, women typically have to work a lot harder and be a lot smarter to get where men are in IT.. that means they're less likely to be laid off when times hit hard. I know only a few female programmers but all but one I know are simply very good or excellent.

I would have posted this as a comment in your weblog but you have a requirement for registration just to post a comment. That's cumbersome and silly... particularly for someone like me who is not a regular reader There are enough useless accounts of mine floating around the web as is.

June 21, 2003

The abuse and over-use of toString()

This one is sneaky.. most programmers when writing debug code tend to call the toString() method on an object to retrieve human-readable information and present it to the user in some shape or form (logs, system out, etc). That's good programming.. when debugging a problem we want to be able to read and view all information possible..

Here is the sneaky part.. you should never *never* call toString() on a Java object unless you're pretty damn sure that object will never be null. Why? It's simple.. calling toString() on a null object will generate our good old friend -- the null pointer exception. (What? Java has no pointers! -- wrong!). This is a huge problem.. Think about it.. where do we usually put most of our debugging code? That's right.. error handling.. Something like this, perhaps:

try 
{
   myObject = doSomething();
}
catch (HorribleException e) 
{
   String msg = "Dude, we got us a problem: " + e.getMessage(); 
   msg += "The object looks like this" + myObject.toString();
  
  // do logging and stuff..
  //
} 


If myObject happens to be null, which may very well be the case considering we have an exception while trying to create, modify or reference it it will throw a null pointer exception at which point this becomes a debugging nightmare as the original exception is now lost. Maybe not a huge nightmare in a development environment.. but try to debug issues with code like this in a production environment where all you have to go on is logs and system output. Right.. nightmare.

What should you do instead? Forget toString()! There is a better way of doing it and that's String.valueOf(object) which is implicitly called on calls that convert objects to strings. String.valueOf(object) internally calls toString() on the object -- but it checks for nulls! This is the behaviour you want in your debugging code.. if the object is null you do not want an exception.. just a "null" ought to suffice and the toString() output otherwise..

try 
{
   myObject = doSomething();
}
catch (HorribleException e) 
{
   String msg = "Dude, we got us a problem: " + e.getMessage(); 
   msg += "The object looks like this" + myObject;
  
  // do logging and stuff..
  //
} 


Will generate exactly the same output as the first example when object is fine.. but only the string "null" when object is null. Safer and even less typing! The scary part is how many experienced programmers have no clue about this little gotcha.. go spread the word. Thanks.

June 17, 2003

Who went to Java one?

Those of you that did.. did you see a guy with really long hair and a patch on one eye? That's my boss who got to go instead of me..

At least he brought me back a MySQL tshirt.. the back says "transactions" with a checkmark.. too funny :)

June 08, 2003

Java performance urban legends

Pretty good article on Java performance "urban legends".

In summary...

  • Urban performance legend #1: Synchronization is really slow

  • Urban performance legend #2: Declaring classes or methods final makes them faster

  • Urban performance legend #3: Immutable objects are bad for performance

Thanks to Demitrious for the link.

June 01, 2003

Java exception handling

I've been involved in a couple of discussions about exception handling in Java recently.. and while the discussions were sparked by unrelated topics I came out with one conclusion from both.. People just don't seem to grasp some very basic design ideas when doing error handling..

Number one mistake I see everyone do is..

try 
{
   ....do something here...
} 
catch(Exception e) 
{
   .. handle error
}

Unless you're working on a one-file CS project this is probably not a good idea.. The generic Exception object should only be caught when you *know* what to do with every different type of exception that could occur.. this includes something as basic as a NullPointerException.

In other words.. just catch the exception you can handle and throw everything else up to the calling class.. more often than not it's much more useful information at a higher rather than lower level.

Another mistake.. wrapping an exception inside a new exception and throwing it up the food chain that way.. This may seem like a good idea from the standpoint of clear, easy to understand design.. but by wrapping that exception you're throwing away vital information that the front end could use to handle the error.. It's often appropriate.. but more often not.

In a jist: Only bother with errors you know exactly how to handle.. throw everything else up. Well, of course, unless you're working on front end code.. then that's a whole different story.

Phew.. Java pet peeve #4908983439 :)

April 30, 2003

Why chaining calls is bad

(or learn from my screw-ups)
Refactoring code is somewhat of a hobby, I suppose, since I do it as much as I possibly can (or have time for).. so seeing something like this..


String result = (someString.trim() + anotherString.trim()).toLowerCase();

Boils my blood and of course I have to rewrite it..


String result = "";
if(someString != null)
   result += someString.trim();
if(anotherString != null)
   result += anotherString.trim().toLowerCase();

.. and of course I completly missed the part where the entire string was set to lower case.. not just the second portion.

Stupid me (this caused real problems too).. but I say at least 20% of the blame is on the hard-to-read chained code.. (20% more on me being in a hurry and rest on me for not paying attention, but who's counting..)

April 25, 2003

What happens when you don't upgrade software

I was writing some test classes at work today using JUnit.. nothing out of the ordinary.. just your typical..


result = doSomething();
assert(expected == result);

I'm sure someone's already spotted my problem.. but wait :)

Code compiled.. that's nice.. then a co-worker cannot compile it in her work area. Hm. Problem. Apparently assert(boolean) is not a valid JUnit method call.. What? Checked my libraries.. sure enough mine's horribly out of date, hers is newer.

Now I'm mad. You don't just remove a call.. you deprecate it! My compiler didn't give me a deprecation warning.. (as you can imagine I was already salivating at the prospect of having a good rant at JUnit's expense). Checked their website.. read documentation (yah, I do that sometimes, but only when absolutely necessary) and found out that since assert has been assimilated by Sun as a Java keyword, the method call was deprecated and since removed.. A long-ass time ago.

My jar file was *really* out of date. (This is where I slap my forehead and you laugh at my expense).

April 22, 2003

There is a programmer hell

.. and I have found it!

You know that part of the project when you're busy doing bug fixes? Tedious.. little, annoying bug fixes? Fixes that only take about half hour to an hour each but because of the qa/testing process really take 2 hours each as you tear your hair out between server restarts and QA deployments? That part..

Now imagine it stretched into two weeks of tedious, annoying bug fixes that require all kinds of hacking around and tweaking to even reproduce (but they're still bugs, need to be fixed!)....

That my friends is programmer's hell. And I'm the newest resident, pray for me.

April 18, 2003

JavaOne or "I work in a Dilbert cartoon"

For years now I've wanted to go to JavaOne but unfortunately I cannot afford to pay the $1700 conference fee on my own.. well, that plus travel expenses. It adds up.

So, naturally, I approached my boss with the idea..

"hey, can the company send me to Java one?" - It is work related, I program Java for a living.
He said he'd ask higher up.. which he did...

The result? Not exactly what I expected.. apparently people higher up thought it's a great idea! Wonderful, our engineers want to learn more Java.. that's great.. Let's send two of them! Yep, two *other* ones including my direct boss.. the one I asked if I could go..

Strike one -- time for plan B.

"I'll stay with friends, pay for my own plane tickets and mooch off of others for meals.. Can I go? Pleaaassseee.. ?"

Yah, we have budget for training for each employee.. but.. *nope*.. It will cost too much to send the other two.

Sigh, I can't win.

April 16, 2003

Classifying programmers

Many of us coders have a hard time deciding just what to use for a job title.. there are so many different terms that essentially describe the same job.. developer, engineer, programmer, coder, hacker.. In theory, anyway, they describe the same job. I'm sure many would argue against such simplification. but before you fire off an angry comment bear with me, please, I will explain.

What matters is how I introduce myself to people. It really varies vastly from situation to situation. Most of the time it's a simple "I write computer software".. which usually elicists a response of "aaah..." and a vaguely blank stare... When I introduce myself to one of my mom's friends I make sure to throw in a term "engineer" in there somewhere so my mom can stick her nose up in the air "see? My daughter is an *engineer*" even though she has very little clue about what I really do.. and frankly the idea of an engineer her friends probably have is about as close to my job as Moscow is to Bundtown, Tennessee.

"Why do you sit in front of the computer all they long like this? "
"uh.. mom.. " sigh.

The problem of what to call my job arrives when I talk to someone in my field. Another geek.. because everyone has their own pre-conceptions about what a programmer is and what (s)he isn't.

So after careful consideration of this problem.. well, okay, the reality is closer to "after having nothing better to think about during a boring meeting.." I've decided to define my terminology a little better. I write code for a living, but while I may have the same official job title as some other coders I know I don't really think I should be classified the same way some of them are because there are so many different types of programmers that one general term of "programmer" is just not descriptive enough to be useful.

So there is the term "programmer" -- easiest definition, of course, "one who programs". That is what I do, it's what we all (the general code-writing "we") do.. So this one's easy.. a programmer is someone who writes code.

Then there's "software engineer" -- "one who engineers software". Not every programmer is a software engineer.. in fact I would dare say that vast majority of programmers are not. We all know the type.. they write their code, they do a really good job, code is functional, it does what it should.. but that's where it ends. The finer points of design and esthetics escape them... they just don't think about writing software in those terms.. it's just a job to them. Those people who go the mile above and take time to think through design and would not be caught dead copy-pasting code without at least giving the thought to how it functions as part of the overall design are software engineers. They engineer, not just code.

Lastly, but not leastly.. there are "hackers" -- not in the definition made notorious by media (for whom geeks behind keyboards are not exciting enough.. they had to make them into dangerous masterminds) but in the original term of well.. hacking stuff together. I'm sure we all hack code every now and then.. In a hurry.. need to patch a bug in production version.. a hack is sometimes the only way.. but then there are programmers who never do anything *but* hack. Often solving some of the most complex problems and producing some of the most brilliant solutions that neither of the types listed above could ever come up with.. Unfortunately more often than not.. they're the only ones who can even understand the flow of the code.. so if such a coder gets hit by a steam train.. people left over to maintain their code are essentially screwed. I once attempted to work with such code.. it would have been easier to convert a catholic priest to judaism than to understand how this particular project worked. But it did work and well.

So going by above definitions.. I would have to say I'm a software engineer. Of course next time I introduce myself to someone and give them this entire spiel about how I define my job title they will be asleep by the time I reach the term "software". Maybe I should just say "I'm a professional geek". It's quicker.

April 09, 2003

Code reviews or "how did I miss that?"

Load testing aside, it's nearly impossible to account for real live usage when writing test plans and some users have incredible talent for coming up with creative ways of using (or rather misusing) a program in a way it was never intended to function.

We just went through some of that with our new project at work and I think the common conclusion was that we really need to do regular code reviews. Three major issues we just fixed were of the "holy crap, who wrote that" and "why the hell is this doing that?" variety.. Something that would have been immediately spotted if someone bothered to look at the code (someone other than the author anyway). It's so easy to make dumbass mistakes when working under pressure and having a second set of eyeballs verifying your code can be more than just helpful.. it could save your sanity and embarrassment later.

One of the principles of extreme programming is to do something like this - pair programming. Having two people work on the same code at the same time. I've been subjected to that at work for about a week.. and it nearly ended in a homicide as I slowly learned to hate the guts of the poor co-worker stuck coding with me. I'm not really good at working in tandem with another programmer.. especially one that argues about my bracing style while sprinkling the code with tons of unnecessary empty lines and indentation that would make groucho marx go ballistic.. (and he wasn't even a coder.. )

So what's the solution? Code reviews.. weekly session, couple hours long (longer and we'll all fall asleep probably) reviewing randomly picked source from project du-jour..

I think this could really work -- we all get to spot our mistakes before they enter production and can lock ourselves up in blissful, headphone-induced isolation in the meantime. Perfect.

April 02, 2003

Useless polls

I suppose a statement "useless online polls" is a tad redundant.. but there it is anyway. Someone pointed out a poll to me today on hotscripts.com.. it's right there on the right hand side, just scroll down a tad. See it? That one..

What is your scripting language/platform of choice?

Doesn't appear all that useless, right? Until you see the options..

ASP
C/C++
CFML
Flash
Java
JavaScript
Perl
PHP
Python
XML
Other

XML? Java? C/C++? In a poll about web page scripting? (I assume they mean web page scripting considering their content). Is it not bad enough that half the newbies to web design claim they know Java after writing a 10 line JavaScript.. now websites that claim to be some sort of authority on scripting create a poll with this combination of uh, scripting languages? Get a clue.

Welcome to the misinformation super-highway.

March 03, 2003

Bad code annoyance with Java #234840

Gratuitous casting to get around bad design.

I refactored code today that did something like this:

// Imagine this method returns an interface
// iStuff which is implemented by an object called Stuff. 
// 
public static iStuff getStuff(int key) { 
   iStuff rval = new Stuff(key); 
   return rval;
} 

public void doSomeStuff(int key) { 
   // Note, this was just cast to an object!
   //  
   Stuff stuff = (Stuff) getStuff(key); 
   stuff.doSomeChange();      
} 

Sorry, this is the best way I could duplicate what the code did without actually copying the code. Point is: Instead of changing the design to reflect the fact that the interface did not have a method needed.. someone went and cast an interface to an object. How horrible! Yet legal. Also very dangerous as it will break if someone changes the underlying implementation of the getStuff() method.

February 27, 2003

Data validation

Data validation is particularly important when dealing with web development. Especially when passing user input to the database it should be checked not only for validity but also for malicious content.

Something that really bothers me recently (don't ask, project at work) is the level at which the validation is often done when using servlets. Mainly, in the servlet itself. I don't like that. It adds a layer of complexity that is really unecessary and makes reuse and architecture of code more difficult than it has to be.

Java is an object oriented language.. why not use that aspect of it to its fullest ability? Mainly: an object ought to validate itself. So, if you have a user object, instead of using servlet code to validate its attributes (for instance: email address) make the object know what the valid value is.. and return that to the servlet. "Hey object, are you valid? Sure thing! Okie dokie!" .. or.. "Hell no, here's your problem, make them fix it".

Easier, no? Seems obvious.. but apparently not to everyone.

February 08, 2003

Targeted advertising

Those advertising folks at Micro$oft must think these things through quite well.. coincidence or not? You be the judge..

Pay attention to article subject.. and that's a damn big ad too!

New Java features

Catching up on my reading this morning and ran across this on slashdot.

Boxing will be incredibly handy.. I use that all the time (as I imagine most Java programmers do).. Generics (yucky term) will save me headaches from necessary-bad-design to sidestep the lack of this feature in current versions of Java. Big thumbs up for static imports as well!

This will be great.. I can hardly wait!

January 31, 2003

From the 'really bad code' collection..

I should start one.. really.

Today's gem:

public class Stupid { 

   private int _value = 0;

   public void setValue(int value) {
      if (value == _value) {
         _value = value;
      }
   }
}

Duh..huh.. huh.. why are we always seeing the same value?

January 29, 2003

JavaBlog noise

I really like the concept behind JavaBlogs... and for a while it really worked well for me. I've read many excellent entries on Java I may have (actually very likely would have) missed otherwise. Unfortunately, as is true with any growing website, the signal to no