vendredi 7 juin 2019

Design pattern to avoid checks in each method of the Python class

What would be the best approach to avoid checks in each method.

As seen in below example, check is happening in each and every method to make sure app is either connected or not connected.

Any design patterns or other elegant solution to avoid checks and repetition of the code ?

class App:

    def __init__(self):
        self._is_connected = False

    def connect(self):
        if self._is_connected:
            raise Exception('Already connected')
        pass

    def disconnect(self):
        if not self._is_connected:
            raise Exception('Already disconnected')
        pass

    def send_data(self):
        if not self._is_connected:
            raise Exception('Not connected')
        pass

    def recv_data(self):
        if self._is_connected:
            raise Exception('Not connected')
        pass

Aucun commentaire:

Enregistrer un commentaire