Monthly Archives: May 2015

If you do it do it right

This is a philosophical or ethical command. Very general. It is something like “fail fast”. The reason it came up to my mind is that I wanted to compile and release License3j using Java 8 and JavaDoc refused to compile during release build.

This package is a simple license manager, which has some established user base who require that I keep up with the new versions of BouncyCastle. It itself being a cryptography package should not be outdated and programs are encouraged to use the latest version to avoid security issues. When I executed mvn release:prepare I got many errors:

[ERROR] * <p>
[ERROR] /Users/verhasp/github/License3j/src/main/java/ error: unexpected end tag: </p>
[ERROR] * </p>
[ERROR] /Users/verhasp/github/License3j/src/main/java/ warning: no @param for args
[ERROR] public static void main(String[] args) throws Exception {
[ERROR] /Users/verhasp/github/License3j/src/main/java/ warning: no @throws for java.lang.Exception
[ERROR] public static void main(String[] args) throws Exception {
[ERROR] /Users/verhasp/github/License3j/src/main/java/com/verhas/licensor/ warning: no @param for expiryDate
[ERROR] public void setExpiry(final Date expiryDate) {
[ERROR] /Users/verhasp/github/License3j/src/main/java/com/verhas/licensor/ warning: no description for @throws
[ERROR] * @throws IOException
[ERROR] /Users/verhasp/github/License3j/src/main/java/com/verhas/licensor/ warning: no description for @throws

New JavaDoc Wants You DIR

The errors are there because the java doc of License3j is a bit sloppy. Sorry guys, I created the code many years ago and honestly it is not only the java doc that could be improved. As a matter of fact one of the unit tests rely on network and the reachability of GitHub. (Not anymore though, I fixed that.)

The new Java version 8 is very strict regarding to JavaDoc. As you can see on the “Enhancements in Javadoc, Java SE 8” page of ORACLE:

The javadoc tool now has support for checking the content of javadoc comments for issues that could lead to various problems, such as invalid HTML or accessibility issues, in the files that are generated by javadoc. The feature is enabled by default, and can also be controlled by the new -Xdoclint option. For more details, see the output from running “javadoc -X”. This feature is also available in javac, although it is not enabled by default there.

To get the release working I had the choice to fix the JavaDoc or to use the configuration


in pom.xml. (Source is stackoverflow.)

But You Just Won’t DIR

You can easily imagine that you will opt for the second option when you are under time pressure. You fix the issue modifying your pom.xml or other build configuration and forget about it.

But you keep on thinking about why it is the way like that? Why is the new tool strict by default? Is it a good choice? Will it drive people to create better JavaDoc?

(Just for now I assume that the aim of the new behavior was to drive programmers to create better JavaDoc documentation and not simply to annoy us.)

I am a bit suspicious that this alone will be sufficient to improve documentation. Programmers will:

  • Switch off the lint option.
  • Delete JavaDoc from the source.
  • Write some description that Java 8 will accept but is generally meaningless.

or some of them will just write correct java doc. Some of them who were writing it well anyway and will be helped by the new strictness. How many of us? 1% or 2%? The others will just see it as a whip and try to avoid. We would need carrot instead. Hey, bunnies! Where is the carrot?


Test JavaBeans

The first question is not how to test JavaBeans. The first question is not even if you need to test JavaBeans. The very first question is whether we need JavaBeans at all.

I am generally against JavaBeans, but when it comes to Java EE and services you can hardly avoid them. And that is the most I can tell about the first question.

The second question is if we need testing them. JavaBeans are usually generated code and the rule is that generated code should not be tested. Testing a generated code implicitly tests the code generator and not the generated code. If there is any error then the generator is faulty. And the generators have their own unit tests. Hopefully. I am, perhaps, still kind of junior having such beliefs.

So what is the conclusion: Shouldn’t you test JavaBeans?


Why? Because the assumption that JavaBeans are generated may be false. They are generated at first, but they are source code and source code has long life. Source code gets modified. By programmers. By humans. Humans make mistakes. Programmers are humans. More or less. You get it?

The usual modification to JavaBeans are small. Minor. Trivial. Trivial code should not be tested. Paying careful attention and generally lacking functionality (is setting and getting a real functionality?) makes tests unnecessary. WROGN again, just like my spelling wrong. Did you notice that at first? Probably not. That is also the case with the errors in the setters and getters. There may be only one single letter of typing. No problem, integrated development environments will do the code completion and voila! The typo proliferates and becomes legacy in the whole corporation. Does it cost? Sooner or later it does.

Code is used from JSP, where the editor does not spot the mistake, BeanUtils does not find the getter or setter and need extra code, but the names are already carved into stone and are guarded by dead souls. You try to change it and application developers in the corporate will bang on your door claiming back their good old cozy typo infested setter and getter.

What errors can there be? Presumably any as far as the possibility is concerned, but the most typical are:

  • Name of the setter or getter has typo and thus does not follow the JavaBeans standard.
  • Setter alters something else not only the field it is supposed to.
  • Setter does something and you can not get back that via the getter.

To test these, however, you should not write real unit test code. You should probably create some unit test class files, but they should not contain more than some declarative code. To do the real test you should use some libraries. A good start article is at stackoverflow. They mention Bean Matchers or Reflection Test Utilities. You can also give a try to JavaBeanTestRunner which tests that the setters do not mess up fields they should not, but does not check methods like toString(), or equals().

Generics Names

Generics type parameter names usually contain one, single capital case character. If you start to read the official ORACLE documentation on generics the first example is

 * Generic version of the Box class.
 * @param <T> the type of the value being boxed
public class Box<T> {
    // T stands for "Type"
    private T t;

    public void set(T t) { this.t = t; }
    public T get() { return t; }

The name of the generic type is T. One single letter, not too meaningful and generally against other identifier naming styles. It is widely used only for generics. Strange. What is the reason for that?

Here are the arguments I have heard so far:

  • A class or method does not need many type variable names, so you will not run out of the letters of the ABC.
    • Based on that reasoning we should also use one character method names? There should not bee too many methods in a class so we will not run out of the alphabet there as well.
  • It is not a problem that the one character does not inherently explain the type, since there is JavaDoc. You can explain what the type name actually stands for.
    • And we should also forget everything we have learned about clean code and variable naming. Code structure defines what the code does and since that is what it really is code structure is up-to-date. Naming (variables, methods, etc.) usually follow the change of code structure, since naming helps the programmer. Even though naming is many times outdated especially in case of boolean variables. It suggest many times just the very opposite what the real meaning is. JavaDoc is maintained and corrected some time after the code and the unit tests are finished, debugged and polished. In practice “some time after” means: never. JavaDoc is outdated, not available when reading the code as promptly as name itself thus should contain information you can not include into the code structure and well naming. Why would type names be an exception?
  • Types names bearing one character makes them distinguishable from variable, method and class names as well as constant names.
    • It is a good point. Type names have to be distinguishable from variable, method and class names. But I see no strong point why we should use different name casing from constants. There is no place where you could use a constant and a type or where it would really be confusing. They are used in totally different places, in different syntactical positions. If this is such a big pain in the donkey why do not we suffer from it in case of method and variable names? Method names are followed by () characters in Java? Not anymore as we get to Java 8!
  • But Google Code Style allows you to use multi character type names.
    • Oh yes. And it says that if you use multi character type names the name should have a T postfix, like RequestT, FooBarT. Should I also prefix String variables with the letters sz and Integers with i as in Hungarian Notation?

What then?

If you do not like the single character naming for generics you can name them with _ or $ prefix. This is a suggestion that you can see on stackoverflow. As for me: it is strange. Using the $ makes some “heimlich”, warm feeling reminding me of my youth when I was programming Perl. I do not do that anymore and for good reasons. Times changed, technology changed, I changed.

The $ is usually used by the compiler and some code generators to name generated fields and methods. Your use of $ on the Java source level may cause some difficulty for the compiler to find the appropriate name in case there is some naming collision, but the current version of the java compilers are fairly error prone in this respect. They just keep trying to find an appropriate name with some simple algorithm until they find a name that is not colliding with any Java source code name, so this will not be a problem.

Underscore: well, is really something that we used in old times instead of space. On old matrix printers the underscore character was printed so badly that you could not distinguish it from space and thus this was an ugly trick to have multi word variable names. Because of this underscore at the start of the name is a total anti-pattern imho, practically naming two things using the same name. It is almost like if the underscore character was not there at all.

You can also use T_ prefix as it is the convention in C++ and in C# (I am not familiar with those too much, I am not sure about that). But this is just as ugly as it is without the T.

My taste is to use meaningful names with the same conventions we follow in case of constants. For example to use

    public final class EventProducer<LISTENER extends IEventListener<EVENT>,EVENT> 
           implements IEventProducer<LISTENER, EVENT> {

instead of

    public final class EventProducer<L extends IEventListener<E>,E> 
            implements IEventProducer<L,E> {

Even though that is my personal, senior, professional, expert opinion I do not use it. Why? Because I work in an enterprise environment in a team. The gain to use something more readable than the official default is not as high as the damage of a debate and disagreement would be. In addition to that new hires have to get used to the local style and it also costs money. Using the usable, but not optimal global style is better than using a good local style. Live with it.

Can we go global?

You can try. That is the most I can say. It would have been better if the original suggestion setting the coding standard were better than the 1960’s style one letter approach, but this is already history. The damage has been done. And this is nothing comparable to the damage caused by the brilliant idea introducing null into OO.

We will live with the one character generics so long as long Java is alive. And since I am almost 50, it is going to be a longer period than my life span. Note that COBOL is still alive. We should expect nothing less from Java.

Using Junit Test Name

Name your tests

When we create Junit test usually there is no practical use of the name of the method. The Junit runner uses reflection to discover the test methods and since version 4 you are not restricted to start the name of the method with test anymore. The name of the test methods are there for documentation purpose.

There are different styles people follow. You can name your test in the given_Something_when_Something_then_Something style I also followed for a while. Other schools start the name of the method with the world should to describe what the tested object “should” do. I do not really see why this is significantly better than starting the name of the method with test. If all methods starts with the same prefix, then this is only noise. These days I tend to name the methods as simple statements about what the SUT does.

How to Access the Test Name?

Technically you are free to name your methods so long as long the names are unique. The name is usually not used in the test and the outcome of the test should not depend on the actual name of the test method. Even though there is a way supported by Junit to access the name of the method.

If you have a Junit Rule

public TestName name = new TestName();

you can refer to the object name in your test getting the name of the actual method as

String testName = name.getMethodName();


What can we use this for?

Sometimes the unit under test creates some huge structure that can be serialized as a binary or text file. It is a usual practice to run the test once, examine the resulted file and if that is OK then save it to use for later comparison. Later test executions compare the actual result with the one that was saved and checked by the developer.

A similar scenario may be used in case of integration tests when the external systems are stubbed and their responses can be fetched from some local test data file instead of querying the external service.

In such situations the name of the test can be used to create a file name storing the test data. The name of the test is unique and makes it easy to pair the data with the test needing it. I used this approach in the jscglib library. This library provides a fluent API to create Java source code. The tests contain some java builder pattern director code and then the resulted source code is saved into a file or compared to an already stored result.

To save the file the aux method getTargetFileName was used

	private String getTargetFileName() {
		String testName = name.getMethodName();
		String fileName = "target/resources/" + testName + ".java";
		return fileName;

To get the name of the resource the method getResourceName was used:

	private String getResourceName() {
		String testName = name.getMethodName();
		return testName + ".java";

After that loading and saving the generated Java code was a breeze:

	private void saveGeneratedProgram(String actual) throws IOException {
		File file = new File(getTargetFileName());
		FileOutputStream fos = new FileOutputStream(file);
		byte[] buf = actual.getBytes("utf-8");
		fos.write(buf, 0, buf.length);

	private String loadJavaSource() {
		try {
			String fileName = getResourceName();
			InputStream is = this.getClass().getResourceAsStream(fileName);
			byte[] buf = new byte[3000];
			int len =;
			return new String(buf, 0, len, "utf-8");
		} catch (Exception ie) {
			return null;

Generally that is the only example I know that you can use the name of a test method for other than documentation.

What you should not use the name for

There is a saying in my language: “Everybody is good in something. At least demonstrating failure.” The following example demonstrates such a failure.

I have seen a code that was encoding test data into the name of the test method. Access to the test method name was also implemented in a strange way. The programmer probably did not know that there is a supported way getting the name of the method. This lack of knowledge may have stopped him or her to do the evil, but this person was a genius. The test test method was calling static method of a helper class. This static method was throwing an exception, it also caught it and looked into the stack trace to identify the name of the caller method.

After it had access to the name the code applied regular expression to extract the values from the method name.


I do not know what the intention of the developers of Junit was giving us the class TestName. Probably there was some use case that needed the feature. I am certain that they did not provide the function because it was possible to do so. If you do not know what the API you provide is good for, you probably should not provide it just because you can. Novice programmers will use it wrong way more than good.

Also on the other hand: if you see something in a API that can be used it does not mean that you should use the feature. You should better understand the aim of the feature what it was designed for and use it accordingly.

Writing unit tests is more important than naming them. Debate on the naming of unit tests is useless so long as long there are no unit tests.

Write unit tests as many as needed, but not more.