Functional Classes

Oskar Szrajer,  Feb 27, 2017

Most of us spend their careers working with Object Oriented code. Because of it we learn automatically explain every new issue using object. We often forget that most languages are multi-paradigm and we can write our code in different way. One of important lesson, that change the way how I write Service Objects (and many other classes too), I learned from functional programming approach.

Normal classes we write every day, we initialize with some values and then call methods on those instance. For example like this one:

class CreateUser
  attr_reader :data

  def initialize(data)
    @data = data
  end

  def call
    UserRepo.create(data)
  end
end

Looks normal, isn’t it? But the problem with this class is we can use every of it instance only once. We need to create new one for every user we want add to our system.

john_data = { name: "John", age: 12 }
paul_data = { name: "Paul", age: 25 }

john = CreateUser.new(john_data).call
paul = CreateUser.new(paul_data).call

Most of you probably will tell, where’s the problem? Creating new instances are cheap and we have great stuff like garbage collectors so we don’t need to worry about memory and number of objects inside it. That’s true but with simple change we can reuse one instance all the time. Why not?

class CreateUser
  def call(data)
    UserRepo.create(data)
  end
end

john_data = { name: "John", age: 12 }
paul_data = { name: "Paul", age: 25 }

create_user = CreateUser.new

john = create_user.(john_data)
paul = create_user.(paul_data)

This technique will simplify code and (what the most important) simplify writing tests. Because create_user is a simple function we can change it with simple proc:

DB = []

user_repo = -> (data){ DB << data }
create_user = -> (data){ user_repo.(data) }

john_data = { name: "John", age: 12 }
paul_data = { name: "Paul", age: 25 }

create_user.(john_data)
create_user.(paul_data)

Functions like that can be easily chained and called as a group of transactions. But it’s a topic for another time. Hope some of you will find it useful and start using in everyday work.

Author
Oskar Szrajer

Oskar is a full-stack developer & software architect. He’s driven by contributing to beautiful user - and customer-driven applications and will dive into any aspect of an application, in any technology, if it will help serve a well-fitting end result.

Published on:

Feb 27, 2017

Tags