mardi 15 novembre 2022

When to use methods vs classes in SOLID?

My Ruby on Rails app has a User and a Plan model. When someone hops on a paid plan, I create a Stripe::Customer and a Stripe::Subscription on Stripe.

This is being done in an action in a functional programming manner. I'm now applying SOLID principles to this action. For now, I have only applied the Single Responsibility Principle.

This is how the code was before:

def create
  user = User.find(params[:user_id]
  plan = Plan.find(params[:plan_id]

  # The following generates the necessary hashes for Stripe from the user and plan objects
  customer_info = { ... }
  subscription_info = { ... }

  customer = Stripe::Customer.create(customer_info)
  subscription_info[:customer] = customer
  subscription = Stripe::Subscription.create(subscription_info)

  # Rest of the code...
end

This is the new code:

def create
  user = User.find(params[:user_id]
  plan = Plan.find(params[:plan_id]

  subscription = SubscriptionHandler.create_subscription(user, plan)

  # Rest of the code...
end

However, I'm a bit undecided on how break down the code in SubscriptionHandler. I am specifically trying to extract the Stripe::Customer creation code in SubscriptionHandler.create_subscription.

Should that code go in a new class like SubscriptionCustomerHandler, like this:

class SubscriptionHandler
  def self.create_subscription(user, plan)
    subscription_info = { ... }

    customer = SubscriptionCustomerHandler.create_customer(user, plan)
    subscription_info[:customer] = customer
    subscription = Stripe::Subscription.create(subscription_info)
  end
end

class SubscriptionCustomerHandler
  def self.create_customer(user, plan)
    customer_info = { ... }
    customer = Stripe::Customer.create(customer_info)
  end
end

Or should it go in a method like SubscriptionHandler.create_customer, like this:

class SubscriptionHandler
  def self.create_subscription(user, plan)
    subscription_info = { ... }

    customer = SubscriptionHandler.create_customer(user, plan)
    subscription_info[:customer] = customer
    subscription = Stripe::Subscription.create(subscription_info)
  end

  def self.create_customer(user, plan)
    customer_info = { ... }
    customer = Stripe::Customer.create(customer_info)
  end
end

What are the advantages/disadvantages of one or the other? How does one decide which one to go for? Also, how do you feel about the SubscriptionHandler name?

Aucun commentaire:

Enregistrer un commentaire