From: James Edward Gray II Date: 2010-11-03T03:12:02+09:00 Subject: Re: the dark side of inherited methods On Nov 2, 2010, at 1:04 PM, Joel VanderWerf wrote: > On 11/02/2010 10:02 AM, Josh Cheek wrote: >> On Tue, Nov 2, 2010 at 11:19 AM, James Edward Gray II>> wrote: >> >>> Of course, inheritance has it's place and uses but I feel it's definitely >>> overused. >>> >>> >> Can you give some examples of where it has its place? I have been trying to >> think of one, and can't. I realized the only time I ever subclass anything >> is ActiveRecord::Base (and I'm not really sure what that offers over >> modules, DataMapper uses modules, for example). > > The shortest example that occurs to me: > > class A < Struct.new :x, :y, :z > def length > Math.sqrt(x**2 + y**2 + z**2) > end > end > > That only saves a couple of keystrokes compared to: > > A = Struct.new :x, :y, :z > class A > ... > > but it's cleaner IMO. Also, it allows you to do this: > > def x=(new_x) > raise ArgumentError if new_x > 100 > super > end > > In the "A=Struct.new" approach, you have to muck around with alias to get the same effect. Neither are required though, since Struct.new() takes a block: A = Struct.new(:x, :y, :z) do def length Math.sqrt(x**2 + y**2 + z**2) end end James Edward Gray II