This is a post about fences, but not in the good fences make good neighbours sense that you might expect. (This could be the way into lots of good things about interfaces, encapsulation and so on.) In this post I’m not interested in the things that the fence is separating, but in the fence itself – how it’s made up of posts and panels.
Fence panels and fence posts isn’t really a fully-fledged software design pattern, but is still a useful shorthand for a class of problems to do with counting things.
The anatomy of a fence
As far as we’re concerned, a fence is made up of posts with panels between them to make a continuous barrier. At the risk of pointing out the obvious: each panel needs a post at both ends, but one post can be shared by the panel to its left and to its right. This means that if you have 4 panels you need 5 posts, if you have 17 panels you need 18 posts and so on – it’s always 1 more post than panel.
How is a fence a useful model for software design?
Often software counts things. Within counting things, sometimes it’s obvious what you’re counting – how many rows in the results returned from a database query, how many items in a shopping cart etc. However, sometimes you need to be careful to make sure if you should count things or the things between them.
For instance, I was recently on the Tube in London and I needed to remember when it was time to get off. The Central line between Tottenham Court Road and Liverpool Street is like this:
The technique I use is to count down towards zero, so that when I reach zero I know I’m getting off at the next stop. To give myself some warning I number the gaps between stations rather than stations, like this:
The stations are like fence posts, and the tracks between stations are like fence panels.
Sometimes you might not be interested in counting fence panels or posts, but it’s still a useful model. If the fence posts are events that happen, e.g. when a car completes a lap of a circuit, then the time between the events – the lap times – are the fence panels. In order to have a lap time, you need to know two consecutive events when the car was at the start / finish line.
Fence panels and fence posts doesn’t crop up all that often, but when it applies it’s a tool that can help you to avoid off-by-one errors and other problems, which can be nasty.
2 thoughts on “Counting – fence panels or fence posts?”
Can I be the first to say Mornington Crescent in terms of Tube routing 🙂
LikeLiked by 1 person
Have you seen what the destination URL is of the link for “Tube” above? (In the second paragraph of the section titled: How is a fence a useful model for software design?) 🙂