开发者

Is it better to have standalone functions in globals or group them in a class?

I have inherited code in which there are standalone functions, one per country code. E.g.

def validate_fr(param):
    pass

def validate_uk(param):
    pass

My idea is to create a class to group them together and consolidate the code into one method. Unfortunately that breaks cohes开发者_如何学Cion. Another option is to dispatch to instance methods ?

class Validator(object):
    def validate(param, country_code):
       # dispatch 

Alas, python does not have a switch statement.

UPDATE: I am still not convinced why I should leave them as global functions in my module. Lumping them as class methods seems cleaner.


I would keep the functions at module level -- no need for a class if you don't want to instantiate it anyway. The switch statement can easily be simulated using a dicitonary:

def validate_fr(param):
    pass

def validate_uk(param)
    pass

validators = {"fr": validate_fr,
              "uk": validate_uk}

def validate(country_code, param):
    return validators[country_code](param)

Given the naming scheme, you could also do it without the dictionary:

def validate(country_code, param):
    return gloabls()["validate_" + country_code](param)


You do not need a switch statement for this.

validators = {
  'fr': Validator(...),
  'uk': Validator(...),
   ...
}

 ...

validators['uk'](foo)


Classes are not meant to group functions together, modules are. Functions in a class should be either methods that operate on the object itself (changing it's state, emitting information about the state, etc.) or class methods that do the same, but for the class itself (classes in Python are also objects). There's not even a need for static methods in Python, since you can always have functions at module level. As they say: Flat is better than nested.


If you want to have a set of functions place them in separate module.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