3
\$\begingroup\$

I consider these two options exactly the same. I prefer the first one but I'm not sure if it's better than the second option in terms of cyclomatic complexity or readability.

Assuming that this is not pure Ruby and I can call to the try method.

existing_transaction = database.find_transaction_by_id(transaction.id)
database.create_transaction(transaction) unless existing_transaction
database.update_transaction(transaction) unless existing_transaction.try(:processed)
existing_transaction = database.find_transaction_by_id(transaction.id)
if existing_transaction
 unless existing_transaction.processed
 database.update_transaction(transaction)
 end
else
 database.create_transaction(transaction)
end
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Mar 15, 2014 at 13:25
\$\endgroup\$

2 Answers 2

4
\$\begingroup\$

It's obviously subjective, but IMHO inline conditionals make code harder to understand, indentation is very important. So I'd definitely take the second approach, but writing it differently to use only one indentation level:

existing_transaction = database.find_transaction_by_id(transaction.id)
if !existing_transaction
 database.create_transaction(transaction)
elsif !existing_transaction.processed
 database.update_transaction(transaction)
end
answered Mar 15, 2014 at 13:47
\$\endgroup\$
1
\$\begingroup\$

I would actually take a mixed approach:

if existing_transaction
 database.update_transaction(transaction) unless existing_transaction.processed
else
 database.create_transaction(transaction)
end

This way the code is more readable than the first option, but more succinct than the second option.

answered Mar 15, 2014 at 16:46
\$\endgroup\$
2
  • \$\begingroup\$ This is exactly my solution wrote with unless inlined. \$\endgroup\$ Commented Mar 15, 2014 at 19:57
  • \$\begingroup\$ Yes, it is - it just reads better IMHO \$\endgroup\$ Commented Mar 15, 2014 at 20:18

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.