Java - is this an idiom or pattern, behavior classes with no state

Posted by Berlin Brown on Stack Overflow See other posts from Stack Overflow or by Berlin Brown
Published on 2011-01-14T15:44:12Z Indexed on 2011/01/14 15:53 UTC
Read the original article Hit count: 231

I am trying to incorporate more functional programming idioms into my java development. One pattern that I like the most and avoids side effects is building classes that have behavior but they don't necessarily have any state. The behavior is locked into the methods but they only act on the parameters passed in.

The code below is code I am trying to avoid:

public class BadObject {

    private Map<String, String> data = new HashMap<String, String>();

    public BadObject() {
        data.put("data", "data");
    }

    /**
     * Act on the data class. But this is bad because we can't
     * rely on the integrity of the object's state.     
     */
    public void execute() {
        data.get("data").toString();
    }

}

The code below is nothing special but I am acting on the parameters and state is contained within that class. We still may run into issues with this class but that is an issue with the method and the state of the data, we can address issues in the routine as opposed to not trusting the entire object.

Is this some form of idiom? Is this similar to any pattern that you use?

public class SemiStatefulOOP {

    /**
     * Private class implies that I can access the members of the <code>Data</code> class
     * within the <code>SemiStatefulOOP</code> class and I can also access
     * the getData method from some other class.
     *  
     * @see Test1
     *
     */
    class Data {
        protected int counter = 0;        
        public int getData() {
            return counter;
        }
        public String toString() { return Integer.toString(counter); }
    }

    /**
     * Act on the data class. 
     */
    public void execute(final Data data) {
        data.counter++;        
    }

    /**
     * Act on the data class. 
     */
    public void updateStateWithCallToService(final Data data) {
        data.counter++;       
    }

    /**
     * Similar to CLOS (Common Lisp Object System) make instance.
     */
    public Data makeInstance() {
        return new Data();
    }

} // End of Class //

Issues with the code above:

  1. I wanted to declare the Data class private, but then I can't really reference it outside of the class:

  2. I can't override the SemiStateful class and access the private members.

Usage:

final SemiStatefulOOP someObject = new SemiStatefulOOP();
final SemiStatefulOOP.Data data = someObject.makeInstance(); 

someObject.execute(data);
someObject.updateStateWithCallToService(data);

© Stack Overflow or respective owner

Related posts about java

Related posts about functional-programming