Ruby thread control: throw an exception, return zero or crash it?

I think of the best flow control methods. Which direction should I go?

1) Do not check anything or run the program (cleaning code, natural error messages):

  def self.fetch(feed_id)
    feed = Feed.find(feed_id)
    feed.fetch
  end

2) Unsuccessful failure by returning null (however, "Clean Code" says you should never return null):

  def self.fetch(feed_id)
    return unless feed_id
    feed = Feed.find(feed_id)
    return unless feed
    feed.fetch
  end

3) Throw exceptions (because this excludes the possibility of searching for a feed by id):

  def self.fetch(feed_id)
    raise ArgumentError.new unless feed_id
    feed = Feed.find(feed_id)
    raise ArgumentError.new unless feed
    feed.fetch
  end

In other words: should you actively use the protective conditions, or is it better to rely on the Ruby / Rails methods and let them throw an exception if something goes wrong?

+5
source share
3 answers

1) - ( , ):

, " " , , NoMethodError, nil, . ActiveRecord#find ActiveRecord::RecordNotFound, :

def self.fetch(feed_id)
  Feed.find(feed_id).fetch
end

2) , (, " " , null):

, , Ruby , nil; ( , ), "Nothing" ( something_that_can_be_nil || another_value). Ick maybe:

def self.fetch(feed_id)
  Feed.find_by_id(feed_id).maybe.fetch
end

3) ( , ID):

, RecordNotFound, ( , AR, ).

+6

, : . - . . ( - ).

, , , , . , . . , , .

, . , - . , - . , , .

, , . .

+2

.

feed_id fetch, ArgumentError: wrong number of arguments(0 for 1), β„– 3 .

feed_id, Feed.find(feed_id) , , ActiveRecord::RecordNotFound , , ( feed_id nil), .

It seems to me that it’s stupid to call a method with feed_id = nil, so I would probably argue that β€œif you send the wrong input, it may break”, in which case I think that ActiveRecord::RecordNotFoundwill give you much more information about what went not like if you raise ArgumentError.

Returning a null value is rarely good, as it will not tell you what really went wrong. Therefore, I also exclude No. 2.

+2
source

All Articles