From: Matthew Kerwin Date: 2012-07-31T10:28:04+09:00 Subject: Re: Supporting multiple versions of an API On 31 July 2012 07:54, Intransition wrote: > Any recommendations on the management of API versions. I have a case in > which it is important that my library support all versions. > > For example, currently I am basically doing: > > module MyLib > module V0 > module Main > ... > end > end > > class Main > def initialize(version) > extend MyLib.const_get("V#{version}")::Main > end > end > end > > Does that seem like a good approach. Or is it overkill? Is there a better > way to handle this? > > Thanks. For what it's worth, I kind of like this solution, but I get the feeling there's something not quite right about it. An alternative could be to strategically name source files, and `require` the appropriate one; in that case each version-specific file could redefine the relevant part of Main. E.g. # File: main.rb class Main def initialize version require "./main-v#{version}.rb" end # universal code end # File main-v0.rb class Main # version-specific code end It splits things up into maintainable files quite nicely, and also has less parsing (for what that's worth.) However it wouldn't work if you need two different versions of Main in the one program. Alternatively you could create a factory, which is essentially what you've done, but might be a bit more recognisable to, or better understood by, maintainers. E.g. class Main # ... universal code end class MainV0 < Main # ... version-specific code end module MainFactory def self.create version const_get("MainV#{version}").new end end It's mostly a fluff change to what you've already got, but it means each object has the version-specific API as their class rather than a mixed-in module (i.e. no real difference as far as I'm aware), and it's clear that the MainFactory is a factory and that each of the MainVx classes are what it instantiates, whereas a partially implemented Main class with some strange magic in its #initialize method might be a bit less clear. That all said good documentation will almost always trump recognisable patterns or otherwise self-documenting code. I'd be interested to see other peoples' comments. -- Matthew Kerwin, B.Sc (CompSci) (Hons) http://matthew.kerwin.net.au/ ABN: 59-013-727-651 "You'll never find a programming language that frees you from the burden of clarifying your ideas." - xkcd