The documentation problem

Introduction

As developers, the first thing we look for when integrating with an external system (or determining whether or not we should) is some sort of documentation. It’s an invaluable tool in increasing efficiency. Given that so many of us rely on documentation, why is it so difficult for us to write it?

Documentation isn’t the most fun part of our jobs, but it’s required for good communication. It’s easy to procrastinate on writing it, however, especially when the reader is internal, because we can always come up with a good excuse: “Documentation is never up-to-date anyway,” or, better yet, “It’s better if they have to come ask me about it.”

The real reason we’re so bad at documentation is that it’s hard to write it in such a way that it’s meaningful for the user, and that it’s difficult to maintain it because constantly tracking changes is tedious and untenable.

Of course, there are some good tools for documentation generation, like javadoc or Doxygen. These tools are great for generating API documentation, but poor with hand-written documentation defining scenarios, examples and best practices. Also, most examples are indeed part of the source code as comments, but they are usually never part of the source code, which makes refactoring ineffective.

What tool should I use?

Let’s step back and examine the core of what we need for documenting our projects and frameworks:

  • The ability to share best practices as easily as possible using hand-written examples
  • The ability to include snippets to illustrate our examples directly from our source code

This is where a tool like Projbook comes in being:

The steps are easy and seamless: Add Projbook using nuget to any of your projects, and it will bring all the default resources you need, like templates (that you can use as-is or customize), default pages as examples (that you will fill out), and default working configurations. Then, when you build your project, it will generate your documentation and drop it into your target directory. The hand-writing part is done in markdown files (called pages) where you can create references to your source code. These references are checked at build time, so if you break a reference, it will not compile, so it guarantees strong documentation-generation checking.

The benefits are:

  • You cannot have out-dated documentation because it targets your current build source code
  • If you break references, the build will fail, which helps you immediately find the issue
  • You can enable PDF generation
  • A default, ready-to-go, customizable working template is provided to you from the get-go

I want to use it, but how does it work?

It’s super simple. We’re assuming your project already exists, and your code base is available in front of you.

The first step is going to be adding a documentation project to you solution. Technically, you can reuse any project, but it’s recommended that you have a dedicated project to isolate the effort done in the documentation.

Projbook install

It will automatically set up everything that is required for documentation generation:
Projbook installed

In page1.md, you can see that two snippet references are already set. The first one extracts the full content, and the second extracts the content of the specified member. The following is the example of a method:

Page 1

Whole file content:
```csharp [Code/SampleClass.cs]
```

Just method content:
```csharp [Code/SampleClass.cs] -Method(string)
```

Let’s update it to extract our class content into our existing project:

# Hello world!!!

This is my awesome code:
```csharp [MyClass.cs] MyClass
```

Don’t forget to add a reference from your documentation project to your other project:
add reference

Now simply build and you’ll get your documentation in your output directory:
generated

Congratulations, you’re now all set! Refactor your snippet, and the next generation will have the latest version. Break you documentation references, and it will refuse to compile. Think even bigger by making this project run on your build server, and deploy your freshly generated documentation to a public space or internal documentation location. Ask for code reviews during documentation changes and keep track of who updated the content. With Projbook, you can now trust your documentation.

For any requests, please take a look at the current issue list, and give ideas or propose contributions, anything is very welcome.

Unicode source code

One day I have read that java source code is considered as unicode text.

Today I want to try that :

$ echo "\u0070\u0075\u0062\u006C\u0069\u0063\u0020\u0063\u006C\u0061\u0073\u0073\u0020\u0041\u0020\u007B\u000A\u0020\u0020\u0020\u0020\u0070\u0075\u0062\u006C\u0069\u0063\u0020\u0073\u0074\u0061\u0074\u0069\u0063\u0020\u0076\u006F\u0069\u0064\u0020\u006D\u0061\u0069\u006E\u0028\u0053\u0074\u0072\u0069\u006E\u0067\u005B\u005D\u0020\u0061\u0072\u0067\u0076\u0029\u0020\u007B\u000A\u0020\u0020\u0020\u0020\u0020\u0020\u0020\u0020\u0053\u0079\u0073\u0074\u0065\u006D\u002E\u006F\u0075\u0074\u002E\u0070\u0072\u0069\u006E\u0074\u006C\u006E\u0028\u0022\u0070\u006F\u0075\u0065\u0074\u0022\u0029\u003B\u000A\u0020\u0020\u0020\u0020\u007D\u000A\u007D" > A.java
$ javac A.java
$ java A
pouet

The unicode string is equivalents to the following code :

public class A {
    public static void main(String[] argv) {
        System.out.println("pouet");
    }
}

The perfect copy

The Prototype pattern allows to initialize a new instance with the state of an other.
It’s easy to implement this pattern when the fields of the instance are are of primitive types (int, …).
However, when the fields are references, It can be more complex to clone all the members recursively.

