Tony DiNitto
Tony DiNitto

Reputation: 1239

Inherit all instance variables into another class

I have tons of different methods in a particular class that all calculate unique instance variables. I've been using the attr_reader to access these without any problem, but now I've got dozens of these and wondering if there's a preferred / eloquent way to access all of these instance variables - not just a solution, but a generally accepted preferred method/style.

I've seen similar questions regarding class level variables, but that's something I'd like to avoid. Maybe I can do this with a Module, but I thought those were for storing piles of constants? But maybe it's something I'm missing with regular Class inheritance? Inheriting self?

If you imagine the pile of these instance variables as mathematical constants (pi, eulers, etc.) that all get a number added to them (depending on user input). I'm aware of classes and methods doing one thing, which the Stack class and method definitely do one thing - they're just storing pieces of data that are needed by many other classes and methods.

An example of code that I'm working with:

    class Stack
    attr_reader :pi, :euler  # ... and dozens more of these

    def initialize
        @pi = 3.14 + 8
        @euler = 0.577 + 8
        # dozens more assignements here
    end
end

class Overflow
    def show
        a = Stack.new
        p a.pi  # attr_reader works fine here
    end
end

class AnotherClass
    def some_method_that_needs_all_variables_in_Stack
        # Do I need to create another instance of the 
        # Stack class like I did in Overflow?
        # or should AnotherClass somehow inherit all the instance variables?
    end
end

Overflow.new.show   # => 11.14. 

Thanks!

Upvotes: 0

Views: 76

Answers (1)

Aleksey Shein
Aleksey Shein

Reputation: 7482

Have you heard about Single Responsibility Principle? It says, that 1 class should do only 1 thing, but do it well. Having a hundred (man, even five of them should make you doubt if your code is good) of instance variables, means that you have an antipode: God object, that does everything. This code is very hard to change because of myriad of hidden dependencies between method calls and instance variables.

The solution: Move out new classes and make them talk to each other. Read some book on the Object Oriented Programming, there are tons of them, and you'll immediately start feeling better about your code.

Upvotes: 2

Related Questions