vendredi 29 mars 2019

How to refactor two functions that require all of the same but one parameter?

I have two methods that take all but one of the same parameters and run the same code except one additional line for one of the methods. I'm trying to decide what the best approach is to clean up the functions so I'm not duplicating code. Here are the methods in question.

I've tried using a try/except clause, but I feel like that is clunky and overkill. I am considering adding a param to a function that notes if the intent is to create or edit a file but that feels too restrictive.

def create_file(self, file_blob, filename, commit_message, committer_info, branch):
    json_file_data = self._file_data(file_blob, commit_message, committer_info, branch)
    content_url = '{}/{}'.format(self._github_content_url, filename)
    response = self._request(content_url, method='PUT', data=json_file_data)
    self._handle_errors(response)

def edit_file(self, file_blob, filename, commit_message, committer_info, branch):
    file_blob_sha = self._latest_blob_sha_for_file(branch, filename)
    content_url = '{}/{}'.format(self._github_content_url, filename)
    json_file_data = self._file_data(file_blob, commit_message, committer_info, branch, file_blob_sha)
    response = self._request(content_url, method='PUT', data=json_file_data)
    self._handle_errors(response)

Aucun commentaire:

Enregistrer un commentaire