Functional patterns help make your code simpler and easier to test when you use them with object-oriented programming (OOP).
0
0
Why functional patterns complement OOP in Ruby
Introduction
When you want to keep your objects focused on their main job without extra side effects.
When you need to write small, reusable pieces of code that do one thing well.
When you want to avoid changing data directly to prevent bugs.
When you want to make your code easier to understand by separating data and behavior.
When you want to test parts of your program independently.
Syntax
Ruby
# Example of a functional method in Ruby def add_one(number) number + 1 end # Example of an OOP class class Counter def initialize @count = 0 end def increment @count += 1 end def value @count end end
Functional methods usually take inputs and return outputs without changing anything else.
OOP classes bundle data and actions together to model real-world things.
Examples
This is a simple functional method that returns the square of a number.
Ruby
def square(x) x * x end
This class uses OOP to store a person's name and greet them.
Ruby
class Person def initialize(name) @name = name end def greet "Hello, #{@name}!" end end
This functional method takes a name and returns a greeting without storing any data.
Ruby
def greet_person(person) "Hello, #{person}!" end
Sample Program
This program shows how a functional method double can be used inside an OOP class Calculator to keep code simple and reusable.
Ruby
def double(number) number * 2 end class Calculator def initialize(value) @value = value end def double_value double(@value) # Using functional method inside OOP end end calc = Calculator.new(5) puts calc.double_value
OutputSuccess
Important Notes
Functional patterns help keep methods pure, meaning they don't change outside data.
OOP helps organize code around objects, but mixing in functional methods can reduce complexity.
Using both styles together can make your programs easier to read and maintain.
Summary
Functional patterns focus on small, reusable methods without side effects.
OOP organizes code around objects with data and behavior.
Combining both helps write clearer and more reliable Ruby programs.