Java best practices 2 – Explicit cases

15 augustus 2007, door arjan

This is the second installment of my discussion about various bad practices in Java that I encountered during my work. As outlined in the first installment, this entry will be about “Not structuring different cases explicitly”.

After the first installment some readers wondered why the discussion is called “best practices”, while I actually talk about “bad practices”. The idea here is that recognizing these bad practices helps you in avoiding them and doing the opposite, which is a good practice ;-)  

Not structuring different cases explicitly

A particularly nasty bad practice is when programmers don’t structure different cases in their code simply as, well… different cases. Oftentimes this bad practice is introduced into a software system whenever an extension is made to existing code.

We all know the deal; we’ve created a nice and simple Servlet that only takes an ID of something and does some work with that in a clean and straightforward way. Inevitably however a boss or customer comes along, asking for an addition to be made. Now how do you handle this?

A beginning or perhaps less talented developer tends to just keep adding parameters to the URL calling the Servlet, sorting the now implicit cases out as the code progresses. At first this may seem reasonable, but it very soon becomes a total maintenance nightmare. Bug fixing becomes hard (which set of parameters belongs together?) and refactoring becomes near impossible if you need to unravel the tightly knitted fabric of 20 or more possible lines of execution, just to find out what cases the code actually handles. After some given threshold is reached even the original programmer is unable to make any changes at all to the code and development grinds to a halt.

If you ever come to work somewhere and a ‘senior’ developer tells you some piece of code can’t be touched since “it’s to dangerous to make changes”, it’s often because of exactly this bad practice.

To give you some idea of what this would look like in practice, take a look at the following code example. Let’s suppose a Servlet can be called using a URL with the following parameters:

“ownerID, customerID, productID, salesDescription, changeText and changeID”

Now suppose the code handling these would look something like this:

processor.customerID = customerID;
if (ownerID != null) {
   store.setOwnerID( ownerID );
   // lots of other code ...
   int foo = processor.getFoo(); // introduce an intermediate variable
   // again lots of other code ...
   if ( changeID != null && changeText == null && customerID > 1) {
       store.setCustomerRegularID( customerID );
       // lots of other code ...
       if ( productID != null ) {

       }
   }
   else if ( salesDescription != null && foo != changeID  ) {
        // again lots of code here
   }
   store.setFoo(foo);
   // More and more code
}
// Lots of other code again ...
if ( productID != null && changeID != null ) {
   // ...
}
// etc etc etc

This already looks pretty bad, but now suppose the “lots of other code” comment is actually replaced with lots of other code. It shouldn’t require too much imagination to understand that it becomes ‘rather difficult’ then to decipher what the code is doing.

The problem here is clear; every ‘command’ given to the code is implicitly expressed through a complex combination of overlapping parameters. Which combination of parameters relates to which command is extremely hard to grasp just by looking at the code. The above code may actually do relatively straightforward things such as “update product description” or “update customer description” but we just can’t see that when looking at the code.

The solution to this problem is equally straightforward; simply adopt the command pattern (described by the GOF in the most excellent book Design Patterns, Element of Reusable Object-Oriented Software). Using this pattern, the above code would look more like this:

switch (command.cmd) {

   case updateProductDescription:
      handleUpdateProductDescription(command.params);
      break;

   case updateCustomerDescription:
      handleUpdateCustomerDescription(command.params);
      break;

   // other cases
}

A similar approach can be used at the URL level. Simply introduce one extra parameter called “cmd” and clearly document the meaning of the rest of the parameters depending on the value of the “cmd” parameter. E.g. compare:

http://example.com/foo?productID=4&description=some_description

with

http://example.com/foo?cmd=updateProductDescription&productID=4&description=some_description

This example may look trivial, but imagine 10 URLs with each a different combination of the parameters mentioned earlier. You’ll appreciate the cmd parameter pretty soon. Please note though that in object oriented frameworks like JSF we rarely need to construct URLs manually like this.

It may be hard to believe, but there’s actually an even more hideous form of the “Not structuring different cases explicitly” bad practice; Variable name re-using. This can actually be a bad practice by itself, but it most often shows up in combination with the former. Variable name re-using is often introduced into a software system when the number of parameters and conditionals in the code has already reached a certain threshold due to the usage of the implicit cases as described above. At this point the developer in question thinks he’s being clever and ‘abstracts’ a number of (partly) common cases by reusing existing variables to hold wildly different things. Of course, this only creates an even bigger mess.

E.g. imagine the first code fragment above starting with this:

