exception - Method that fails loudly vs silently -
i have method (or function, or procedure, doesn't matter sake of question) void dostuff()
. has depends on data , has side effects. also, valid operation in state; in other state operation can not performed.
now, although i'm developing api, i'm thinking api used. there 2 typical situations operation performed:
user code should've checked, if state valid, , implement custom logic of it's own if it's not. if code ends trying implement operation in invalid state means it's programmer error, , should reported , investigated.
the client doesn't need custom logic in case, , doesn't need know if operation successful or not.
to make api useful in both situations, want expose 2 variants of method: 1 dostuff()
throw exception — or, let's say, use given language's capabilities report error loudly possible signify logic error. , other, trydostuff()
, not error reporting @ all, , fail silently.
so, have 2 questions:
does sound idea create 2 api endpoints instead of one? see convenience, although in general, more api endpoints mean more code support , more complicated api.
what appropriate naming convention use?
trydostuff()
work?
(this language has nothing language in particular. use c# syntax examples, question not c# , not oop, please don't add these tags).
this can solved in numerous ways:
- return result of operation, throw upon failure.
- return result of operation or default value upon failure.
- return result of operation or error indicator upon failure.
- return complex result object 1 of states can express failure.
now, these designs not mutually exclusive; parse
/tryparse
methods come in pairs in .net, might want offer "safeguarded" , loudly failing variant of each method. more precisely, following 3 ways of handling seem viable:
- provide 2 variants of each method, described above.
- provide several api objects methods can accessed, "safeguarded" 1 , loudly failing one.
- provide global api mode setting controls general behaviour of methods.
now, options 2 , 3 not mean full double amount of code maintain. externally, able have api objects implement same common interface. , internally, both options 2 , 3 (and actually, option 1) allow write crucial internal methods once , treat problems differently, depending on public method called, or on current api mode.
which design (or combination of designs) choose depends largely on various contextual factors:
- what users of api used to; conventions in target environment?
- what metaphor should api convey? instance, should using api "feel" using "device", or calling functions on lightweight service module?
Comments
Post a Comment