From: Neubyr Neubyr Date: 2012-07-04T09:14:01+09:00 Subject: Re: passing ARGV to class methods Josh Cheek wrote in post #1067267: > On Tue, Jul 3, 2012 at 5:07 PM, Neubyr Neubyr > wrote: > >> >> I was wondering if I really need to pass ARGV to MyPrinter's initialize >> method. The ARGV is anyway available to the class so I think it doesn't >> need to be passed and can be used directly during option parsing step - >> 'opts_obj.parse!(ARGV)' . But I am not sure if it's a good practice or >> not. Any tips? >> >> > It kind of depends on the scope of what you're doing. Is it a small one > file script? Then its probably not necessary (of course, in that case, > the > class itself is probably overkill, too, probably a procedural file all > in > the toplevel is enough). > > If it's got more than one file, or you start feeling the need for the > class, then you should probably do it. Otherwise, you're coupling it to > ARGV, it now knows about who is using it, and it can only be used easily > in > that context. If you want your code to be reusable or testable, then > directly referencing ARGV is a losing strategy. If you can pass in the > args > array and file streams, then you can test that it does everything > correctly, by giving it arrays of hypothetical arguments and StringIO > instances. > > In general, it's better to avoid hard references (references to > constants > and globals). But be aware of your context. > > -Josh Thanks for the suggestions Josh. All of my command-line scripts are simple one-class files with structure similar to the above code snippet. Only few of them use classes and modules which are outside of the command-line script. I agree that hard-referencing ARGV is not good idea from reusability and testing point of view. And I am actually doing some testing (during development) in this manner without passing ARGV from command-line each time. So hard-referencing ARGV in this manner won't be a good idea for such cases. Thanks for pinting it out. - neubyr -- Posted via http://www.ruby-forum.com/.