Blog

The configuration config-smartics-pmd for PMD has been released with version 2.0.0.

This update is based on PMD 5.0.2 to be used with maven-pmd-plugin 3.0.1.

The Java library smartics exception has been released with version 0.11.2.

This bugfix release updates the dependencies to the qdox and javassist libraries. It is the basis for the update of the exceptioncodes-maven-plugin to 0.10.2 which fixes a bug when dealing with multi module projects that share code implementation.

For details on this library please visit the project's homepage. For changes regarding the exceptioncodes-maven-plugin for Maven please have a look at the release notes.

Constructing complex objects for tests can be simplified by builders. If these builders are not part of the API, they can be added to the test classes and exported via the Maven Jar Plugin.

 

We cannot add these test helper classes to another project, since we want to use them in the project’s unit tests, too. Therefore we started to use the artificial ‘top-level’ domain help in our projects to group all our test helpers to be exported and used by other projects for writing unit tests.

  help.de.smartics.something.XBuilder
  help.de.smartics.something.YBuilder
  ...

The Maven configuration to create an archive of test helpers and attach it as an additional artifact looks like this:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-jar-plugin</artifactId>
  <executions>
    <execution>
      <id>testhelper</id>
      <goals>
        <goal>jar</goal>
      </goals>
      <configuration>
        <classifier>testhelpers</classifier>
        <classesDirectory>
          ${project.build.testOutputDirectory}
        </classesDirectory>
        <includes>
          <include>help/**</include>
        </includes>
      </configuration>
    </execution>
  </executions>
</plugin>

We add the classifier testhelpers to identify the artifact as containing our test helpers. The classifier tests is still used, if we export our test case classes.

For more information about writing and organizing tests, please have a look at Growing Object-Oriented Software Guided by Tests by Steve Freeman and Nat Pryce!

Please note

 

Due to MNG-3559 you will encounter difficulties on multi-module builds when creating a site. The workaround is to run phase install before phase site (or try to avoid modules, see Nicholas Williams’ comment on MNG-3559 for details).

mvn install site

The exception design best practice Design Exception Class Hierarchy provides two reasons to design a new exception class for a Java application or library:

  1. You want to catch an exception and handle it individually.
  2. You require specific information to be passed to the exception to document the context in which the exception has been raised.

 

 

For a discussion, why having more than one reason may put us into trouble, have a look at Why is having two Reasons a Problem at all?.

Not a Problem for the Java Core Library

Java exceptions in the core library do not have to tackle the second reason. They usually do not contain data fields and therefore add specific information directly into the message text (or do not have any message text at all). Examples are NullPointerException or MalformedURLException. It is the responsibility of the developer, who throws the exception to text the message individually.

throw new IllegalStateException(
  String.format("This is my message to signal"
      + " that '%s' is not initialized properly.", it));

When there is additional information as part of the exception instance that can be retrieved by getter methods, this information is not necessarily part of the message text. SQLException is an example for this kind of exception. Exception information and the exception message are independent of each other. Therefore you can reuse the same exception class in many situations. So it is no big deal that this exception serves two purposes.

Something to consider for smartics-exceptions

smartics Exceptions puts much effort to help application developers to design exceptions with searchable exception codes and meaningful messages. The act of throwing of the exception should be easy and detached from the work of wording the encountered problem into a message text. Therefore smartics-exceptions moves the message out of the exception class and associates the message with the exception by an exception code. The developer now only uses the exception and the code, adds the relevant information to it and has not to bother with any message texts.

throw new NotInitializedException(COMPONENT_A_CODE, it);
 

Well, in fact someone has to write the exception message text. So the developer adds some more artifacts (code enum, message bundle and the exception class). But these steps have to be taken whenever a new exception class has to be created. You'll find an overview on this in What is smartics-exceptions all about?

So why are the two reasons to design an exception type a problem for smartics-exceptions? Since you attach the message to the exception type by the use of a code, the chance of reuse of the same exception is reduced. The exception code points to a message template that requires specific information for its placeholders. This is especially true, since the messages are often quite detailed and therefore require specific pieces of information to merge into the message template. So although you may change the code to select a different message, the message template often does not match the provided information of the exception type. Different messages call for different information and therefore you end up with writing different exception types (i.e. Java classes).

As we have shown above, the exceptions of the Java editions 'solve' this problem by urging the developer to assemble the message text on a ad-hoc basis. That way the information stored inside the exception is decoupled from the message text. And all that is really important is the type of the exception to be caught.

Additional Layers of Abstraction

 

 All problems in computer science can be solved by another level of indirection ... except for the problem of too many layers of indirection.

David Wheeler (first part), Kevlin Henney (corollary)

 

Having two reasons for creating a new exception class should be avoided, since it makes the design more complex, less intention revealing and may lead to conflicting goals. The problem stems from the fact that an exception type has two responsibilities that are both equally stressed by smartics-exceptions. If we want to decouple these two responsibilities, we would have to attach a common information instance to the exception type during initialization. This approach has the following form:
final MessageBean info = 
  new MySpecialExceptionMessageBean(MyCode.X, "Arg1", arg2, arg3);
throw new MyException(info);

In this scenario you would have to write a new exception info container type (we call it message bean, although it is not necessary to actually add getter methods to it) for each context that provides its own set of information. With static methods and imports this can be shortened to:

throw new MyException(info(MyCode.X, "Arg1", arg2, arg3));

We solve our problem by adding additional levels of abstraction. It is just a matter of how much code we want to write to ease the act of throwing of exceptions and enabling single responsibilities.

The approach of providing separate message beans is currently supported by smartics-exceptions as an alternative way of designing exceptions. Please refer to Separation of Exception Type and Information for more information on this topic.

Worth the Effort?

Under which conditions is the introduction of message bean types worth the effort?

If you are using the same message bean in many contexts, this usually pays off. If you have many message beans that you only use in one or two situations, then it is only a matter of coding style and readability.

If you are using the message bean in different situations, especially in the case of logging, you my see the message bean not as an additional effort, but as an opportunity to store the relevant information of a certain context. If it is possible to design these message beans this way, they may be used by a class of exceptions (e.g. all exceptions dealing with security) and logging statements (logging in each security service). The containers are in these scenarios not designed for a specific occasion (as exceptions are), but for a context in which different kinds of exceptions and logging events occur. The context in this case naturally allows to specify more information than is actually reported in an exception or log event. This allows reuse and makes this approach less work intensive.

But this can also lead to more complicated code, if the context of information that is passed to an exception is only partially filled. If looking at the code does not reveal if all information required by the exception is actually present, you may find yourself looking at a log that lacks the information required to analyze an error condition. In this case, writing specific message types may make your maintenance time easier.

Since neither approach may fit each situation within your application, extending AbstractMessageException or AbstractMessageRuntimeException allows to construct a solution for each exception situation individually.

 

You may have a look at two example projects that use smartics-exceptions: One is a library called smartics-exceptions-sample-lib, the other an application that uses this library: smartics-exceptions-sample-app

Conclusion

smartics Exceptions allows to separate between exception types and exception context information using message beans. It is a design decision whether to use this approach or not. The decision can be made for each exception type of a project individually.

The Java library smartics exception has been released with version 0.11.1.

With this release users of the library may choose between the classical and the message bean approach for each exception type individually.

For details on this library please visit the project's homepage, for changes since the last version, please consult the release report.

In this article I want to show, why it is a problem to have two (or more) reasons for a change or for the creation of something.

The event that made me think about this topic was an email of a friend of mine discussing some design issues in our exceptions library. He pointed out that there are two reasons for creating an exception class for Java:

  1. You want to catch an exception and handle it individually.
  2. You require specific information to be passed to the exception to document the context in which the exception has been raised.

I want to explain the problem with having two reasons in the light of

  1. Reducing Complexity
  2. Revealing Intention
  3. Reducing Conflict
 

If you are interested in a more detailed discussion on the problem according exception handling and our smartics exception library, please refer to Exceptions have two Responsibilities.

Reducing Complexity

The Single Responsibility Principle (the S in SOLID) is a design principle to make program code more understandable and easier to maintain.

There should never be more than one reason for a class to change.
Robert C. Martin

So reducing complexity by having only one responsibility is one of the reasons to have only one reason for a change.

Revealing Intention

In his book Practical API Design Jaroslav Tulach encourages to create APIs whose elements have a clear intention. One way to express expected API use is through modifiers of methods.

Access ModifierPrimary MeaningAdditional Meanings
publicMethod to be called by external clients of the API.Can be overridden by subclasses. Can also be called by subclasses.
public abstractMethod has to be implemented by subclasses.Method can be called by external clients.
public finalMethod to be called.None.
protectedMethod can be called by subclasses.Method can be overridden by subclasses.
protected abstractMethod needs to be overriden by subclasses.None.
protected finalMethod can be called by subclasses.None.

Source: Practical API Design, p. 172ff

Having only one meaning makes the intention clear. There is only one reason for the existence of a method.

Reducing Conflict

In her keynote The Power of Abstraction at QCon 2013 Barbara Liskov speaks about (beside other very interesting stuff) inheritance having two purposes (starting from minute 38, if you want to jump right into it):

  1. Implementation Technique
  2. Type Hierarchy

You can see inheritance as a way to provide a skeleton that indicates clearly, what has to be implemented to get things done faster. Basically you provide a type with a couple of methods to be implemented or overridden by subtypes and the task is done.

The second reason to use inheritance is again a design principle called Liskov Substitution Principle:

Objects of subtypes should behave like those of supertypes if used via supertype methods.

Barbara Liskov. The Liskov Substitution Principle

These two reasons conflict with each other. Where following the view of inheritance as an implementation technique is stressing the syntax, software development regularly heads into trouble, if it does comply with the second reason – which is purely semantic one. That is the reason why Barbara Liskov’s finding is the L in SOLID and a principle that is valued highly.

For this reason, reducing the possibility for conflicts, it would be better, if we had only one reason for selecting inheritance.

Conclusion

In a context where we are overwhelmed by alternative paths, it is a great relief to reduce our freedom of choice. At least as long as the one alternative that is most appropriate does not get cut off too early. But on the other side: a less optimal solution is often suitable enough in many circumstances. Getting things done cleanly is the way to go and deal with any technical dept as we have the knowledge to find a more suitable solution.

Trying to emphasis the notion of one reason is a benefit of any design. It leads us to solutions that are easier to understand, reduce the risk of doing something wrong and remove the danger of wasting time on decision making.

 


 

“Single responsibility principle” and the whole of SOLID are more or less for the non-thinking person. The SRP, as usually applied in OOP, is based on an either oversimplified or wrong understanding both of what responsibilities are and of what OOP is about.

Responsibilities, as they exist in the end user mental model, are system operations and have little to do with objects and nothing to do with classes. Neither objects nor classes have responsibilities: *roles* do. If you’re thinking responsibilities in terms of classes or objects, you’re just doing modules with instantiation. If you’re thinking of operations at the system level and role-level responsibilities, then you’re starting to think in an object-oriented sort of way.

See the many online materials by Trygve Reenskaug about this. You’ll find similar sentiments in Rebecca Wirfs-Brock’s latest book as well as in the Lean Architecture book.

James O. Coplien. (May 10, 2013 at 9:11 pm)

Dear Mr. Coplien,

thank you for your comment! I’m quite late with my response, but you gave me a long reading list and it took some time to catch-up. (wink) And I still have to admit that I am yet not fully through this list as I only read Mr. Reenskaug’s publications as far to get to realize that there are many treasures yet to dig up.

I cannot object to the points you addressed, but I would like to add a few comments.

SOLID

I agree that the SOLID principles are simplified, but none-the-less they form a tool to help beginners to start caring about design. To my experience they are the first step for software developers on their journey of learning software design. And with many tools, if applied by the “non-thinking” person, these principles will not automatically lead to “good design” (I put this in quotes since I do not specify what good design is). Probably by giving the false impression of being on a safe track, they may indeed wreak havoc. This is similar to designs where software developers apply each and every design pattern they read about. But this does not make those patterns worthless.

Maybe you are objecting to the naming of SRP as “principle”, if principles have to lead automatically to desirable results. Maybe the wording should have been “guiding rule”?

So if I understand you correctly: The SRP is about class design (“There should never be more than one reason for a class to change.”) and therefore it will not lead to a good OO design, where you set focus on the element’s roles and their associated responsibilities.

I have to agree. But I wanted to point out that we shouldn’t abandon all of SOLID – which my impression is, your first paragraph is all about.

Responsibility

When you emphasize the fact that only roles have responsibilities, you certainly help to get software designers on the right track. Your comment helped me to see this more clearly.

On the other hand, if you state that no other entities (to be fair: in your comment you restrict this to classes and – in parts – objects only) can possibly have responsibilities, I’m lacking the vocabulary to document the justification for the existence of a particular element. I’m currently reading George Fairbanks’ book “Just enough Software Architecture”. He writes:

“As you design a system, you allocate responsibilities to system elements. You can allocate responsibilities to elements of any model in any viewtype. […] System elements can have both functional and quality attribute responsibilities.” (p. 251)

Again it makes sense to emphasize focusing on each element’s role and reason about this role’s responsibilities. But is saying that an element has a certain responsibility not just a shortcut? If a single line of code checks that a user is who he pretends to be, is it wrong to say that the responsibility of this line of code is authentication? So I still have no solution how I should describe that some element’s justification for existence is its ‘responsibility’ to fulfill a requirement. I continue having this gut feeling that the “One-Reason-to-Change” thing is helping to organize code (not objects). And there seems to persist my misunderstanding.

Conclusion

Finally, on the bottom line, in response to your comment, I will try to make it more clearly when I talk about OO design and when I’m addressing “technical issues”, try to address how these aspects are connected, and put focus on roles.

Of course I missed some things. God is in the details! Maybe I just have to continue reading and learning – well that’s certainly a sure bet. (smile)

Thank you so much for your input!

Robert. (December 31, 2014 at 2:15 pm)

The Maven plugin Alias Maven Plugin has been released with version 0.3.3.

The improvement escapes the environment variables on windows boxes so that they are no longer expanded on the help page.

j7 = set JAVA_HOME="D:\java\edition\jdk1.7.0" ;; 
set PATH=D:\java\edition\jdk1.7.0\bin;
C:\Windows\system32;C:\Windows; ...
...
...

Is now reduced to:

j7 = set JAVA_HOME="JAVA_HOME_7";; set PATH=JAVA_HOME_7\bin;PATH

The Java library smartics exception has been released with version 0.10.0.

This library allows to design exceptions in your application and to generate reports on the error codes. The exceptioncodes-maven-plugin generates exception codes reports and has also been released to match the new features of smartics-exceptions.

One major change is the inclusion of ICU's MessageFormat. Now it is possible to use telling names for place holders instead of the numeric indices required by Java's message format class.

@ParentMessageParam("cause=0:message")
public class MyException extends BaseException {
  @MessageParam("2:host,3:port")
  private final URL url;
@ParentMessageParam("cause=0:message")
public class BaseException extends AbstractLocalizedRuntimeException {
  @MessageParam("1")
  private final String name;

You may now do this:

public class MyException extends BaseException {
  @MessageParam(":host,:port")
  private final URL url;
@ParentMessageParam("cause=causeMessage:message")
public class BaseException extends AbstractLocalizedRuntimeException {
  @MessageParam
  private final String name;

This will make it much easier if you add new properties to the base class later.

The message bundles will also be easier to read. The indexed version:

1000=The name is set to {1}. URL is ''{2}:{3}'': {0}

The new version with property names:

1000=The name is set to {name}. URL is ''{host}:{port}'': {causeMessage}

Thanks to ICU the composed messages are now also easier to handle:

  /**
   * Count of faults.
   *
   * @serial
   */
  @MessageParam
  private final int faultCount;
