17 February 2012

Reinventing the wheel: Collection.size()

 Original way to reinvent the wheel - by an examination of "Programming Fundamentals"
 
public class MyContainer {
   private final Collection myBag;

   public int getBagSize() {
    int j = 0;
    for(int i = 0; i < this.myBag.size(); i++) {
     j++;
    }
    return j;
   }
}

15 February 2012

Improper inheritance and light-hearted downcast

And here is maybe the worst design I've ever seen - directly from production-released code, of course...


Inheritance is a key feature in object-oriented programming languages, providing support for both specialization and flexible extensibility. But... using inheritance just to use it can drive to horrible design cases, where distinction between superclass/interfaces and different subclasses is improper and extensibility is actually impossible. This is the case of a real-life production code I was lucky enough to see:

public interface InterfaceX {
   public abstract void aMethodX();
}

public interface InterfaceY {
   public abstract String aMethodY(final String s);
}
 
Class FatImplementation implements both InterfaceX and InterfaceY:
 
public class FatImplementation implements InterfaceX, InterfaceY {
   public void aMethodX() {
      ...
   } 
 
   public String aMethodY(final String s) {
      ...
      return ...;
   }
}
 
And... Ladies and Gentlemen... the crazy client class, whose method is casting to InterfaceX an InterfaceY reference, relying on the fact that FatImplementation implements both interfaces:

public class CrazyClass {
 public void theCrazyCastingMethod(final InterfaceY y) {
  ...
  ((InterfaceX)y).aMethodX();
 }
}

This is an improper use of abstraction - inheritance programming model, since the cast succeeds only with a specific implementation (FatImplementation) of given interface and polymorphism is actually not possible.
... ... ... poorly and foolishly designed, isn't it? And... what if I said that InterfaceX and InterfaceY, in the original code, where StatefulXXX and StatelessXXX? So... FatImplementation was stateful and stateless at the same time! AAAAAAHHHH!

13 February 2012

Minimal log4j.xml configuration file template

Here a log4j.xml file template, providing a minimal log4j's configuration that enables console output and DEBUG logging level for a given base package - logging level is set to WARN for remaining packages.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration>
 <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
  <param name="Target" value="System.out" />
  <param name="Threshold" value="DEBUG" />
  <layout class="org.apache.log4j.PatternLayout">
   <param name="ConversionPattern"
    value="%d{ABSOLUTE} %-5p [%c{1}] %m%n" />
  </layout>
 </appender>
 <!-- Insert your own base-package HERE! -->
 <logger name="org.amicofragile">
  <level value="DEBUG" />
 </logger>
 <root>
  <priority value="WARN" />
  <appender-ref ref="CONSOLE" />
 </root>
</log4j:configuration>
 
Official log4j.xml documentation 

11 February 2012

Singleton, testing and dependency inversion

Singleton: pattern or antipattern?
Accordingly to Wikipedia, Singleton is a creational pattern, used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object. So, it's a pattern!
But it's an antipattern, too, especially from the point of view of testing: it's a (simple) variant of Service Locator testability antipattern.

As states Jens Schauder in his post Fixing the Singleton, there are two key characteristic of the (classic implementation of) singleton:
  • There can be only a single instance of the class developed as singleton
  • There is a central, global acces point to the singleton instance
Alhough the first one is the main - if not the only - reason for use of Singleton pattern, it comes almost alway with the second one. But... while the first one is a conceptual featur of the pattern, the second is nothing but an implementation detail!

We can therefore speak of conceptual Singleton, when we have a class that can be instantiated only once in the application lifecycle, and syntactic Singleton, with reference to the traditional GoF's implementation. 
Well, my idea is that you can think of two different basic implementation strategies for conceptual Singletons:
  • Singleton by syntax - traditional GoF's implementation, through private static instance and public static (and then: global) accessor
  • Singleton by contract / application - implementation of the concept of "single class instance" without syntactic constraints: application code takes care of respect the contract of "single instance". Tipically, application infrastructure responsible for creating object and setting up collaborators references instantiates the Singleton class only once and passes created instance to modules interested in its use: this is substantially an application of Dependency Inversion Principle, and can be implemented through Inversion of Control frameworks like Spring and Google-Guice (for a good discussion about self implemented dependency injection, see this article).
First approach suffers the problem suggested initially: there is a global state, publicly accessible, liberally referenced everywhere in the client code - and global state is evil!
The second one, instead, provides a conceptual Singleton instance without referring to syntactical constraints: application lifecycle infrastructure ensures unicity of the Singleton class instance.

In code:
  • Singleton by syntax:
    package singleton;

    public class UIDGenerator {
      private static final UIDGenerator INSTANCE = new UIDGenerator();

      public static UIDGenerator getInstance() {
        return INSTANCE;

      }

      private UIDGenerator() {
      }

      public String nextId() {
        return ...;
      }
    }

    Client code:

    public void foo() {
      String newId = UIDGenerator.getInstance().nextId();
      // Use newId
    }
      
    public void bar() {
      Account account = new Account(UIDGenerator.getInstance().nextId());
      // Use newly created Account
    }
    This the classical GoF's implementation of pattern Singleton: private constructor and final static INSTANCE ensure instance unicity, public static accessor provides global access to singleton instance.
  • Singleton by contract:
    package singleton;

    public interface UIDProvider {
      public abstract String nextUid();
    }


    Client code:

    package singleton;

    public class AccountManager {
      private final UIDProvider uidProvider;

      public AccountManager(UIDProvider uidProvider) {
        this.uidProvider = uidProvider;
      }
      
      public void bar() {
        Account account = new Account(uidProvider.nextUid());
        // Use newly created Account
      }
    }
