NoName
NoName

Reputation: 10334

Should input validation be done redundently to be safe?

Say classA takes in a credit card number as its parameter. It checks whether that credit card number exists, then passes it onto classB to be processed.

Should classB also check if the credit card number is valid, even though it will always get the credit card number from classA which already validated that?

ClassB will not be reused by any other classes in the foreseeable future.

Upvotes: 1

Views: 27

Answers (1)

user3437460
user3437460

Reputation: 17454

Should classB also check if the credit card number is valid, even though it will always get the credit card number from classA which already validated that?

If we are trying to achieve low code coupling with high cohesion, whenever possible, you should be separating the task for each class and method with clear boundary.

You do not want to have duplicated, or semi-duplicated jobs. If you set a clear job scope for each class, you may realize each class can somewhat work independently and the code may even be reused to work with other classes.

Just imagine, one day you need to amend the rules for validating credit card number, you ended up having to make amendments for classB as well. At worst, classA is validating for classC to classZ as well and you have to make changes to all who work with classA.

So generally, you should "trust" classA to do its job well, and classB only needs to concentrate on its own task.

Upvotes: 1

Related Questions