Skip to content

Instantly share code, notes, and snippets.

@dissolved
Last active May 8, 2019 12:16
Show Gist options
  • Save dissolved/289bd65127eecf71f818424d6db34dad to your computer and use it in GitHub Desktop.
Save dissolved/289bd65127eecf71f818424d6db34dad to your computer and use it in GitHub Desktop.
ABC Complexity and Readability

I was helping out my friend who’s rubocop was complaining on ABC complexity on a method to format a range where either the lower or upper bound or both might be absent. Here was my solution that finally solved it, but here is where I simply wonder if the hoops we jump through to make static code analyzer’s happier isn’t always leading to more readable/maintainable code. You tell me, which is better?

The examples have been simplified to remove implementation details not important to this discussion. example.rb satisfies Rubocop while original.rb gets flagged for ABC complexity.

# frozen_string_literal: true
SYMBOL = {
[false, false] => '%{lower}%{upper}',
[false, true] => '%{lower}<%{upper}',
[true, false] => '%{upper}>%{lower}',
[true, true] => '%{lower}-%{upper}'
}.freeze
def display(lower: nil, upper: nil)
format(SYMBOL[[lower.present?, upper.present?]], lower: lower, upper: upper)
end
# frozen_string_literal: true
def display(lower: nil, upper: nil)
if lower.present?
if upper.present?
"#{lower}-#{upper}"
else
">#{lower}"
end
elsif upper.present?
"<#{upper}"
else
''
end
end
[2] pry(main)> display(lower: 9)
=> ">9"
[3] pry(main)> display(upper: 9)
=> "<9"
[4] pry(main)> display(lower: 2, upper: 9)
=> "2-9"
[5] pry(main)> display
=> ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment