refactor large switch-statement

时间:2014-12-09 20:04:27

标签: refactoring switch-statement conditional

重构这个丑陋案例的任何建议 - 转换成更优雅的东西?

这个方法(在Ruby中)给出比利时省份的(简短或完整)描述,给定一个邮政编码。

def province(zipcode, short = false)
  case zipcode
  when 1000...1300
    short ? 'BXL' : 'Brussel'
  when 1300...1500
    short ? 'WBR' : 'Waals-Brabant'
  when 1500...2000, 3000...3500
    short ? 'VBR' : 'Vlaams-Brabant'
  when 2000...3000
    short ? 'ANT' : 'Antwerpen'
  when 3500...4000
    short ? 'LIM' : 'Limburg'
  when 4000...5000
    short ? 'LIE' : 'Luik'
  when 5000...6000
    short ? 'NAM' : 'Namen'
  when 6000...6600, 7000...8000
    short ? 'HAI' : 'Henegouwen'
  when 6600...7000
    short ? 'LUX' : 'Luxemburg'
  when 8000...9000
    short ? 'WVL' : 'West-Vlaanderen'
  when 9000..9999
    short ? 'OVL' : 'Oost-Vlaanderen'
  else
    fail ArgumentError, 'Not a valid zipcode'
  end
end

根据MiiinimalLogic的建议,我制作了第二个版本。这更好吗?

class Provincie
  ProvincieNaam = Struct.new(:kort, :lang)

  PROVINCIES = {
    1000...1300 => ProvincieNaam.new('BXL', 'Brussel'),
    1300...1500 => ProvincieNaam.new('WBR', 'Waals-Brabant'),
    1500...2000 => ProvincieNaam.new('VBR', 'Vlaams-Brabant'),
    2000...3000 => ProvincieNaam.new('ANT', 'Antwerpen'),
    3000...3500 => ProvincieNaam.new('VBR', 'Vlaams-Brabant'),
    3500...4000 => ProvincieNaam.new('LIM', 'Limburg'),
    4000...5000 => ProvincieNaam.new('LIE', 'Luik'),
    5000...6000 => ProvincieNaam.new('NAM', 'Namen'),
    6000...6600 => ProvincieNaam.new('HAI', 'Henegouwen'),
    6600...7000 => ProvincieNaam.new('LUX', 'Luxemburg'),
    7000...8000 => ProvincieNaam.new('HAI', 'Henegouwen'),
    8000...9000 => ProvincieNaam.new('WVL', 'West-Vlaanderen'),
    9000..9999  => ProvincieNaam.new('OVL', 'Oost-Vlaanderen')
  }.freeze

  def self.lang(postcode)
    provincie_naam(postcode).lang
  end

  def self.kort(postcode)
    provincie_naam(postcode).kort
  end

  def self.provincie_naam(postcode)
    PROVINCIES.each { |list, prov| return prov if list.cover?(postcode) }
    fail ArgumentError, 'Geen geldige postcode'
  end

  private_class_method :provincie_naam
end

2 个答案:

答案 0 :(得分:0)

就个人而言,我指定了拉链范围&不同数据结构中的省信息a la Range对象/省的映射,然后使用Ruby的Range方法检查结果是否落在范围方法的范围内。

答案 1 :(得分:0)

您可以考虑只使用一个范围查找,无论是在此处还是使用地图结构,都可以从简短描述到长描述进行辅助查找(可能在地图中)。