The Real Adam Always course correcting

Posted
6 August 2008 @ 12pm

In
Code

Refactoring to more code

Refactor my code is a neat site where you can post your code and watch others refactor it. I saw an interesting bit of code whiz past and thought I’d take a crack at it.

Removing conditionals from code is one of the little games I sometimes play while coding. Here, I’ve extracted the logic of the conditional into another class. The resulting class is much more code than the original. So why do that?

Well, I say you get a few benefits:

  • The logic is now far easier to test. It’s a standalone object now rather than a Rails functional test.
  • The flow of what’s being done and tested is more decomposed and easier to follow.
  • Most importantly, the code explains itself. No need for comments (which will undoubtedly go out of sync over time) here!

While I delight in deleting code and writing as little as possible, refactoring this to more code seems the right way. What say you?

Update: Make sure you check out Marcel Molina’s refactoring. Its probably better than mine ;)


2 Comments

Posted by
http://edspencer.net/
6 August 2008 @ 3pm

I like it - very neat. But isn't it amazing how what one guy does in 12 lines another does in 6 and another in 40, all to achieve the same result? I wonder how often people write thousands instead of tens, and how often each is better.


Posted by
Ryan Carmelo Briones
7 August 2008 @ 7pm

I think the determination of whether Marcel’s or your refactoring is “better” highly dependent on context, which we don’t have here. However, if this action is indicative of a pattern in the application, your refactoring is a good step forward. If I were giving your refactoring, I’d probably either encapsulate more by passing in the controller object ending up with something like PasswordValidator.handle_demo_user(self, params[password]) or gone the other direction with a mix of your’s and Marcel’s.


Leave a Comment

Program is information. American demographic inversion

Flickr View All » RubyConf Notes #3RubyConf Notes #2RubyConf Notes #1RubyConf Notes #0Dogs in the morningMy Day, YesterdayGetting aroundMolly loungingasdfjkl;