samedi 5 février 2022

Find the right pattern for code duplication

I have a car service that is using car api to work with the car. The problem is that I use get_driver_car in every single method of my service to get the car object and in the end I use update_car method to save the data. From my perspective, it seems like these two methods can be used from another method but I have no idea how to refactor this code. I would be glad to hear all suggestions

class CarService(object):
    def __init__(self):
        self.api = CarApiService()

    def add_branding(self, car_id: str):
        car = self.api.get_driver_car(json.dumps({'car_id': car_id}))['car']
        if 'sticker' not in car['amenities']:
            car['amenities'].append('sticker')

        if 'lightbox' not in car['amenities']:
            car['amenities'].append('lightbox')

        return self.api.update_car({'car_id': car_id, 'data': json.dumps(self.create_car_request(car))})

    def remove_branding(self, car_id: str):
        car = self.api.get_driver_car(json.dumps({'car_id': car_id}))['car']
        
        if 'sticker' in car['amenities']:
            del car['amenities'][car['amenities'].index('sticker')]

        if 'lightbox' in car['amenities']:
            del car['amenities'][car['amenities'].index('lightbox')]

        return self.api.update_car({'car_id': car_id, 'data': json.dumps(self.create_car_request(car))})

    def add_booster(self, car_id:str):
        car = self.api.get_driver_car(json.dumps({'car_id': car_id}))['car']

        if car['booster_count'] == 0:
            car['booster_count'] = 1
        else:
            return None

        return self.api.update_car({'car_id': car_id, 'data': json.dumps(self.create_car_request(car))})

    def remove_booster(self, car_id: str):
        car = self.api.get_driver_car(json.dumps({'car_id': car_id}))['car']

        if car['booster_count'] == 1:
            car['booster_count'] = 0
        else:
            return None

        return self.api.update_car({'car_id': car_id, 'data': json.dumps(self.create_car_request(car))})
    def create_car_request(self, car: dict) -> dict:
        del car['is_readonly']
        del car['created_date']

        return car

Aucun commentaire:

Enregistrer un commentaire