Have you ever stumbled across a project and just think to yourself why does this class exist, or more specifically why did they use this design pattern? Recently I happened across one of those projects, in it the project used a Factory class that’s purpose was to instantiate and return a single class. In essence the developers knew what the Factory pattern was and utilized it without having any purpose to do so. Instead they created additional worthless code. This use of a programming pattern without the need of the pattern is known as Cargo Cult Programming

Cargo Cult Programming

The Cargo Cult Programming anti-pattern is the use of patterns, structures, or code in a project because you either always do or simply because you don’t know what it is doing but are copying it from another project or programmer. This style of programming causes unnecessary abstraction, code bloat and increases the difficulty of maintaining the project over its life span.

Want to be a better programmer? Then understand your code, don’t blindly copy/paste or use a pattern just because you can. Take your time and think is this needed, does it provide a useful functionality or enhancement to my project? or does it simply add additional code and size to the project. Don’t fall pray to becoming a Cargo Cult Programmer

Resources

, , , ,

When working in applications that utilize a lot of variables I often come across interfaces containing nothing but constants. Instead of creating a class containing the constants the developers choose to define them in an interface that can be implemented by a class so that constants don’t need to be qualified to a class in the code. This is so widespread that it has been termed the Constant Interface Antipattern. To ease users into correctly defining and using interfaces Java introduced Static Import in version 1.5.

To help illustrate why people choose to use interfaces to define constants lets have a look at an example. Lets assume we have defined our constants in the following interface MyConstants.

public interface MyConstants {
    public static final String PASS= "pass";
    public static final String FAIL = "fail";
}

To use the constants one would have their class implement the interface:

public class BadConstants implements MyConstants {
    private void outputResults() {
        System.out.println("FAIL Constant is " + FAIL);
        System.out.println("PASS Constant is " + PASS);
    }
}

As can be seen in the example the reason people prefer to use this method is that they do not have to qualify the constant by instead using:

System.out.println("FAIL Constant is " + MyConstants.FAIL);

To make it easier for coders to write good code Java introduced the Static Import feature in 1.5. What this does is allow us developers to import static properties into the current class’s namespace effectively allowing you to not qualify the constants. This is down by use of the import static statement where you can import a single constant or all constants of a class.

import static com.example.MyConstants.PASS;
import static com.example.MyConstants.*;

To put it simply don’t define constants in an interface, instead create them properly in their own classes and if you really don’t want to qualify them then utilize static import to import the constants into your class.

References

, , , ,

Overview

The Factory Pattern is a Software Design Pattern that is used to create an object without calling the specific object’s constructor.  This pattern allows a end user to call the factory to instantiate a class without having to know how to instantiate the class itself.  How it works is by the creation of a Factory object that contains a get method that returns an Object based on the parameters inputted to it.

To illustrate the pattern imagine you have a database that contains rules that need to be run every so often to ensure the integrity of your system. Next less also assume that each Rule could potentially be a different class but they all implement a common interface with the method execute. Using the Factory Pattern would be a good choice to go with as it would enable you to create new rules without having your engine know what it is running.

In Java we can utilize the Class object to make it so that our factory itself would not have to know about every Rule that it could create. This is done by utilizing the forName and newInstance methods. The Class.forName method takes as a parameter the name of a class and returns a Class Object for the specified class, and if it can’t find the class it throws a ClassNotFoundException. Using the Class Object returned from the forName method we can then call newInstance to instantiate the object.

Now to guarantee that you are instantiating a rule object and not just any object you could make use of an interface. This way when you instantiate the class you can cast it as the interface, and if this object doesn’t implement the interface then a ClassCastExeption would be thrown.

Java Example

Rule Intrface

package com.mdbitz
 
/*
 * Import Statements
 */
import java.util.List;
 
public interface IRule {
 
    /**
     * This is a set of init params which will be used 
     * to seed the rule
     * 
     * @param initParams
     */
    public void init(List initParams) 
                            throws IllegalArgumentException; 
 
    /**
     * This is the main business method of the rule
     * @return
     */
    public Boolean execute();
 
}

RuleFactory

package com.mdbitz;
 
/**
 * This class is a factory which instantiates the rules
 *
 */
public class RuleFactory{
 
 
    /**
     * Private constructor to enforce that it cannot be 
     * instantiated
     *
     */
    private RuleFactory(){
        super();
    }
 