1001=The service has encountered {faultCount,plural,\
  =0{no faults}\
  =1{one fault}\
  other{# faults}\
 }.

 

Instead of our old proprietary format:

1001=The service has encountered {0}.
1001.0.0=no faults
1001.0.1=one fault
1001.0.m={0} faults

For more new message format features provided by ICU’s message format, please refer to their API documentation.

For details on this library please visit the project’s homepage, for changes since the last version, please consult the release report.

Taglets by Example

In recent posts we showed how to configure taglets within you Maven build to create visually appealing API documentation with Javadoc. In Using Taglets with Java 7 we showed how to tweak your configuration to get them running with Java 7.

Here we are giving some code samples to get you started using it. In the following five sections we show first the rendered example and then the code that produced it as part of the Javadoc comment. You may download a zipped Java file containing all examples shown below to quickly check your installation.

 

Please note that in the examples the end pre tag is ‘damaged’ since I had difficulties to render the examples. Adding the pre element to surround the code helps the Eclipse formatter to keep these sections untouched.

Note

 * <pre>
 * {@stickyNote "Note"
 * This is a <i>note</i>.
 * }
 * 

XML Markup

 * <pre>
 * {@markupExample "POM Dependency"
 * &lt;dependency&gt;
 *  &lt;groupId&gt;xerces&lt;/groupId&gt;
 *  &lt;artifactId&gt;xercesImpl&lt;/artifactId&gt;
 *  &lt;version&gt;2.10.0&lt;/version&gt;
 * &lt;/dependency&gt;
 * }
 * 

Java Code

 * <pre>
 * {@source
 *     final OutputStream out = ...;
 *     try {
 *       final PropertiesPropertyReport report = new PropertiesPropertyReport(out);
 *       final ReportBuilder reportBuilder = ReportBuilder.create(configuration);
 *       reportBuilder.reportTo(report);
 *       myHelper.reportProblems(report);
 *       report.flush();
 *     }
 *     finally {
 *       IOUtils.closeQuietly(out);
 *     }
 *   }
 * 

Java Code with Annotations

 * <pre>
 * {@source "Usage Example"
 * {@annotation}DocTag("parent-tag")
 *   public interface TestProperties
 *   {
 *     String inheritAll();
 *
 *     {@annotation}DocTag({ "sample-tag one" })
 *     String oneValue();
 *
 *     {@annotation}DocTag({ "sample-tag one", "sample-tag two", "sample-tag three" })
 *     String multipleValues();
 *   }
 * }

Tables

 * <pre>
 * {@table [noheader] [nofill]
 *   || header 1 | header 2 | ... | header N ||
 *   || cell 1/1 | cell 1/2 | ... | cell 1/N ||
 *   || cell 2/1 | cell 2/2 | ... | cell 2/N ||
 *   ...
 *   || cell M/1 | cell M/2 | ... | cell M/N ||
 * }
 * 

Other Tags

Have look at more examples of predefined tags on the taglets homepage!