Does it make sense to include callback and errback when running inside an EM.defer?

StackOverflow https://stackoverflow.com/questions/18193609

  •  24-06-2022
  •  | 
  •  

Pergunta

I'm trying to integrate some blocking libraries/operations inside EventMachine, and I've considered encapsulating such code inside a class that includes EM::Deferrable. Does it make sense to have such code in a Deferrable object:

class Whatever
  include EM::Deferrable
  def some_operation
    result = some_blocking_operations
    if result.considered_success?
      succeed(result)
    else
      fail(result)
    end
  end
end

or should I just stick to:

op = lambda do
  result = some_blocking_operations
end

cb = lambda do |res|
  # do some kind of if here to check if it's success or failure
end

EM.defer(op,cb)

Personally, I prefer the first one, since for me it reads a bit better. Does it make sense to implement deferrable in such a case?

Foi útil?

Solução

Your first implementation looks way more OOP to me. Using lambdas is great and very flexible but if things start to get complicated you'll endup with a bunch of random lambdas and no way to tell what they are actually doing.

To answer your question, yes it makes sense to me to create a class to run your blocking code.

Also, you'll have a place to put all your private methods related to your blocking actions logic.

Finaly, if you name your class carefuly, it won't be hard for any developer to understand the basic idea behind that class. If further informations are needed, he would just have to digg into the code.

I think lambdas are a poor design in this case. Pretty sure you'll be thanking yourself for using classes when things will get more complexe (it always does).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top