From: Ned Konz Date: 2001-08-15T01:11:52+09:00 Subject: [ruby-talk:19702] Re: class methods and optimizing On Tuesday 14 August 2001 08:52 am, you wrote: > Does anyone know what class methods are as opposed to instance methods? Are > they for optimizing? when would I use them?I have looked at a couple > manuals that tell you how to do them: def classname.method but none seem to > explain the why and when. Class methods are those that don't operate upon a single instance of a class. Typical examples of class methods are: * Constructors: these can't be instance methods since there isn't an instance yet. (but note that initializers have to be instance methods). * Methods that do something with all the instances of a class (collect them, index them, count them, etc.) * Utility methods: these just use the class as a convenient namespace for what otherwise would be unattached methods. > And this leads to my second question. In terms of memory usage and speed, > is it better to extend the existing classes (when possible) or to build > your own, or to just make a subclass? e.g. If I program a deck routine for > a card game I can just add shuffle, play etc. routines to class Array. Now > the computer isn't holding an extra class definition in memory, but ALL > arrays (not decks) are also extended. If I make my own class/subclass, not > all of the arrays are extended but there is another class definition in > memory... Does [1, 2, 3].play make sense? Probably not. How does one play [1, 2, 3]? Instead, you should have domain-specific entities: cards and card decks. Some operations (shuffle, for instance) may indeed be applicable to Arrays in general. These could be added as extensions to Array. But when you do this, you run the risk of colliding with others who may be doing the same thing. -- Ned Konz currently: Stanwood, WA email: ned@bike-nomad.com homepage: http://bike-nomad.com