For a function with an intuitive first argument (e.g. a find semantic) I'd like to provide a way to write a function call without argument names while more complicated cases should better be done using named arguments
/// simple intuitive approach
const result1 = object.find("hello");
/// bad: nobody knows what true stands for
const result1 = object.find("hello", true, true);
/// verbose but readable approach
const result2 = object.find({
expression: "hello",
case_sensitive: true,
whole_word: true});
in Python the function signature would look like this:
def find(self, expression, *, case_sensitive=False, whole_word=False):
return do_actual_search(expression, case_sensitive, whole_word);
I found some examples written in the following way:
find(args) {
const [expression, case_sensitive, whole_word] = ((typeof args=== "object")
? [args["expression"],
args["case_sensitive"] || false,
args["whole_word"] || false]
: [args, false, false]);
return do_actual_search(expression, case_sensitive, whole_word);
}
Here you can write both - arguments with and without names (while in this case you would be forced to use 'named arguments' if you provide more than the expression)
In the provided example has only one 'intuitive' argument, so you probably could rename args to expression and it could still be considered OK to provide an associative array instead of just the expression:
find(expression) {
const [exp, case_sensitive, whole_word] = ((typeof expression=== "object")
? [expression["expression"],
expression["case_sensitive"] || false,
expression["whole_word"] || false]
: [expression, false, false]);
return do_actual_search(exp, case_sensitive, whole_word);
}
Either way is hard to write documentation for since the first argument can be both - the whole set of arguments or just one specific argument.
It gets more complicated when you have more than one 'intuitive' arguments:
people.find('Mickey', 'Mouse');
or
people.find({
firstName: 'Mickey',
lastName: 'Mouse',
fictive: true,
born: "1928.11.18"
});
Are there any typical approaches for this when you try to provide a comfortable API or do I have to stick to just one of both approaches?
:instead of=in object literals.find('hello'),findWholeWord('hello', CASE_SENSITIVE)and such.