문제

Say an API returns the following pieces of data:

  • daily_price
  • number_of_days
  • total_price

Assume that the API will always have the number_of_days and at least daily_price or total_price.

In cases when the API only has the daily_price or total_price, should the API compute the missing value (e.g. daily_price * number_of_days = total_price) - or should it leave it to the consumer to calculate? And if the API did compute the missing value, should it indicate which of the two values (if any) was computed?

도움이 되었습니까?

해결책

The mistake is mixing them together.

If the api provides totals it shouldn't provide what it used to arrive at that total.

If the api provides the dependencies used to calculate the total it shouldn't also calculate the total.

The reason why is because these are two different levels of abstraction. You can provide both api's but they should be separate beasts. You should be able to use one without getting the other in the bargain.

Look at your using code when making these decisions. Don't just look at the data and try to imagine all of it's uses. Start from the real uses you have now.

다른 팁

Should an API return calculated values that the consumer can calculate themselves?

Short answer:

Yes.

Long answer:

What are the advantages for letting the client compute the missing information? Are you saving bandwidth because there is less bytes transmitted over the network? Do you have a cleaner API by not returning derived data from the core data? What's the reason to not just compute this field?

Even if you have a reason. What you are doing is increase the coupling between your server API and your clients. If, for example, you return daily_price and number_of_days then the client needs to compute total_price. Always.

What if at some point this is no longer a multiplication? But some other other rules start to apply? Maybe new regulations introduced? I'm speculating here but what if taxes apply beyond a certain total amount? What if you want to apply discounts for certain total amounts? And a bunch of any other cases that changes the rules of the game?

If the rules change at some point, are you going to contact all your clients and have them change their code to now handle the new rule? This is your API, thus your responsibility. Don't put part of the responsibility for your API on your clients. Just add the derived/redundant data to your responses. You are not gaining anything if you don't.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 softwareengineering.stackexchange
scroll top