te25son / Jokes

CLI app for jokes
0 stars 0 forks source link

Double validation in submit pipeline #21

Open te25son opened 2 years ago

te25son commented 2 years ago

There is a performance downgrade introduced in #19 .

Due to the inheritance of JokeSingleSubmit + the workflow of using JokeBase to match the joke type, "type" and "category" are validated twice in the submit pipeline.

Screen Shot 2022-08-07 at 4 10 21 PM

te25son commented 2 years ago

After investigating the pydantic docs, it doesn't seem there's a possibility to skip only certain fields. Pydantic does offer a construct method on all models that inherit from BaseModel but simply creates the model without any validation.

It is possible to delay the validation until the JokeSingleSubmit is called by using the construct method to build the joke base. So something like

joke = JokeBase.construct(**data)

However, this would make the use of match_type less safe since the type hasn't been validated at this point. If the type is not valid, the method can raise a key error when converting the string to an enum in Type[self.type].

Of course, the type should never be invalid since it's coming directly from click which also checks that the input is valid 🤷‍♂️ Also the method is wrapped inside a @safe decorator, so even it if fails, it won't display anything to the user unless the debug flag is activated.

All in all, if we want to improve the performance slightly, while also having plenty of safety checks in place, we could simply use the construct method as mentioned above and delay the validation until the JokeSingleSubmit or JokeTwopartSubmit models are created.