Only Syntax

Journal of my investigation into the development of a new programming language

Wednesday, January 19, 2005

 

Refactoring Rectangle

I have run across two representations of rectangles (actually Axis-Aligned Bounding Boxes, or AABBs). Mac OS represents them (or at least once did) as the four integers left, top, right, bottom; Windows represents them as the position point (generally if not always meaning the top left) and a two-dimensional Size structure. I think both of these are poorly factored representations.

Many of the things we do with rectangles have direct counterparts in a one-dimensional range. For example:

And having written these methods for range, if we represent a rectangle as a horizontal and vertical range, we can simply delegate most behavior to the ranges. Here are some examples.




range:
. . low
. . length
. . high:
. . . . get: return low + length - 1
. . . . set: length = high - low + 1
. . empty: return length = 0
. . contains x:
. . . . x < low? . . return false
. . . . x > high?. . return false
. . . . return true
. . intersection that:
. . . . this.empty?. . return that
. . . . that.empty?. . return this
. . . . lo = max(low, x.low)
. . . . hi = min(high, x.high)
. . . . lo < hi?
. . . . . . yes:. . return range(lo, hi - lo + 1)
. . . . . . no: . . return range(0, 0)



rectangle:
. . x
. . y
. . empty: return x.empty or y.empty
. . contains p:
. . . . return x.contains p.x and y.contains p.y
. . intersection that:
. . . . return rectangle(x.intersection that.x,
. . . . . . . . . . . . .y.intersection that.y)


I think that's pretty nice.


Comments: Post a Comment

<< Home

Archives

03/30/2003 - 04/06/2003   04/06/2003 - 04/13/2003   10/12/2003 - 10/19/2003   01/09/2005 - 01/16/2005   01/16/2005 - 01/23/2005  

This page is powered by Blogger. Isn't yours?