    /**
     * This method initializes a Rule Class
     * @param Name of the Class
     * @return IRule
     */
    public static IRule getRule( String className )
    throws ClassNotFoundException,ClassCastException,
    IllegalAccessException,InstantiationException{
        IRule rule = null;
        try{
           Class implementationClass = Class.forName(className);
	   rule = (IRule)implementationClass.newInstance();
	   if(!implementationClass.isInstance(rule)){
	       throw new ClassCastException(
                      rule.getClass().getName()+ 
                      " is incompatible with "+className);
	   } 
        }catch(ClassNotFoundException cnfe){
	     throw new ClassNotFoundException( 
                      "In RuleFactory >> "+ruleClassName+
                      " not found",cnfe );
	 }catch(ClassCastException cce){
	     throw new ClassCastException(
                      "In RuleFactory >>" +ruleClassName+
                      " does not implement required interface" + 
                      " IRule\n In"+cce.getMessage() );
	 }
         return rule;
    }    
 
}

Calling the Factory

RuleFactory.getRule( "com.mdbitz.SpecificRule" );
, ,

Overview

Anti-Patterns are a pattern of behavior or design that proves to be counterproductive or inefficient to a project.  Although Anti-Patterns exist for Software and Object-Oriented designs my favorites mostly apply to organizational and project management (personal and group behaviors). Some patterns are listed below, if these sound familiar to you and you happen to be a project manager or a team lead then you may want to do research into how to modify the group’s or your own behavior.

Analysis Paralysis

This anti-pattern is defined as spending too much time on the analysis and planning of a project that too little time is left to the actual development or completion of the project.  Basically the project sits around with meetings and research going on but no work is being done on the actual project deliverable, until the implementation time period is shortened to the point the project is delayed or even canned.

Mushroom Management

This one I think explains itself in that the management keeps the team uninformed and fed lies (crap).

Death March

A project that everyone knows is going to be a disaster, which results in stress and pressure to work nights and weekends (or depending on the situation mandatory overtime). This can be caused by a multitude of factors some prominent ones are unrealistic time-lines, lack of necessary skills for the project, and poor management.

Scape Goat

Another one that probably needs no explanation but one I have often come across the brunt of. A scape goat is the individual that gets blamed for the failings of a project regardless of the factors that caused the project to fail. Ever been blamed for something when everyone knows their were a dozen other reasons that it went wrong? Congratulations!!, you were the goat BLEAT.

Wrap Up

There are dozens of other anti-patterns and hundred more unofficial ones, a quick way to find ones are to visit Wikipedia or the Anti Patterns Catalog. Some other ones i am fond of are Feature Creep ( I prefer CreepingFeaturitis ), Design By Committee, and Group Think.

Overview

Design Patterns are a reusable solutions to a commonly seen software desgin problem. The key item to remember is that these patterns are more like templates and instructions and are not reusable code. Although helpful and can solve many problems they are not usefull in every case and can hinder you from finding the best solution if you get in the mentality of  “what pattern should I use for x”. The better mentality is “does this functionality fit any patterns?”.

Decorator

The Decorator design pattern put simply is a way to add dynamic functionality to an object. This pattern is an alternative to sub-classing.  The basic pattern is that instead of sub-classing a base object to modify its values you create a decorator object that wraps the object and performs any modifications to functions that need changing or calls the base object functions.

The easiest way to explain this pattern is with an example. And what could be better then ice-cream.

Example

Lets start with a base object of an ice cream. In this example we will be modifing one value cost.

class IceCream {
    public IceCream() {}
 
    public getCost(){
        return 1.00;
    }
}

Next we will define the various modifications we can make to the ice cream as Decorators, For example we could add Sprinkles, Hot Fudge, and Cherry Dip. The basics elements to the decorator is that it takes an object into its constructor that it “decorates” or modifies.

class Sprinkles {
    private _baseObj;
 
    public Sprinkles( baseObj ) {
        this._baseObj = baseObj;
    }
 
    public function getCost() {
        return this._baseObj.getCost() + .25;
    }
}
class HotFudge{
    private _baseObj;
 
    public HotFudge( baseObj ) {
        this._baseObj = baseObj;
    }
 
    public function getCost() {
        return this._baseObj.getCost() + .50;
    }
}
class CherryDip{
    private _baseObj;
 
    public CherryDip( baseObj ) {
        this._baseObj = baseObj;
    }
 
    public function getCost() {
        return this._baseObj.getCost() + .50;
    }
}

You may have noticed that defining an interface that all decorators and base object implement is a great idea, but for the purpose of the demo we don’t need to. Now that the decorators are defined we can now modify or “decorate” our ice cream

var myIceCream = new HotFudge( new Sprinkle(new IceCream()) );
myIceCream.getCost();

The Cost of my icream will be 1.75 as seen this pattern is an excellent way to implement modifications to objects without creating distinct subclasses and allows the program to use whichever decorators it requires at run time by simply wrapping the base object.  Further details as well as non pseudo code examples can be found at wikipedia