1

I'm writing an application in Python. Somewhere, I write a model layer composed with classes, and, any of them, say:

class Orders:

has a bound method whose signature is :

def delete(self, id=None, name=None):

I need id or name not to be None. Then, here is my question:

Since I myself write the model layer and the client code, which would be something like:

model.Orders().delete(id=1234)

Would be good practice to check the parameters inside the delete method with code like:

if not any((id, name)):
    raise ValueError('Order Id or Order name must be provided')

?

I think, since I write the two sides, I will always call the delete method providing one of the parameters avoiding checking and saving a lot of code. I expect the model layer will reach 2 or 3 thousand lines, interfacing a database server.

I put a specific example, but I'd appreciate an answer for the general case.

2 Answers2

1

This was discussed here and here.

I would add, however, that since Python does not support mutually exclusive arguments by default, the clean way would be to provide two public interfaces: delete_by_id, delete_by_name; and these ones call a private method _delete. This way the facade to users of the class is clear and enforces the arguments nicely, while from within the class you reuse the code.

miquelvir
  • 1,748
  • 1
  • 7
  • 21
  • 1
    Ok. I better expose a clean interface, If the company hires another developer, for the GUI part, he/she will be writing client code against this model. –  Mar 26 '21 at 12:11
0

In general case, according to me, it is always a good practice to prevent error and misuse in your code. It is true that you can save a lot of coding but what is the price? Someday in the future you will be using this code not remembering to provide one of the two parameters and you can lose hours in debuging. Or maybe you could opensource your code and someone trying to use it may have some problem.

Ad Fortia
  • 333
  • 1
  • 3
  • 12
  • 1
    I like your answer. Maybe in the future, the company hires another developer (Now I'm alone) who will be interfacing this model, so, I better write a clean interface as @miquelvir suggests with a "private" _delete method. –  Mar 26 '21 at 12:08