Category Archives: computer OOD

Simple Explaination of Monad

Here’s my shot at a simple explanation of what a monad is in the computer world. First, I have to explain what a monoid is.

A monoid is (roughly)  a group of functions who take a parameter of a certain type and return a result of that type.

That’s useful because it allows easy “chaining” or “composition” of functions. Any fluent interface in java is a monoid:

MyThing result = myThing.spin()

Note that the input to each function is a MyThing, and the result is a MyThing.

A caution; strictly speaking, a monoid needs a few extra things. It needs an “identity” function that just returns the parameter, it needs a binary function that takes two items of the type and returns a new instance of the type, and those binary functions must be associative, so you can change the order of evaluation: ==

A monad takes the idea of monoid one step further; instead of mapping a class onto itself, it takes a container type which accepts any underlying type, and lifts that into a monoid space. So it’s a monoid using a container type:

A monad is (roughly) a group of functions who take a container type as an argument and return a result of the container type.

But note that the underlying type of the container may change. So you could map Container<String> to Container<Integer>. But the functions would still line up.

MyContainer<Int> myContainer = new MyContainer(1);
MyContainer<String> result = myContainer.<Int>rehash()

So that you are able to “chain” or “compose” the functions and get a result of any arbitrary type! That’s a pretty strong claim for a statically-typed language like Java.

(Note that in Haskell, the signatures of the functions would be a little different. They would be functions of (Int, MyContainer) or (String, MyContainer), and it would be the job of the container to appropriately apply the function to it’s contents. But it’s hard to make a direct comparison from Java to Haskell, because Haskell works much more directly with function composition. In Haskell, the monad is actually composing the type constructors, rather than with instances of the type.)

But the core idea behind the monad is to create a monoid on a container type, in order to get the benefits of chaining and composition across different underlying types.

Leave a comment

Filed under computer architecture, computer OOD, design patterns

Monadic Downcast

lol that’s kind of a cool title.

Downcasts are always a pain in the butt in an OO language. If you’ve designed your code correcly, you should never need to do a downcast. But sometimes you get stuck where you have to.

An upcast is the good kind of object cast, for example casting an ArrayList up to a List so you can handle it more generically. That’s a good practice in OO, something you should aim for.

A downcast goes the other way, for example saying, “I know this Object is really a BigInteger, so I’m going to cast it down the class hierarchy to a more specific type.” The problem is, the compiler can’t guarantee that an Object is a BigInteger, so you’re taking a chance that an Integer or String or whatever slipped in at runtime. You’re risking a Class Cast Exception.

The classic downcast situation is parsing a JSON structure into a nested Map heirarchy, and then pulling values out of it. Each Object in the map could be a String, List, or another Map. Sometimes, rather than encapsulating the JSON structure as a class structure, you encapsulate the data operation as an operation on a nested Map structure as a convenience.


C# has a nice “as” operator that will perform a cast, and return null if the cast isn’t valid. I always really liked that operator. So, inspired by that and my latest investigation of Monads, I came up with this utility.

It’s a monadic downcast utility class. The idea is that you instantiate one with the class that you want to cast to, and then invoke that instance to perform the down-cast.

It’s monadic because:

  • It “lifts” any arbitrary class into a monadic casting space.
  • It also provides a bind operation that allows you to perform arbitrary functions on the data, without recompiling the original code.

I’ve taken shortcuts with convention to make the code shorter. Also, note the @SuppressWarnings that suppresses the compiler warning you about the downcast you’re making.

The usage is to instantiate an As object, and then use the of to perform the cast. The result has an “isA” property (here it’s just an attribute, for brevity) if the cast is possible, and a “present” property if the object is not null. The “get” property returns the object as the type that you want.


