Hi all,

I've got a question for you about how to best design an API that has to handle requests for single objects and collections of those objects.

My naming conventions are: Plural nouns for collections, singular nouns for single objects. "Key_to_value"-style for dictionaries. So I normaly know in my code wether I'm handling collections, dicts or single types.

So, here's an simplified example:
#-----------------------------------------------------------------------
class Meals(object):

    def __init__(self, id_on_menu_to_meal):
        self.id_on_menu_to_meal = id_on_menu_to_meal

#-----------------------------------------------------------------------

Now I need to return one meal by one id_on_menu and also several meals by several ids_on_menu.

I can think of three options:

1) create two methods:
#-----------------------------------------------------------------------
    def get_meal_by_ident(self, ident):
        return self.id_on_menu_to_meal[ident]

    def get_meals_by_idents(self, idents):
        return [self.get_meal_by_ident(ident) for ident in idents]

#-----------------------------------------------------------------------


2) create one method, which is smart enough to discriminate between the input (having fun with the naming conventions ;-)):
#-----------------------------------------------------------------------
    def get_meal_or_meals_by_ident_or_idents(self, ident_or_idents):
        try:
            return self.id_on_menu_to_meal[ident_or_idents]
        except KeyError:
            return [self.id_on_menu_to_meal[ident] for
                    ident in ident_or_idents]

#-----------------------------------------------------------------------


3) handle by convention application-wide only collections:
#-----------------------------------------------------------------------
    def get_meals_by_idents(self, idents):
        return [self.id_on_menu_to_meal[ident] for ident in idents]

#-----------------------------------------------------------------------

Without having too much experience on things like that, my gut feeling tells me to use option 1). What would you guys consider as a best practice here?

Thanks in advance and cheers,

Jan

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to