Question

I have a "static" class (i.e. a class with a private constructor and only static members and functions). It wraps Androids' SharedPreferences Editor which has a rather nice fluent API.

I was wondering if it was at all possible to create a similar fluent API using this static class wrapper ?

The problem is that usually when making a fluent API one would return this; in all the functions. that (as far as I know) is not possible in the "static" class design. Is there some kind of workaround to this problem ?

Clearly this can be solved using the singleton pattern, but I'm looking for other solutions, preferably ones that require as little boilerplate code as possible.

Was it helpful?

Solution

I'm not familiar with the preferences API, but making a fluid API that you access statically is pretty simple.

For instance, to have something like Preferences.set().background(green).border(yellow);, you could do the following:

   public class Preferences {

        private Preferences(){}

        public static Preferences set() {
            return new Preferences();    
        }

        public Preferences background(Color color) {
            //set color on real preferences
            return this;
        }

        public Preferences border(Color color) {
            //set color on real preferences
            return this;
        }

    }

OTHER TIPS

Usually you would have a static factory method that returned a new object, then non-static methods of that object that customize the object or return copies of the object with the new behavior. The latter is preferable because then your objects can be immutable.

For what I think is a good example of this, see Guava's Ordering class:

// yields a natural ordering over some type
// where the largest object comes first (reverse ordering)
Ordering.natural().onResultOf(someFunction).reverse();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top