The JVM can help us do that more easily with serialization.

Thanks to ByteArrayStream you can write an object, and read the copy of the object.

You want to make the both classes cloneable :

class B {}
class A implements Cloneable {
    public B b = new B();

    @Override
    protected A clone() {
        try {
            return (A) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return null;
    }
}

We write two unit tests to check if the cloning is ok :

class CloneTest extends TestCase {
    private A a = new A();

   @Test
   public void testInstanceClone() {
       assertTrue(a != a.clone());
   }

   @Test
   public void testInstanceMembreClone() {
       assertTrue(a.b != a.clone().b);
   }
}

testInstanceClone passes but testInstanceMembreClone fails.

The clone seems good but the cloned references are the sames.

To create a perfect clone you can use the JVM and serializable objects as in this snippet :

class Cloner {
     static <T> T clone(T t) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(t);
            oos.flush();
            return (T) new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())).readObject();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

You can now use it in the clone method :

    @Override
    protected A clone() {
        return Cloner.clone(this);
    }

Now the two tests pass :).

This tip is not the most performant way to clone an instance but it’s the most reliable.

Should I use the template method or the command pattern to create a hook ?

Sometimes you need to have a hook in your code. This hook allows other developers to make some of their code be executed within yours.

void m() {
    System.out.println("my code");
    // hook
    System.out.println("my code");
}

You have two ways to do that. The first way is the template method pattern and the second is the command pattern.
The template method uses inheritance while the command pattern use composition.

If you use the template method your code will be as follows :

abstract class A {
    void m() {
        System.out.println("my code");
        hook();
        System.out.println("my code");
    }
    void abstract hook();
}

class B extends A {
    void hook() {
        System.out.println("hook code");
    }
}

You can also write a stub implementation :

class A {
    void m() {
        System.out.println("my code");
        hook();
        System.out.println("my code");
    }
    void hook() {}
}

class B extends A {
    void hook() {
        System.out.println("hook code");
    }
}

But Inheritance is static, thus solved at compile-time. If you want a dynamically (run-time) modifiable hook, you have to use composition. You can do that thanks to the Command pattern.

class A {
    private Command command;
    public A(Command command) {this.command = command}
    void m() {
        System.out.println("my code");
        if (command != null) command.hook();
        System.out.println("my code");
    }
}

interface Command { void hook(); }
class StubCommand implements Command { public void hook() {} } // Empty hook
class CommandImpl implements Command {
    public void hook() { System.out.println("hook code"); }
}

There is no particular solution but generally the most reusable solution uses composition.

Implement State pattern with enum

State pattern allow to choose the correct action related to the state of an object. The goal is to get rid of if/elseif and switch blocks.

You can replace constants which represents state by implementing the pattern as follows :

public class A {
    private int state = State.OPEN;

    class State {
        public static final int OPEN = 1;
        public static final int CLOSE = 2;
    }
}
public class A {
    private State state;

    interface State {}
    class OpenedState implements State {}
    class CloseState implements State {}
}

But now if you want to compare the state, you must use the instanceof operator.

You can do better with enum :

public class A {
    private State state;
    public A(State state) { this.state = state; }
    public State getState() { return state; }
    public void setState(State state) { this.state = state; }

    public void doSomething() { state.doSomething(); }

    public static void main(String[] argv) {
        A a = new A(State.CLOSE);
        a.doSomething();
        a.setState(State.OPEN);
        a.doSomething();
    }
    
    enum State {
        OPEN(new StateOpen()), CLOSE(new StateClose());
    
        private StateInterface stateInterface;

        private State(StateInterface stateInterface) { this.stateInterface = stateInterface; }
        
        public void doSomething() { stateInterface.doSomething(); }
    
        public static interface StateInterface { void doSomething(); }
        public static class StateOpen implements StateInterface {
            public void doSomething() { System.out.println("open"); }
        }
        public static class StateClose implements StateInterface {
            public void doSomething() { System.out.println("close"); }
        }
    }
}

How to customize dependency injection

Hi,

I often explain particular features of JSE but not JEE possibilities.
Today we’ll see how to make a custom injection with JEE.
This feature is not directly supported by JEE but with defaults interceptors it becomes possible.
The Steps are :
1/ Create the annotation which will be used to tag a member instance to inject.
2/ Write a default interceptor which acts at post construction. It must check if the annotation exists, and thanks to reflexion set the value.
3/ Use the annotation with your EJB.

Annotation definition :

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface InjectedValue { }

Interceptor implementation :

