Objects, classes, inheritance, polymorphism- it sounds a little like Biology, and in some ways, object oriented programming (OOP) mirrors the natural world.
I've finally reached the OOP section in the Odin Project's Ruby Programming course. Many of the concepts are straightforward-especially to anyone who has read a little philosophy or studied evolutionary biology. The difficult part is translating the concepts into actual functioning OOP applications.
I've started reading what looks to be a promising book on OOP design in Ruby. I've learned something already that may improve my code. Here's an example from chapter 2:
class Gear
attr_reader :chainring, :cog,
def initialize(chainring, cog)
@chainring = chainring
@cog = cog
end
def ratio
(chainring / cog.to_f).round(2)
end
end
This is the 'good' way to create a class.
Below is the 'bad' way- I've highlighted the offending variables in red.
class Gear
attr_reader :chainring, :cog,
def initialize(chainring, cog)
@chainring = chainring
@cog = cog
end
def ratio
(@chainring / @cog.to_f).round(2)
end
end
The point here is that you should hide variables, even from the class where they are defined. That way, if you need to alter the variables, you can do so with a single method definition.
I'm going to implement this suggestion in the game I'm currently working on.
I've finally reached the OOP section in the Odin Project's Ruby Programming course. Many of the concepts are straightforward-especially to anyone who has read a little philosophy or studied evolutionary biology. The difficult part is translating the concepts into actual functioning OOP applications.
I've started reading what looks to be a promising book on OOP design in Ruby. I've learned something already that may improve my code. Here's an example from chapter 2:
class Gear
attr_reader :chainring, :cog,
def initialize(chainring, cog)
@chainring = chainring
@cog = cog
end
def ratio
(chainring / cog.to_f).round(2)
end
end
This is the 'good' way to create a class.
Below is the 'bad' way- I've highlighted the offending variables in red.
class Gear
attr_reader :chainring, :cog,
def initialize(chainring, cog)
@chainring = chainring
@cog = cog
end
def ratio
(@chainring / @cog.to_f).round(2)
end
end
The point here is that you should hide variables, even from the class where they are defined. That way, if you need to alter the variables, you can do so with a single method definition.
I'm going to implement this suggestion in the game I'm currently working on.
Comments
Post a Comment