From: Matthew Smillie Date: 2006-06-19T22:50:09+09:00 Subject: Re: best way to deal with command line options On Jun 19, 2006, at 13:14, thomas coopman wrote: > Suppose I have a program, with a class say A and a main. > My program also has a verbose option (program --verbose). > What's the best way to implement the verbose option in a OO-way? > > a) give the boolean verbose to the class and let the class control > it. (method(verbose) --> puts "something" if verbose) > b) run the program and let the main handle with the verbose option. > c) something else Hard to say without a little more knowledge of the program and the nature of the class. In general I'd say it depends mostly on how many different places in the code would have different behaviour based on the parameter. In other words, how many places in the code need something like this: "if @verbose then..." If there's just one place, then it's fine to do it there. If there's more than one place, then you want to make it one place. One way of doing this is using a logger: the class would *always* tell the logger what's going on, and the logger worries about the verbose parameter and whether or not to tell you. Sort of like this: class A def initialize(verbose = false) @logger = Logger.new(verbose) end def do_something_complicated @logger.write("verbose information") end def do_something_even_more_complicated @logger.write("verbose information") @logger.write("more verbose information") end end class Logger def initialize(verbose = false) @verbose = verbose end def write(str) puts str if @verbose end end The Logger class in Ruby's stdlib does exactly this, but in a significantly more sophisticated way. > A second question about this is suppose my program runs a loop for > a number of times and the user may specify the number of loops to > make, and if the program must run to the end in once or ask for > user action every x steps) > like: program --loops 50 --steps 5 --> this would ask for user > input every 5yt steps and loops 50 times. > > What's the best way to do this? > > a) again let the class handle it (a method run(number_of_loops, > steps)) > b) or let the main handle it (in the class just a method step() and > in the main the method run(number_of_loops, steps)) > c) something else a) and b) are the same thing, it's just the location of the 'run' method that's different, so the question boils down to "where's the appropraite place to have my 'run' method?" Which is actually quite difficult to answer without knowing anything about the code. Do you think that the 'run' method is integral to the A class? Or is it more of a user-interface thing that should be separate from A? Both approaches could be justified. matthew smillie.