public class CustomInterceptor {
    public void inject(InvocationContext invocation) throws IllegalAccessException {
        Object o = invocation.getTarget();
        for (Field field : o.getClass().getFields()) {
            if (field.isAnnotationPresent(InjectedValue.class)) {
                boolean previousAccessibility = field.isAccessible();
                field.setAccessible(true);
                try {
                    field.set(o, 42);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                field.setAccessible(previousAccessibility);
            }
        }
    }
}

Interceptor declaration :

<interceptors>
    <interceptor>
        <interceptor-class>ejb.CustomInterceptor</interceptor-class>
        <post-construct>
            <lifecycle-callback-method>
                inject
            </lifecycle-callback-method>
        </post-construct>
    </interceptor>
</interceptors>

Using of the interceptor :

@Stateless
public class MyEJBBean implements MyEJBRemote {
    @InjectedValue
    private int myValue;
}

Dependency injection is the foundation of IOC (Inversion of control) and with interceptors you can write your dependency injections.
Defaults interceptors are applied on all EJBs, but if you want, you can attach interceptor to a particular EJB.
With AOP (Aspect Oriented Programming), and thanks to pointcuts, you can precisely identify a method signature and act on it.
We’ll maybe see that later.

Final keyword is not used enough

Mostly when I see the final keyword, it is for defining a constant reference, whereas this is not the main use of “final”.

Remember that the final keyword is applied to references but not to objects. That means objects are mutable but we can’t reaffect an instance to the reference.
This behavior is the same if I use final on variables or parameters.

Now check this code :

void m(String p) {
    // Here my code
}

No problem, I’ve “p” parameter of type String and I can use it, but I can reaffect “p” :

void m(String p) {
    p = "new value";
    // Here my code
}

What’s the problem ? There is no problem, this code compiles and runs fine, but the question is why should I do that ?
Because reaffectation is like creating a new variable, I probably have other choices that reaffect the “p” reference.
This reaffectation can be difficult to see and It’s always a good idea to have immutable references when you can to avoid side effects.

We can talk about final members. If there is no reason to change a reference, make it final as in the following code :

public class C {
    private final List<String> data = new ArrayList<String>();

    public void m(final String p) {
        // Code here
    }
}

.

What’s my ressources future when I get java.lang.OutOfMemoryError ?

A finally block are always called, even if the function returns in either the try block or the catch block.
But if my application shutdowns quickly (when I get java.lang.OutOfMemoryError, for example), can I trust in my finally block ?

Try a single test as follows :

public class HeapSpaceTest {
        public static void main(String[] argv) {
                List<String> l = new ArrayList<String>();
                try {
                        while (true) {
                                l.add("bim");
                        }
                } finally {
                        System.err.println("finally");
                }
        }
}

And you get :

[kaz@akina test]$ java HeapSpaceTest
finally
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at java.util.Arrays.copyOf(Arrays.java:2760)
	at java.util.Arrays.copyOf(Arrays.java:2734)
	at java.util.ArrayList.ensureCapacity(ArrayList.java:167)
	at java.util.ArrayList.add(ArrayList.java:351)
	at HeapSpaceTest.main(HeapSpaceTest.java:9)

Yeah thanks very much finally, I trust in you !

Delude java about generic with two step compilation

After “Generics inside byte code ?” we can be curious about the behavior of byte code at runtime.

After compilation generics disappear, and javac is aware of the real generic type, but can I delude java at runtime ?
Try to perform this tasks :
1/ Compile two classes. One of these use List<String>

public class L {
    public void doSomething(List<String> l) {
        l.add("str");
    }
}
public class M {
    public static void main(String[] argv) {
    new L().doSomething(new ArrayList<String>());
    }
}

2/ Recompile just the class which uses List<String> and modify it to use <Integer>

public class L {
    public void doSomething(List<Integer> l) {
        l.add(42);
    }
}

3/ Replace the old .class version

You can now run your application which calls doSomething(List<Integer> l) from doSomething(new ArrayList<String>()).

It’s not a good practice, it’s juste a trick which allows a better understanding of java 😉

IntelliJ, a beautiful IDE

I’ve recently discovered IntelliJ Idea (thanks to Julien), the most powerful IDE I’ve ever seen.

IntelliJ can manage completion and syntaxical coloration inside strings representing jpql, aop pointcut, regex. Ant & Maven are natively supported and CVS/SVN/GIT too, and many other things …

I can speak about this IDE and its benefits but I would like to speak about IDETalk, a feature of IntelliJ which allows connection to jabber networks. Now, I can chat with my google talk account through IDETalk, directly from my favorite Java IDE …

To configure your google account on IntelliJ :
1/ Click on the IDETalk button at the right
IDETalk logo

2/ Click on add account and configure your google account
IDETalk account configuration

3/ You can now chat with your contacts 😉
IDETalk contact list

Some persons can find this feature to be useless but I found that to be very fun.

Thanks JetBrains, thanks Julien 😉