Daily Refactor #75: Inline Temp in Invoices#outstanding

I decided to move to another section of Invoice before I tackle the finder used in Invoice#open. I’m thinking about using a simple state machine for the different invoice states and that will require some redesign. I found it’s best to think about redesigns for time before starting on them.

The Refactoring

Today I refactored the inner logic of Invoice#outstanding to replace how a temp variable is being used.

Before

1
2
3
4
5
6
7
class Invoice  0.0
      return total
    else
      return 0.0
    end
  end
end

After

1
2
3
class Invoice  0 ? total : 0.0
  end
end

Review

This was a simple method but it was doing two things wrong:

  1. There was too much code to do a simple arithmetic operation.
  2. payments.collect(&:amount).sum was creating a bunch of ActiveRecord objects that would just get thrown away. The new code uses SQL to sum the amount field directly.

I’m thinking about changing this method so it will return negative amounts when there is an overpayment. If that happens, I can remove the ternary operation entirely.

Reference commit

Share

  • Facebook
  • Twitter
  • HackerNews
  • Reddit
  • Tumblr
  • Delicious
  • Email
  • RSS

Related posts:

  1. Daily Refactor #70: Inline Temp in SourceVersion#migrate
  2. Daily Refactor #69: Inline Temp in SourceNews#migrate

About Eric Davis

I founded Little Stream Software where I provide Redmine and ChiliProject services to help projects teams. I also created an ebook, Redmine Tips, were I show you how to become more productive using Redmine. I am also the author of Refactoring Redmine, where I go about refactoring Rails using Redmine as an example.

, , ,

Chirk HR     Reuse your existing job applicants »
WP Socializer Aakash Web