I had this whole clever plan.

An app I'm building uses nested routes (e.g. /houses/1/rooms/2/cupboards/4).

I prefer that, it's logical, it's organised, and the user can see what's going on. They can also guess at and use the URL to find other items. They should be able to, that's the point.

Yes, I could show the user the same page with a URL of /cupboards/4 and calculate the rest, but it loses opportunities offered by established web practices.

So I use nested routes. They're good and worth the investment.

Finding Nested Items

So there's a problem with this. To show a list of cupboards, I have to calculate their paths every time so that I can provide links to them. If you want to see all yellow cupboards, then this could mean they're in all sorts of rooms and houses, so they must be calculated on the fly.

So I created this clever Wayfinder class that could be configured with a bunch of wayfinders (e.g. CupboardWayfinder), and had a map of object classes to wayfinder classes. It could then use the right wayfinder for an object to get its path. Still had all the expensive calculations, but now they're nicely abstracted. All I needed to do was build in a cache mechanism to the Wayfinder class and we're done.

All very clever, and it worked.

But that's not the right way!

The whole point of using nested routes is that it leverages existing web practices more fully.

And today I realised I'd missed an opportunity. So I'll be refactoring around this today.

Instead of a clever wayfinder and a clever cache and all that clever (expensive, complex, breakable) stuff, I could use the web's power again.

So I'll create all links to an object by using a root locator, e.g. /cupbard/3, unless the controller/view happens to have the path information handy. Cheap, easy to calculate on the fly. Then, there will be a series of single-action controllers which will redirect you to the right nested path e.g. /houses/1/rooms/2/cupboards/3.

This will only be calculated when someone actually clicks the link (i.e. very infrequently compared to every time an item is listed), will not need caching, and will always redirect to the right place (even if the item has moved since).

Why did I not see this before?