jeudi 25 février 2016

Design-pattern/solution for logically similar functions without code dupplication

I am looking for an elegant solution for the following (generic) problem. I want to implement several protocols to access files. Let's say ftp and tftp. More may be added in the future. Right now i'm doing:

get_file(filename):
  # some generic code for opening the file etc.
  if mode == 'ftp':
    get_file_ftp(filename)
  else:
    get_file_tftp(filename)
  # some generic code for closing the file etc.

get_file_ftp(filename):
  # ftp-specific code

get_file_tftp(filename):
  # tftp-specific code

Same for put_file(), ls() and a dozen more funtions. As code grows, this is starting to get ugly. So my question is: Is there a more clever way to get the job done? Is thera a design pattern that makes sense for this use case? If so, how would i accomplish this in Python?

Aucun commentaire:

Enregistrer un commentaire