How to explain failure with complex constraints

I am introducing a system in which a client can use vouchers to receive discounts for a purchase. If a voucher can be used for a specific purchase, it depends on several circumstances.

For instance:

  • Correct voucher code - correct code?
  • Range - is the voucher still valid?
  • Can I use a voucher with a purchase type?
  • Combination allowed - can a voucher be combined with other vouchers?
  • many more ...

There are also some more complex restrictions that need to be checked. If one or more of the restrictions is not met, the client cannot use the voucher, and I would like to inform him of an error explaining “WHY” that he cannot use this voucher, for example:

"You cannot use this voucher because it is outdated."

Now my question is: How would you implement checks?
Inject each constraint into its own class, link them and throw exceptions? (The problem is here, it is possible to execute several identical database queries) To implement all the restrictions in one method? (really why?) In general, how do you implement a mechanism in which you should inform the client about the details of the failure if a complex restriction is applied to the action?

Thank,

+3
source share
3 answers

Personally, I would only perform checks with one method. A voucher arrives, an error message appears (if any).

, , . , - , ..

, ( - , , ).

.

+2

, , , . , .

- :

let reasons be a new, empty collection of failure reasons 
let checkers be the list of relevant checkers

for each checker in checkers
    if checker passes, continue
    if checker fails, add explanation to reasons

if number of reasons is zero, 
    voucher is valid, success
if number of reasons > zero, 
    the voucher is invalid, format each element in reasons for display to the user

, , , . , , . , . , , ( - ).

, , , .

. , .

... . . , , .

:

  • , , (, , -).
  • , : - . .
  • , .

:

  • . , .
  • , , . . , . , , , , , , , , , .

Java, . , .

0

, . , "" ( , ..), , .

This works with a single validation method that returns an array of related problems. The main checker method calls more specific verification methods to build the array. He may decide to skip some checks if others have not already worked.

0
source

Source: https://habr.com/ru/post/1730047/


All Articles