-2

Which code should I prefere and why? Is there some general rule?

Code 1:

var apiLicenseInfo = GetLicenseFromApi(string userId, string deviceId);
var localLicenseInfo = MapToLocalLicense(apiLicenseInfo);

Code 2:

var apiLicenseInfo = GetLicenseFromApi(string userId, string deviceId);
var localLicenseInfo = MapToLocalLicense(apiLicenseInfo, userId, deviceId);

In Code 1 arguments (userId and deviceId) passed to method GetLicenseFromApi are returned in result of method. Then the result is translated to another object using only the result of previous method.

In Code 2 arguments (userId and deviceId) are not returned in result of GetLicenseFromApi method and must be passed to second method.

In my opinion the Code 1 is more consistent, but sends unnecessary data.

  • 2
    This is akin to building a new house and stressing over the wall color of one bathroom before considering anything else. Questions like this should be viewed in the context of your entire domain, how those methods are used, and how your classes are defined. Either approach could make sense. More important questions are does the application serve its purpose and is the code maintainable? – Dan Wilson Oct 16 at 12:20
  • The building is built already and I am trying to paint bathroom. In this example the context is quite simple in my opinion: querying the api, nothing more. I thought that there are some rules which I am not aware of. – raV720 Oct 16 at 12:34
  • 2
    In the second case, what would happen if you use different userIds for each call? – Jacob Raihle Oct 16 at 13:45
  • 2
    You store the return value of GetLicenseFromApi() in apiLicenseInfo but then pass apiLicense to the mapping function. Is that a typo? – besc Oct 16 at 18:31
  • @besc yes, it is a typo. Fixed – raV720 Oct 19 at 6:08
1

Knowing nothing about the context of your concrete application I can only answer in general. Keeping that in mind: Prefer Code 1.

I see two guidelines at work here:

  1. Aim to design your APIs in a way that makes using them incorrectly impossible. The best programming error is the one that cannot happen. Only if such a design is not feasible detect and report programming errors – i.e. assert.
  2. Aim for self-contained data structures. If a licence is only valid for a certain user and device those three pieces of information belong together semantically. As soon as you start passing non self-contained data around you run the risk of losing important pieces or introducing a mismatch.

Code 1 satisfies both guidelines, Code 2 doesn’t.

| improve this answer | |
  • Thank you very much. This is what I needed. – raV720 Oct 19 at 6:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.