Question

This is more of a general question. And it might be dumb but since I constantly have this dilemma- decided to ask.

I have a function (in Rails if it matters) and I was wondering which approach is best practice and more common when writing large apps.

def retrieve_object(id_of_someobject)
   # Gets class object ID (integer)
   OtherObject.where('object_id = ?', id_of_someobject)
end

Here for example it receives 12 as id_of_someobject

OR

def retrieve_object(someobject)
   # Gets class object
   OtherObject.where('object_id = ?', someobject.id)
end

Here it gets class object and gets its ID by triggering the object attribute 'id'.

Was it helpful?

Solution

In this instance I would prefer the second approach. They may be functionally equivalent, but in the event that there's an error (e.g. calling nil.id), it makes more sense to handle that within the function so that it's easier to debug in the event of failure.

For the first approach, passing in nil wouldn't result in an error, but rather would return an empty array. So it might be difficult to know why your results aren't what you expected. The second approach would throw a flag and tell you exactly where that error is. If you wanted to handle that case by returning an empty array, you could do so explicitly.

As Michael mentioned, passing the whole object also gives you the flexibility to perform other operations down the road if you desire. I don't see a whole lot of benefit to evaluating the id and then passing it to a method unless you already have that ID without having to instantiate the object. (That would be a compelling use case for the first option)

OTHER TIPS

Support both. It's only one more line and this way you don't have to remember or care.

def retrieve_object(id_or_someobject)
   id = id_or_someobject.is_a?(SomeObject) ? id_or_someobject.id : id_or_someobject
   OtherObject.where('object_id = ?', id)
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top