Показаны сообщения с ярлыком java tips. Показать все сообщения
Показаны сообщения с ярлыком java tips. Показать все сообщения

5/13/2010

Why the devil invented javadoc?

It is believed that a good program should be well documented.

SUN company even creared a special format javadoc - "a standard for documenting classes Java". In fact, it was quite a common case in my experience, when a code did not pass Code Review just because some of its methods lacked comments.

Today I'll tell you why the comments are evil.

Start from example


Consider the real example from live code. This is a real code written quite diligent programmer who was not lazy and wrote a commentary on his method. Pleased with himself, he went to pour himself a cup of coffee from the machine. While he is going to the office kitchen, let's take a look at what we have here.

public class AddressUtil {
/**
* Format string as address, expected input
* format:"EE ; ;Tallinn;Narva mnt;120B;831;10127"

*
* @param flatAddress
* @return Formatted address

*/
public static String toString(String flatAddress) {......}
}


Excellent! We have a correctly designed a format javadoc, from which a special program can generate HTML-documentation. As it is easy to see that (theoretically) makes this method.

Where is the hidden devil?


But where are those little things that hid the devil? And here they are:

  1. Very soon this documentation becomes outdated, because some other developer will come and change the code, but forget to change the documentation. It may even be the same developer, because while he was standing in line for coffee, it occurred to him that he forgot to process one rare case. When he comes back, he adds the desired IF into the code, but forgets that he already has javadoc, which must be maintained.

  2. This documentation does not describe the mass of cases: how the method behaves, if the input comes null or empty string? What if address contains house number, but misses apartment number (ie bourgeois took home a whole)? What's that empty parameter between the "EE" and "Tallinn"?

  3. Documentation doesn't describe what this method returns.

  4. There are three extra lines in the documentation: "*", "@ param flatAddress" and "@ return Formatted address". Just think: they occupy a large part of the documentation, and they are absolutely useless!

It can be summarized in two words: "Comments lies"! That's all. You cannot do anything with this, except the cases when you have a special position for people how review all the documentation periodically. Damn, do you really want to do that?

The Magic


Now let's do a focus-pocus and create The Magic. We make a few magical passes. Sim salyabim, Ahalan-mahalay, Lyaska-masyaski ....


  1. Pass # 1: Everything that is written in red, we turn to the name of the method: toString -> formatAddress.

  2. Pass # 2: Everything that is written in blue, transfer to unit-test.

  3. Pass # 3: (my favorite) The text, written in green, wipe fuckin. Do not spare him, he was born in vain!

What we did in the end?

public class AddressUtil {
public static String formatAddress(String flatAddress) {......}

@Test public void testFormatAddress() {
assertEquals("Narva mnt 120B-831 10127 Tallinn",
AddressUtil.formatAddress(
"EE ; ;Tallinn;Narva mnt;120B;831;10127"));
}

}


What the new version better than the old?

  1. It's just shorter: there are now 4 rows compared to former 8.

  2. This test will never becomes obsolete, because it will run automatically every time you build the project, and if the programmer change the code, and forget about the method, it immediately pops up.

  3. You can describe all the rare cases: the empty string, missing keys, invalid values, etc.



In short,
GOOD TITLE + TESTS = DOCUMENTATION


rather, executable documentation, or documentation that can not only read but also "run", automatically checking that it is still adequate.

It is said that Confucius was a poster over the bed:

Convert comments to executable documentation



Afterword



I'm just afraid that our brave programmer, returning from the kitchen, will not understand the focus, because he had not seen our magical movements. He will get mad only because SOMEONE Nagle has deleted his comments, and he will try to find us and kill for such subversive activities.

... And his coffee gets cool in the meantime. Well, no so bad: after all, coffee, they say, is harmful. So, we did today did one good thing.



Andrei Solntsev

http://funny-java.blogspot.com/

PS. Well, I must admit the documentation is still needed in some cases, for example, when you writing public API, which other people will download and use. This API is hardly going to be changed, so it's possible to maintain the documentation. But you must remember that documentation is not just comments in code - this is a part of you product, which requires resources for creation and maintenance. Tule of thumb: prefer NOT to writing comments. Write them only if it's really unavoidable.

12/23/2009

HireBug

On the last DevClub meeting I presented a HireBug - a "server-side Firebug".

This is presentation in russian:
http://www.slideshare.net/asolntsev/hire-bug

Update: presentation video (also in russian):
http://www.devclub.eu/2009/12/29/andrei-slontsev-hirebug/

5/20/2009

ThreadSafeDateFormat

Problem
As known, Java class SimpleDateFormat is not Thread-safe.
It means that you cannot declare a static member DateFormat in class:

private static final DateFormat DATE_FORMAT = new SimpleDateFormat( DATE_PATTERN ); // WRONG!

Using this member by 2 concurrent treads will lead to error.

What is a solution?
One solution is to create new SimpleDateFormat( DATE_PATTERN ) each time you need to parse a date. Another solution is to create a Thread-safe version of DateFormat.

That's it:


import java.lang.ref.SoftReference;
import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
* Thread-safe version of java.text.DateFormat.
* You can declare it as a static final variable:
*
* private static final ThreadSafeDateFormat
* DATE_FORMAT = new ThreadSafeDateFormat( DATE_PATTERN );
*/
public class ThreadSafeDateFormat extends DateFormat
{
private static final long serialVersionUID = 3786090697869963812L;

private final String m_sDateFormat;

public ThreadSafeDateFormat(String sDateFormat)
{
m_sDateFormat = sDateFormat;
}

private final ThreadLocal m_formatCache = new ThreadLocal()
{
public Object get()
{
SoftReference softRef = (SoftReference) super.get();
if (softRef == null || softRef.get() == null)
{
softRef = new SoftReference(
new SimpleDateFormat(m_sDateFormat) );

super.set(softRef);
}
return softRef;
}
};

private DateFormat getDateFormat()
{
return (DateFormat) (
(SoftReference)m_formatCache.get()).get();
}

public StringBuffer format(Date date,
StringBuffer toAppendTo, FieldPosition fieldPosition)
{
return getDateFormat().format(
date, toAppendTo, fieldPosition);
}

public Date parse(String source, ParsePosition pos)
{
return getDateFormat().parse(source, pos);
}
}



The main idea of this class is storing separate instances of SimpleDateFormat for separate Threads in ThreadLocal variable. If 2 concurrent threads try to parse date, the will use 2 different instances of SimpleDateFormat.

3/14/2009

Functional Programming in Java

This is my seminar about Functional Programming and using its ideas in Java.

It was done in year 2006.

http://www.slideshare.net/asolntsev/functional-programming-in-java

3/05/2008

How to find which jar file contains your class at 'runtime'

It's often happening when you want to get know where JVM takes some class from.
If this class potentially can be located in several folders/jars, you never know which one of them JVM uses.

There is a simple method allowing this:

/**
* Method returns code source of given class.
* This is URL of classpath folder, zip or jar file.
* If code source is unknown, returns null (for example, for classes java.io.*).
*
* @param clazz For example, java.sql.SQLException.class
* @return for example, "file:/C:/jdev10/jdev/mywork/classes/"
* or "file:/C:/works/projects/classes12.zip"
*/
public static String getCodeSource(Class clazz)
{
if (clazz == null ||
clazz.getProtectionDomain() == null ||
clazz.getProtectionDomain().getCodeSource() == null ||
clazz.getProtectionDomain().getCodeSource().getLocation() == null)

// This typically happens for system classloader
// (java.lang.* etc. classes)
return null;

return clazz.getProtectionDomain()
.getCodeSource().getLocation().toString();
}

2/08/2008

Null-Initialization in Java

In many languages (C++), uninitialized variables lead to errors. So, it's considered to be a good style to initialize every variable with 0 or null.

however, in Java it's quite the opposite.
Initialization with null is not recommended for those class members that should not be null.

Instead, it's recommended to declare those members final and initialize only once with an adequate value.


See example below.


Bad practice:

private CCollectorTarget m_collectTrg = null;

private CCollectorSchema m_collectSchm = null;

private CCollectorProject m_collectPrj = null;

private CCollectorFiles m_collectFiles = null;

public CCollectorData( CCollectorTarget collectTrg,
CCollectorSchema collectSchm,

CCollectorProject collectPrj,

CCollectorFiles collectFiles )

{

m_collectSchm = collectSchm;
m_collectTrg = collectTrg;
m_collectPrj = collectPrj;
m_collectFiles = collectFiles;
}

Good practice:

private final CCollectorTarget m_collectTrg;
private final CCollectorSchema m_collectSchm;
private final CCollectorProject m_collectPrj;
private final CCollectorFiles m_collectFiles;

public CCollectorData( CCollectorTarget collectTrg,
CCollectorSchema collectSchm,

CCollectorProject collectPrj,

CCollectorFiles collectFiles )

{

m_collectSchm = collectSchm;
m_collectTrg = collectTrg;
m_collectPrj = collectPrj;
m_collectFiles = collectFiles;
}

This technique has additional advantages: java compiler detects cases when you

  1. forget to initialize variable, or
  2. try to initialize it more than once.