It’s turtles all the way down

Turtles all the way down” is a concept that Java handles very nicely:

public class Turtle {
    Turtle prevTurtle;

    public Turtle(Turtle prevTurtle) {
        if (prevTurtle == null) {
            throw new RuntimeException("It's turtles all the way down.");
        }
	this.prevTurtle = prevTurtle;
    }
}

(Probably there should be a special FiniteTurtleException, but I wanted to keep the code compact.)

Similarly for other circular references:

class Chicken {
    Egg cameFrom;

    public Chicken(Egg hatchedFrom) {
        cameFrom = hatchedFrom;
    }
}

class Egg {
    Chicken cameFrom;

    public Egg(Chicken mother) {
        cameFrom = mother;
    }
}

You can do it in C-like languages, but you need to be a little clever in your header files, which takes some of the fun out of it.

Yertle the Turtle

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: