From: John Carter Date: 2006-08-09T06:11:43+09:00 Subject: Re: Global variables considered harmful? On Wed, 9 Aug 2006, darren kirby wrote: > I have a Ruby script here that acts like a regular Unix program, including > accepting a large number of command-line options/arguments. After processing > some are simple flags (ie: nil or 1) and some are text/numeric arguments. > Not all are required, and some must be initialized with a default value. I > have currently implemented them as globals, as their values are needed > anywhere in my script, from classes to functions to top-level flow control > code... I tend to parcel such things up into a Context object. Sort of like... class MyProgContext def initialize( argv) parse_args( argv) sanity_check end def print_help_and_exit( plain="Usage:-") puts " #{plaint} myprog [options] arg1 arg2 Description " exit( 1) end end context = MyProgContext.new( ARGV) .... Advantages :- * Collects all the stuff neatly into a class. * Allows me to enforce invariants (ie. sanity check options / arguments for mutual compatibility / sanity. * Easy to unit test the ARGV parsing logic. John Carter Phone : (64)(3) 358 6639 Tait Electronics Fax : (64)(3) 359 4632 PO Box 1645 Christchurch Email : john.carter@tait.co.nz New Zealand Carter's Clarification of Murphy's Law. "Things only ever go right so that they may go more spectacularly wrong later." From this principle, all of life and physics may be deduced.