[Courses] [Ruby] Lesson 1: Classes

Laurel Fan laurel.fan at gmail.com
Sun Nov 27 06:55:32 EST 2005


On 11/23/05, Anne G <anne at wjh.harvard.edu> wrote:
> I have a project I am working on, parsing subject data that
> has been concatennated into one giant file. I figure I can
> write a class and small methods as an exercise...
>
> but it is just as easy to process the file line by line with
> a few switches here and there, without specifying any new
> class (other than an array instance etc)..

It's true that very simple programs such as this are probably just as
easily done procedurally as with objects.

> The song example in the book is a database.  What are other
> examples of common objects? When is it worth creating an
> object, versus plain code?

One way of thinking of this is whether something is represented as an
object in a real world, or whether it has multiple properties.  A few
examples:

If I was writing a jigsaw puzzle game, I could make each piece an
object, with properties such as the image on the piece, and the shapes
of the sides.  I could also imagine creating methods to determine
whether two pieces fit together, or to attach two pieces.  To get more
fancy, since I realize that a set of pieces that are already put
together share many of the same properties as a single piece, I could
even make them share some methods and functionality with inheritance
and mixins.

If I was writing a http server, an http request has several
properties, such as the URL, query string, user agent (the type of
browser making the request), even things such as the time of the
request.  I'd like to keep these together in the same object.  One of
the advantages of this is that when writing functions that use some of
this information, I can simply pass the whole request object instead
of individual properties.  Or, when it makes sense, I can put the
methods on my HTTPRequest class.

> I understand the theory about encapsulation, but in practice
> my code is fairly short, and I only use functions to
> identify what different sections of the code do. I use
> globals to avoid the hastle of passing info to the fxs.
>
> so I don't really know, how do you figure out what part
> of the code would be a good candidate for a class.

For small programs especially, it can be hard to tell whether using
classes gives you any advantage.  It's definitely a lot more obvious
for larger programs;  that's one of the things that makes teaching
object oriented programming difficult.

--
Laurel Fan
http://dreadnought.gorgorg.org


More information about the Courses mailing list