// use a prototype for a custom class
    As<Thing> asThing = As.proto(Thing.class);
    As<Thing> t = asThing.of(o);
    if (t.isA) {
// or use the one of the convenience classes:
    As<Map<String, Object>> a = As.MAP.of(source);
    if (a.isA) {
        a.get.put("zoom", "pop");
// or do a type conversion
    As<String> s = As.STRING.of("123");
    assert s.isA;

    As<Integer> i = s.bind(TO_INTEGER);
    assert i.isA;
    assert i.get == 123;

    // parse int
    static final Function<String, As<Integer>> TO_INTEGER = new Function<String, As<Integer>>() {
        public As<Integer> apply(String b) {
            try {
                return As.INTEGER.of(Integer.parseInt(b));
            catch (NumberFormatException e) {

And here’s the implementation.

public class As<A> {

    // info we're tracking
    public final A get;
    public final boolean isA;
    public final Class<?> clazz;

    // some utility prototypes
    public static final As<Map<String, Object>> MAP = As.proto(Map.class);
    public static final As<List<Object>> LIST = As.proto(List.class);
    public static final As<String> STRING = As.proto(String.class);
    public static final As<Integer> INTEGER = As.proto(Integer.class);

    /** create a prototype */
    public static <A> As<A> proto(Class<?> clazz) {
        return new As<A>(clazz, null, false);

    /** no of a certain type */
    public static final <X> As<X> no() {
        return new As<X>(null, null, false);

    /** generic function interface -- note no monadic restrictions here */
    public interface Function<A, B> {
        B apply(A a);

    /** internal constuctor */
    As(Class<?> clazz, A get, boolean isA) {
        this.get = get;
        this.isA = isA;
        this.clazz = clazz;

    /** of === unit ... lift a value into monadic space */
    public As<A> of(Object a) {
        if (clazz == null) {
            return no();

        boolean is = clazz.isInstance(a);
        As<A> that = new As<A>(clazz, is ? (A)a : null, is);
        return that;

    /** bind :: m a -> (a -> m b) -> m b */
    public <B> As<B> bind(Function<A, As<B>> f) {
        if (! isA) {
            // I'd like to return a prototype, but can't because of type erasure

        return f.apply(get);

    /** a nice to string */
    public String toString() {
        StringBuilder builder = new StringBuilder();

        builder.append(" " + get);
        builder.append(" isA=");

        builder.append(" }");
        return builder.toString();

And here’s a sample, using the classic case of traversing a generic map hierarchy to pull out data.

public class Sample0 {

    public static void main(String[] args) {
        Map<String, Object> source = sample();

        assert !As.MAP.of(null).isA;

        assert !As.MAP.of("booya").isA;

        As<Map<String, Object>> c = As.MAP.of(source.get("ma"));
        if (c.isA) {
            c.get.put("po", "op");

            As<String> d = As.STRING.of(c.get.get("li"));
            assert !d.isA;

            As<String> e = As.STRING.of(c.get.get("str"));
            if (e.isA) {
                System.err.println("String: " + e.get.substring(0, 1));

            As<List<Object>> f = As.LIST.of(c.get.get("li"));
            if (f.isA) {
                System.err.println("List: " + f.get.get(0));

    private static Map<String, Object> sample() {
        Map<String, Object> source = new HashMap<String, Object>();
        Map<String, Object> hoppop = new HashMap<String, Object>();
        List<String> zing = Arrays.asList("1", "2", "3");
        String booya = "booya";
        String zoopup = "zoopup";

        source.put("str", booya);
        source.put("li", zing);
        source.put("ma", hoppop);
        hoppop.put("str", zoopup);
        hoppop.put("li", zing);
        return source;

BTW here is a demonstration that the implementation meets the Monadic Rules. Maybe I’ll post more about that later.

public class Rules {

    /** int to string */
    static final Function<Integer, As<String>> f = new Function<Integer, As<String>>() {
        public As<String> apply(Integer b) {
            return As.STRING.of("" + b);

    /** string to int */
    static final Function<String, As<Integer>> g = new Function<String, As<Integer>>() {
        public As<Integer> apply(String b) {
            return As.INTEGER.of(Integer.parseInt(b));

    /** unit int */
    static final Function<Integer, As<Integer>> u = new Function<Integer, As<Integer>>() { 
        public As<Integer> apply(Integer b) {
            return As.INTEGER.of(b);

    /** associative */
    static final Function<Integer, As<Integer>> r = new Function<Integer, As<Integer>>() { 
        public As<Integer> apply(Integer b) {
            return f.apply(b).bind(g);

    /** test the monadic rules */
    public static void main(String[] args) {

        As<Integer> m = As.INTEGER.of(1);


    /** Left identity: return a >>= f ≡ f a */
    private static void leftIdentity(As<Integer> m) {
        As<String> left = m.bind(f);
        As<String> right = f.apply(1);
        System.err.println(left + " " + right);
        assert left.toString().equals(right.toString());

    /** Right identity: m >>= return ≡ m */
    private static void rightIdentity(As<Integer> m) {
        As<Integer> left = m.bind(u);
        As<Integer> right = m;
        System.err.println(left + " " + right);
        assert left.toString().equals(right.toString());

    /** Associativity: (m >>= f) >>= g ≡ m >>= (\x -> f x >>= g) */
    private static void associativity(As<Integer> m) {
        As<Integer> left = m.bind(f).bind(g);
        As<Integer> right = m.bind(r);
        System.err.println(left + " " + right);
        assert left.toString().equals(right.toString());


Leave a comment

Filed under computer algorithms, computer OOD, design patterns, utility

Whyfore Art Thou Functional vs. OO

John Cook had an interesting post here:

I think the Functional vs. Object Oriented argument is largely made up. It’s basically arguments over code style and syntax. Which, of course, are the fiercest arguments in our stupid industry. It’s just a matter of how you want to divvy up your code. Either you use little functions with complicated arguments, or complicated objects with functions with smaller arguments. There are good points in either style of programming about which is easier to code and validate.

…And on top of that, there are the structural guys who never really got over the idea of a large global function. They just roll their big functions into objects, usually Singletons or as static methods, or as Singletons with static methods, and then go off to lunch, whistling.

…completely unaware of the harm they are doing to the world. Notably, to me.

You can do functional programming in Java, even without Java 8. And you can do object-oriented programming in the functional or procedural languages. All languages provide a way to bundle data and functions, even if it’s just a map (or dict for the pythonneers). It’s just that the compiler says, “I’m not going to let you do that easily, because I think it’s dangerous.”

It’s like the old joke: A PASCAL programmer, a Java programmer, and a Scheme programmer walk into a bar … oh wait its all the same guy.

The more fundamental problem is the difference between imperative and declarative thinking. When developers first walk into the declarative realm, they are just flummoxed when they discover they can’t change the value of a variable they’ve assigned. In the declarative world, you have to think about how to build the answer piece by piece instead of just updating the pieces. That can be really hard if you’re not used to it.

I spend time thinking about declarative programming, and a lot of time thinking about OO, of course. But I always find the declarative problems more fundamentally alien to my usual way of thinking.

Leave a comment

Filed under computer industry, computer OOD, opinionizing

The “Hard Shell Soft Center” Pattern

Maybe there’s a real name for this 😉 but that’s what I like to think of it as.

Also — full disclosure — I never use this pattern. But it’s fun to think about.

It comes down to how do you expose functionality with shared state.

Almost everyone who’s stuck in 2001 immediately jumps to Singleton. The basic idea of the Singleton pattern is that you’re protecting methods on shared state. If there’s no shared state in a class, then Singleton is ridiculous and worse than worthless. (Because of all the design limitations it inflicts.)

The idea of Singleton is that there is a static factory method call “getInstance()” that is guaranteed to always return the same instance. So everyone who calls “getInstance()” gets a specific instance that everyone else gets, and that’s how we share state.

I see static methods as “hard” because they are rigid and tied to one implementation class at compile time. Instance methods are “soft” and can be overridden or provided from an alternate implementation. So Singleton’s like a “hard factory that produces a specific, shared, soft instance”.

But another way to share state is to hide the state information in an internal object, and instead of exposing the object, you create a hard wrapper around it. So it’s like this:

public class HardShell {

private static SoftCenter center = new SoftCenter();

public static doSomething() {

// act on the shared information in the SoftCenter object without exposing it

..and if you’re smart you’ll have some sort of “setCenter(newCenter)” call that allows you to swap out the object you’re protecting.

That way, the hard shell becomes a sort of Locator for the instance that you’re trying to hide. Kind of an interesting idea.

I never use that pattern, though. 😉

Leave a comment

Filed under computer OOD, design patterns, opinionizing