lundi 16 janvier 2017

How to refactor similar methods?

I develop class that manages connections to external resources. Its responsibility is reading credentials from given source and returning authenticated connections, like:

def get_svn_connection(self):
    username, pwd=self.get_credentials("SVN")
    client=self.get_svn_client(username, pwd)
    return client

def get_db_connection(self):
    username, pwd, url, schema=self.get_credentials("DB")
    client=self.get_db_client(username, pwd, url, schema)
    return client

Today I met new use case: sometimes user needs to get only credentials without connection. So, following current solution, I have to create methods get_svn_credentials, get_db_credentials and so on. It looks very redundant so I want to refactor this structure. My ideas are:

  1. Create subclasses for every connection type and for each of them define methods get_connection and get_credentials. The problems are: 1) I want one class to rule all the connections; 2) I would have to use multi-inheritance (possible in Python, but would not work in, for example, Java - if I'll meet this problem in future)

  2. Create methods get_connection(type) and get_credentials(type) and for every known connection type specified by string return corresponding instance. Problem is I have to create a switch which considered bad in OOP.

  3. Use metaprogramming to generate methods for every connection types. Not obvious and Python-specific.

    How would you design this?

Aucun commentaire:

Enregistrer un commentaire