On Thu, 8 Dec 2005, Steve L. wrote:
Hi all,
I wrote some hierarchy handling classes in Node.rb
(Node.rb), and I’ve been
told I write Ruby in Perl style. In future software, what could I do to write
in a more Ruby-like fashion?
here are some thoughts:
class Node < Object
def initialize(nam, type, value)
super()
@name = nam
@type = type
@value = value
@attribs = {}
@parent = nil
@prevsibling = nil
@nextsibling = nil
@firstchild = nil
@lastchild = nil
end
attr_reader :name, :type, :value
attr_writer :name, :type, :value
attr_reader :parent, :prevsibling, :nextsibling,
:firstchild, :lastchild
def setAttributes(attribs) @attribs = attribs; end
def getAttributes() return @attribs; end
def hasAttributes() return @attribs != nil; end
def setAttribute(key, value) @attribs[key] = value; end
def getAttribute(key) return @attribs[key]; end
def hasAttribute(key) return @attribs[key] != nil; end
i would condensed into
class Node
ATTRIBUTES = %w(
name type value attribs parent prevsibling nextsibling firstchild
lastchild
).each{|a| attr_accessor a; alias_method “#{ a }?”, a}
def initialize name, type, value, attribs = {}
@name, @type, @value, @attribs = name, type, value, attribs
end
don’t bother with access control - sometimes it’s needed (object
available on
the web) but sometimes it’s not. with it you are saying “my code has no
mistakes - you will not need access to these vars” by saying
‘read_only’. i’ve
probably fixed about 50 bugs in code where i had to subvert the access
control
by doing
obj.instance_var_set “@broken”, “fixed”
because of this kind of design. don’t use it where it’s not critical.
dont’ use get/set/has - use attr, attr=, attr?
def setParent(parent)
@parent = parent
node = self
while node.prevsibling
node = node.prevsibling
end
@parent.firstchild = node
node = self
while node.nextsibling
node = node.nextsibling
end
@parent.lastchild = node
@parent
end
could be
def parent= parent
parent.firstchild = oldest
parent.lastchild = youngest
@parent = parent
end
def oldest
node = self
node = node.prevsibling while node.prevsibling
node
end
def youngest
node = self
node = node.nextsibling while node.nextsibling
node
end
which isn’t shorter - until the next time you write that code.
food for thought.
cheers.
-a