Search code examples
javaeffective-java

Examples for combinatorial explosion in Java?


In the Effective Java, Item - 18, Bloch says that interfaces prevent combinatorial explosion, which will happen when using abstract classes with multiple attributes in a type system.

I am not able to wrap my head around what exactly is combinatorial explosion.

Can anyone provide an example of combinatorial explosion because of using abstract classes, and how interfaces are used to prevent this problem?


Solution

  • Note: This answer borrows from Software Architecture Design Patterns in Java, see the Decorator pattern chapter for an example of combinatorial explosion.

    Suppose you have a Logger interface, and three concrete implementations: FileLogger, STDOUTLogger, DBLogger. Now imagine that there are 3 possible formats in which a line can be logged: Plain, HTML, Encrypted.

    Naively one can create a class for each of the possible combinations, which total 3 * 3 = 9:

    1. FileLoggerPlain
    2. FileLoggerHtml
    3. FileLoggerEncrypt
    4. STDOUTLoggerPlain
    5. STDOUTLoggerHtml
    6. STDOUTLoggerEncrypt
    7. DBLoggerPlain
    8. DBLoggerHtml
    9. DBLoggerEncrypt

    The 9 above translate to 9 types in Java. Notice the proliferation of classes that has resulted to support each combination. You can instead create reusable types to describe the logger medium (File, STDOUT, DB), and the format (Plain, Html, Encrypt). Notice this results in 6 types only. You can then use patterns like Decorator to wrap a logger type in a format type (E.g. EncryptLoggerDecorator wraps DBLogger, or wraps STDOUTLogger) to dynamically alter behavior of a system, as opposed to statically defining the behavior if you were to use a bloated class hierarchy. I believe the point that Joshua Bloch tries to drive home is to keep hierarchies flat, and Java interfaces lend themselves well for that purpose.