Showing posts with label String. Show all posts
Showing posts with label String. Show all posts

Monday 9 July 2007

space is too much


/**
* Return the concatenation of first name and last name separated by a space.
*/
public String getFullname() {
String s = "";

if (this.getFirstName() != null) {
s += this.getFirstName() + " ";
}

if (this.getLastName() != null) {
s += this.getLastName();
}

return s;
}

Let's say that firstName = 'Pitt' and lastName = 'Dirk'. We got "Pitt Dirk". And what if the firstName is null, we got " Dirk". Hum, less good.

And what if both are null, we got " ", a space!


This f**king space mess up our database. The better, this kind of method are copied/pasted every where the same behavior was needed.


What do we need then ? A nice join method that concatenate elements of an Object array inserting a separator between elements and ignoring null and/or empty string.

Wednesday 20 June 2007

Is empty String ?

How to test that a String is empty?

A lot of people use:


myString.equals("")

Some use:

"".equals(myString)

Few use:

myString.length() == 0

Fewer use:

myString != null && myString.length() == 0

Lazy people use:

org.apache.commons.lang.StringUtils.isEmpty(myString)

Which one is the best solution ?

I tell you ! Be lazy ! Knows libraries like you learn new word from dictionary.
Why ? Because, apache people ARE good. Because it is already done by another. Because it is free.

Else? Use

myString != null && myString.length() == 0

because a String might be null and because it is really fast to test the String length instead of its content.

Thursday 14 June 2007

Code completion and a lazy developer

(Integer) Integer.getInteger("12345")

Wow, that a nice stupid code. I lost 1 hour because of it. Thanks to YOU! The static Integer.getInteger(String) method return the value of a SYSTEM, I repeat a SYSTEM, property as an Integer. Hey! Lazy developers, read the javadoc before code completion.

Use this instead:

(Integer)
Integer.valueOf(String)


or

(int) Integer.parseInt(String)

Intro

This blog is about all stupid line of codes wrote by java developers (mostly). I will comment why they're stupid.

Let's start:

new String("").toString();
It is a really usefull code. Just to be sure that we've got an empty String. Yes, why not complete it like that just to be sure we have an empty String.
new String("").toString().substring(0, 0).trim();
Of course it is a stupid code. You want an empty String.
""
Got it.

It is stupid to do so because "" will create a new instance of String(), new String("") will do the same and toString() is just a shortcut to this String.