zuhao / plotrb

A plotting library in Ruby built on top of Vega and D3.
Other
42 stars 12 forks source link

Refactoring in transforms.rb #8

Closed pjotrp closed 11 years ago

pjotrp commented 11 years ago

I have a problem reading this code. I presume symbols like :round are JSON tags and you are setting properties after validation. Is there no more elegant and clear way that this code can work?

    def treemap(args)
      valid = args[:value] && (args.keys - [:padding, :ration, :round, :size,
                                            :sticky, :value]).empty?
      valid &&= args[:value].is_a?(String)
      valid &&= args[:padding].nil? || args[:padding].is_a?(Numeric) ||
          array_of_Numeric?(args[:padding], size=4)
      valid &&= args[:ratio].nil? || args[:ratio].is_a?(Numeric)
      valid &&= args[:round].nil? || [true, false].include?(args[:round])
      valid &&= args[:size].nil? || array_of_Numeric?(args[:size], size=2)
      valid &&= args[:sticky].nil? || [true, false].include?(args[:sticky])
      if valid
        set_properties(args)
      else
        raise ::Plotrb::InvalidInputError
      end
    end

Maybe you should be using a proper parser/lexer to do this stuff. I mean, if Vega is much larger, this is going to be problematic.

clbustos commented 11 years ago

Maybe, args hash should be replaced with specific Structs. The Struct could be responsible of verification of parameters, so you could separate the logic of the method from the parameter checking.

translunar commented 11 years ago

Ahh! This is a common issue. "When is it appropriate to check arguments and when not?"

Don't check arguments when:

Do check arguments when:

I think generally the appropriate exception to raise is ArgumentError. Sometimes it's something else, like a FileError. Try to find similar examples elsewhere in Ruby code, especially ruby-core.

zuhao commented 11 years ago

A few rounds of refactoring have been done and this issue can be closed.