The Ruby Programming Language by David Flanagan & Yukihiro Matsumoto

The Ruby Programming Language by David Flanagan & Yukihiro Matsumoto

Author:David Flanagan & Yukihiro Matsumoto [David Flanagan]
Language: eng
Format: epub, mobi
Tags: COMPUTERS / Software Development & Engineering / General
ISBN: 9780596158408
Publisher: O'Reilly Media
Published: 2008-12-16T16:00:00+00:00


A Mutable Point

The Point class we’ve been developing is immutable: once a point object has been created, there is no public API to change the X and Y coordinates of that point. This is probably as it should be. But let’s detour and investigate some methods we might add if we wanted points to be mutable.

First of all, we’d need x= and y= setter methods to allow the X and Y coordinates to be set directly. We could define these methods explicitly, or simply change our attr_reader line to attr_accessor:

attr_accessor :x, :y

Next, we’d like an alternative to the + operator for when we want to add the coordinates of point q to the coordinates of point p, and modify point p rather than creating and returning a new Point object. We’ll call this method add!, with the exclamation mark indicating that it alters the internal state of the object on which it is invoked:

def add!(p) # Add p to self, return modified self @x += p.x @y += p.y self end

When defining a mutator method, we normally only add an exclamation mark to the name if there is a nonmutating version of the same method. In this case, the name add! makes sense if we also define an add method that returns a new object, rather than altering its receiver. A nonmutating version of a mutator method is often written simply by creating a copy of self and invoking the mutator on the copied object:

def add(p) # A nonmutating version of add! q = self.dup # Make a copy of self q.add!(p) # Invoke the mutating method on the copy end

In this trivial example, our add method works just like the + operator we’ve already defined, and it’s not really necessary. So if we don’t define a nonmutating add, we should consider dropping the exclamation mark from add! and allowing the name of the method itself (“add” instead of “plus”) to indicate that it is a mutator.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.