In the second implementation we define an interface for UID generation: application infrastructure (i.e.. in most cases. an Inversion of Control container, like Spring) will ensure that a single instance of a class implementing UIDProvider is passed whenever it's necessary.
This way we can obtain the conceptual part of the pattern without the syntactical one: there is no public static context accessed everywhere, and a reference to the singleton is indeed injected into modules that need it. So, unlike in the first case, it's possibile to mock UIDProvider for testing purposes (for example because real implementation is time expensive, or there is a fee for every use, or simply because unit testing is isolation testing and we need to make assumptions on generated uid in testing code):

public class AccountManagerTest {
  @Test
  public void testMethod() {
    AccountManager underTest = new AccountManager(new FixedUIDProvider());
    // Exercises underTest
  }
}


This is IMHO a more, more (more!) powerful approach for implementing singleton than the classic one: can you figure out how to mock UIDGenerator.getInstance().nextId() calls?
The basic idea behind this proposal is a variation of single responsibility principle: classic singleton implementation drives to classes that implement two responsibilities: a functional responsibility - what the class do - and a structural responibility - how is the class instantiated and the instance accessed. Inversion of Control containers, and more generally the idea of Dependency Inversion, support separation of responsibilities by divide functional code and object graph lifecycle management code: this leads to clearer, simpler design, that decouples singleton implementations from client modules and supports testing in a more effective way.

09 February 2012

Book review: Implementation Patterns, by Kent Beck

Implementation Patterns is a book of 2007, written by Kent Beck - software consultant, one of the original signatories of the Agile Manifesto in 2001, and author of, among other things, JUnit, Extreme Programming Explained, TDD By Example.
Implementation Patterns is basically a collection of coding-level patterns, whose purpose is to address values defined in the initial theory of programming: communication (readability), simplicity, and flexibility.
These patterns are described with usual Beck's clear and straightforward style, and are common-sense recipes that every professional should know and recognize themselves. From this point of view, so, this is not an indispensable book: given a bit of common sens, its content is almost trivial, but... there are so many developers without common sense, out there... that such a book, and books like this, like the ultra famous Clean Code by Uncle Bob, are sadly necessary...
I think this is a book every developer should read: even if only for recognize behaviors that already adopts in everiday coding, and that the boss or the management consider just academical...

Uh, and: very interesting the chapter about applying implementation patterns to design-framework-for-evolution...

08 February 2012

Configuration architectural antipatterns

I've got the flu, these days: and in fever's drowsiness has surfaced the memory of an application I've worked on six years ago.
It was an aged application, developed by a former employee using Visual Basic 6 - uh! oh!
I was doing only fixes and small enhancements on that application, but I'll remember it forever due to its bright and genial configuration-relating design.

That application's configuration, as was the case also for other applications by the same author, was "designed" around the Multiple Configuration Points conceptual antipattern: it wasn't stored in a single, well defined, simple accessible place, but in multiple, differently implemented respositories:
  • part of the configuration was read from an "ini" file: the file was processed without using some kind of library, but reading the raw input and counting rows: at row #X, parameter Y - oh, yeah!
  • the remainder part of configuration cames from a MS Access File (may god forgive him! - if a god exists) and was accessed using OLE DB support and SQL queries (this part of the configuration was modifiable through the application itself)
So, in one application, and only with regard to configuration management, you can list several architectural antipatterns:
  1. Multiple Configuration Points: configuration spawned in multiple, heterogeneous repositories
  2. Reinventing The Wheel: "ini" file read through home-made procedure
  3. Brittle configuration: formatting-depandant "ini" file semantics
  4. Tightly coupling to external libraries versions: MDB configuration file could be read without errors  only when the MS Access' version on the host machine was the version for which the application was compiled - otherwise, the application wasn't ever able to start. And if the MDB file was modified using a most recent version, it became unreadable for the application...
And - final masterpiece: that application, which used relational DB for (partial) configuration management, did not use any type of database for business data storage and inter-application communication purposes: data storage was performed writing sequental text files with fixed-length records, and applications interested in data interchange read the same files (code reading and writing records was naturally duplicated between applications, not extracted in a common library).

I've got the flu, these days... but even conceive of such an architecture must have required a great fever... isn't it?

01 February 2012

Manifesto - Reasons for a blog

I am a serial reader: I read tens of thousands of pages every year. I read novels, comics, essays about mathematics and sciences. But my job is Software Engineering, so I read plenty of books, articles, blog posts and wiki pages about this topic.
And I am a serial polemicist: against what I read, against my and other's mistakes in coding and design.
So, after much reading and arguing, I feel it's time to give something back: this blog is intendend to provide a place for my technical thoughts, reasoning, and for the way I feel about Software Engineering.
Some posts will be a kind of repetition of contents already published in the old, defunct blog of the Java User group of Brescia - requiescat in pace. Some posts will be a re-edition of contents, articles, code snippets, and so on, already published on my own wiki: I feel a blog is a more powerful and easy-to-follow kind of communication (you can ultimately simply register my blog's feed in your feed-reader of choice, and you'll be notified when I add a new post), so my intention is to migrate all content from the wiki to this new virtual place.
And there will be obviously new posts and new contents, too: code snippets written by me, technical debates about patterns and anti-patterns, coding horrors I run up against during my teaching at University (and not only...), thinking and reasoning at coffee dispenser, technical books reviews, links to posts and various resources in the web. Something about everything and everything about nothing: small - and hopefully tasty - contributions, just like peanuts.
And now: it's time to write! Stay tuned!