if ( customerID != null ) {
   ownerID = customerID;
}

if ( changeText != null ) {
   ownerID = productID;
}

if ( salesDescription != null && changeText != null ) {
   customerID = ownerID;
   ownerID = salesDescription;
}

// Rest of the code as given in the first fragment here

Seems totally insane? The code fragment above is in fact a ‘simplified’ version of live code that I actually encountered during code auditing.

Well, that’s it for today. In the next installment we’ll be talking about “eating up exceptions” and “mixing JSTL and JSF for common cases”.

Arjan Tijms

 


Java best practices

11 augustus 2007, door arjan

Within Mbuyu, the company I work with, one of the things I’m responsible for is guarding the quality of our code base. This job mainly involves reading through source code and marking dubious constructs and practices. In the past I’ve been doing quite similar things at other locations.

Over time I came across a number of bad practices that seem to be repeated over and over. Many of those originate from people who are just beginning their Java career; new employees, interns etc. Surprisingly, even some more experienced Java developers sometimes sin on these seemingly straightforward rules.

Of course, there is a subjective factor involved here. People actually differ on what is a best practice and what is not. Anyway, without further ado, let’s start with a list of some common bad practices:

  • Not using types
  • Not validating user input
  • Mixing business logic and view code
  • Not structuring different cases explicitly
  • Eating up exceptions; continuing with invalid data
  • Mixing JSTL and JSF for common cases
  • Using native arrays instead of ArrayList
  • Not using Java 5 features where appropriate
  • Coding to a class instead of to an interface
  • Selecting ResultSet columns by index, instead of by name
  • Needless use of instance variables

Due to the size of the discussion, I shall discuss only the first 3 items of this list today and leave the rest to a follow-up posting.

Not using types

This may sound like a weird bad practice in Java. After all, Java is a strongly typed language, so how can we not be using types when the compiler enforces them? Actually, there are at least two ways around the type system; make everything a String or make everything an Object.

This first option is common in plain JSP programming; data enters the application from request parameters as Strings and developers simply don’t care to convert them to some data type. Instead, business logic methods are written to take Strings and layer upon layer only Strings are passed around. It seems insane to do this, but I’ve actually seen people doing stuff like this for years(!).

The second option is nowadays less common, although it sometimes shows up in JDBC programming; programmers do not exactly know what Java types correspond to SQL types so they just call getObject(); and pass the data along. Probably they’re hoping the next guy will somehow magically know to which type the Object needs to be casted.

Before the introduction of generics in Java 5, the second option was very pervasive in Java code though. At that time there simply was no way to store anything in a collection without resorting to using Object. It couldn’t however really be called a ‘bad practice’ by then, since there was really no sane way to circumvent the problem.

Not validating user input

Not validating user input is one of the most common bad practices I’ve encountered. It gives rise to a whole slew of problems, ranging from SQL injection, to cross-site scripting and excessive exception throwing. For instance, many beginners don’t seem to realize that Javascript validations don’t protect your server from malicious users who can (of course) just send data to your server directly, bypassing any Javascript validation you may have in place.

A more subtle form of this bad practice is when a programmer doesn’t validate if data conforms to business rules right when it enters the system. Instead, such a programmer validates data at some other point in time, perhaps when the data is actually used. Of course, it’s often too late then to correct matters and afterwards the location which allowed for this invalid data is hard or impossible to find.

Mixing business logic and view code

Not separating business- and view code is another frequently encountered practice. It’s a major cause of creating spaghetti from code, which makes bug fixing and applying changes much harder than they should be. This bad practice is especially common for people with a PHP background, where the community more or less seems to encourage this practice (or at least doesn’t discourages it as much as in e.g. the Java or .NET communities).

One major problem with this bad practice is that beginning developers don’t always want to adopt a more sane MVC approach. It’s very much true that the MVC pattern may be overkill for small applications. However, many larger applications tend to be grown out of smaller ones. On top of that, for a new programmer the one or two pages he makes at first often seem to be the entire world, even when the application which is going to include these pages already has perhaps 500 other ones. Seeing the rest of the world is a skill often learned only over time.

For Java EE, an early effort by Sun to gently push the programmer into this MVC model was JSTL. In JSTL the programmer is presented with a number of tags and an expression language (EL) to define the rendering. JSTL contains conditionals, variables, and looping constructs. It should be very clear that these are solely meant to be used for rendering and nothing else. Or isn’t that so clear? A couple of years ago I asked one programmer to stop putting business logic in JSP pages using Java scriptlets and start using JSTL. After putting up some initial resistance, he finally agreed and went back to his work. When I looked through his next CVS commit, I was in for a surprise though. All the business logic was still exactly there in the JSP page, but this guy had simply rewritten the Java scriptlet code into JSTL tags! Needless to say that expressing business logic in the view layer through JSTL is an even worse practice.

