From: "Jesús Gabriel y Galán" Date: 2010-04-16T16:56:19+09:00 Subject: Re: Is this good OOP structuring? On Fri, Apr 16, 2010 at 9:49 AM, Derek Cannon wrote: > Robert, I think you were meaning to thank Josh! Anyway, thanks very much > Josh for the great explanations. That answered all my questions! And > Robert, your example really helped -- it was a great concrete example. > > I guess my only question now is: when is it appropriate to make methods > static? In the example that was given earlier: > >>class CourseController >>   def initialize(...) # whatever it needs >>   end >> >>   def self.read_url(url) >>     ... >>     cc = new(...) >>     ... >>     cc >>   end >> >>   def self.read_file(file_name) >>   end >>end > > I understand how one would use CourseController.read_url(xxx) and > CourseController.read_file(xxx), but I don't understand why I'd need it. > > Without it being static, I could just make references to the instance > variables, in this case, the url -- which would be passed through in the > initialize constructor). That would eliminate the need for the parameter > that both static methods carry, right? > > Am I missing something about when static methods should be used? In this particular idiom, the class methods (what you are calling static) are used to construct the object in different ways. You abstract what you need to construct your object, which is a string, and provide utility class methods to obtains the string through different means (url, file, etc). The object is more modular/reusable, since it's constructor doens't depend on a URL, but on the final string you will parse. If a certain client of that object gathers the string from a place that you didn't (or couldn't) imagine, he can still use your class, since he can call the constructor directly. string = get_string_from_some_place controller = CourseController.new string This is the effect of CourseController being more modular: it can be used with other pieces of code, because it has a single, well-defined responsibility. Jesus.