[Tutor] improvement of if - else code

Steve Willoughby steve at alchemy.com
Thu Jun 4 19:36:05 CEST 2009


On Thu, Jun 04, 2009 at 07:25:20PM +0200, Norman Khine wrote:
> Hello,
> Is there a better way to write this:

Depends on what's cleaner and clearer for what you're doing,
especially as the complexity of this code grows.  For example,
if the only difference is which method to call, one approach 
might be to call one method which figures out which set of countries
to return:

	context = get_context()
	root = context.root

	countries = [{...} for x, y in root.get_countries(context, hotel)]

Alternatively, you can put some logic up front which determines which
method to call later, removing the if/else and repetition of code:

	context = get_context()
	root = context.root
	method = root.get_active_countries if hotel else root.get_authorized_countries

	countries = [{...} for x, y in method(context)]


> 
>     @staticmethod
>     def get_form(address=None, postcode=None, town=None, phone=None, fax=None,
>                  freephone=None, address_country=None, address_region=None,
>                  address_county=None, hotel=None):
>         context = get_context()
>         root = context.root
>         # List authorized countries
>         if hotel is True:
>             countries = [
>                 {'name': y, 'title': x, 'selected': y == address_country}
>                 for x, y in root.get_active_countries(context) ]
>         else:
>             countries = [
>                 {'name': y, 'title': x, 'selected': y == address_country}
>                 for x, y in root.get_authorized_countries(context) ]
> 
> Thanks
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Steve Willoughby    |  Using billion-dollar satellites
steve at alchemy.com   |  to hunt for Tupperware.


More information about the Tutor mailing list