Well, I’ll leave it to that today. Stay tuned for the next installment. 

Arjan Tijms 


Eclipse en Mac OS X

23 januari 2007, door edwin.metselaar

Afgelopen week heb ik getracht Eclipse aan de gang te krijgen op Mac OS X. Uiteindelijk draait het wel, maar er waren de nodige hobbels op de weg. We gebruiken trouwens SVN. De eerste stappen gingen gemakkelijk genoeg:

  • downloaden Eclipse voor Mac
  • downloaden MyEclipse plugin
  • aanpassen memory settings
  • Tomcat eraan hangen
  • aanmelden op de svn (met username/wwoord) en checkout

Vervolgens probeerde ik een simpele aanpassing te doen in een stukje sourcecode. Deze comitten – error. Nog eens proberen – error! Hmmm – misschien toch iets foutgegaan tijdens installatie. De hele procedure opnieuw gedaan. Weer die error tijdens comitten. Damn..

Vervolgens nog eens opnieuw, maar dan met de Subclipse plugin van Polarion in plaats van de MyEclipse plugin. Ik had het vage vermoeden dat die MyEcplise het op de 1 of andere manier niet goed doet op de Mac. Zou nergens op slaan, aangezien het Java is, maar goed. Weer vage errors tijdens comitten: NullPointerException
Vervolgens met mijn useraccount op een werkend Ecplise installatie op Linux geprobeerd – ook een error. Gelukkig – het ligt dus waarschijnlijk aan de serverkant.
Het issue bleek te zijn dat ik wel leesrechten op het filesystem had van de svn server, maar geen schrijfrechten. Blijkbaar gaat het op een vrij laag nivo fout en kan Eclipse de error niet opvangen en doorgeven. Errug jammer van de verspilde tijd, maar wel weer een goede les geleerd.


Programmeur junior – M4N – Amsterdam

22 januari 2007, door edwin.metselaar

Bij M4N in Amsterdam worden Java programmeurs gezocht – ook studenten en stagiaires kunnen hier aan de slag.

Taken & verantwoordelijkheden

  • Ontwikkelen van nieuwe functies en verbeteren van de online software applicatie
  • Het verbeteren of verminderen van het aantal stappen van het gebruik van de website
  • Nieuwe concepten bedenken, programmeren, testen en verbeteren
  • Efficiëntere querys schrijven. Query tijd terug brengen van 5 naar 1 seconde
  • Automatische e-mails systeem maken om gebruikers op de hoogte te houden
  • Verbeteren van systeem om online advertenties te beheren
  • Systeem wijzigen voor internationaal gebruik, zoals talen maar ook betaal methodes
  • Categorieën indelingen websites verbeteren
  • XML koppelingen naar online boeking systemen

Profiel

  • Jonge, enthousiaste medewerker met java of PHP ervaring die bereid is veel te leren en zich verder wil verdiepen in programmeren van complexe systemen
  • Kennis van Java, SQL en databases zoals Mysql of Postgresql is vereist
  • Kennis van en ervaring met programmeren voor het internet zoals PHP of JSP is vereist
  • Basis kennis van UNIX of LINUX
  • Kennis van C of C++ is een pre
  • In staat gestructureerd en gedocumenteerd te werken
  • Passie voor automatiseren en/of versimpelen van bestaande software

Programmeur JAVA J2EE – M4N – Amsterdam

22 januari 2007, door edwin.metselaar

Bij M4N in Amsterdam worden Java programmeurs gezocht. We zijn op zoek naar iemand die programmeert in de hoofdapplicatie van M4N, maakt de applicatie functioneler en gebruiksvriendelijker. Je programmeert in Java met behulp van Tomcat, MyFaces en Hibernate. Verder maak je gebruik van Quartz (scheduling), OSCache (caching) en verschillende Apache Commons libraries. Zie java vacature


Start site

3 november 2006, door development

Hi mede web gebruikers,

Zoals jullie zien is dit de start van deze nieuwe web-site.
Welke gevult gaat worden over informatie mbt java.

Ik hoop dat iedereen er veel plezien aan beleeft.
Groeten,
Willem


best counter