Question

I am writing API client and I want to define default value for one parameter via constant. Now I have it like this:

/**
 * Available: val_1|val_3|val_3|val_4|val_5
 * 
 * @var string
 */
const MY_DEFAULT_VALUE = 'val_1';

But I am not sure if this usage of "enum" is correct. I found how to do it with method parameters, but this is not the same problem. Definition of my method is:

public function callApi($someParam, $anotherParam = self::MY_DEFAULT_VALUE)

Is there any standard about this? Thanks a lot.

EDIT: I will stop using abstract values and parameters and I'll try to explain it on specific example which I am solving... I am calling API with method setLanguage() which has optional parameter $lang. Snippet of my code:

const DEFAULT_LANGUAGE = 'ENG';
// ...
public function setLanguage($lang = self::DEFAULT_LANGUAGE)

But API, which I am calling, accept only some languages. Basicaly, what I want to tell to other programmers in comment is: "Ok, so you want to change default language, but note that only these values are valid.". This is nothing critical and I think my currect solution is clear enough too:

/**
 * Available: ENG|ITA|FRA|DEU|ESP
 * 
 * @var string
 */
const DEFAULT_LANGUAGE = 'ENG';

I was just wondering, if there is some "good practice" about this.

Was it helpful?

Solution

Any time I need a specified enumeration of possible values, I'll always use individual constants to explicitly define all of them, e.g. const VALUE_1 = 'val_1';, const VALUE_2 = 'val_2';.

As for identifying what a default value should be, I agree with your approach of just having that second argument in callApi() to set what the default would be (callApi()), but to do so by using one of the actual constants rather than having another "default" constant that just points to one of the value constants. That way, you can set the main default in your base class, and if child classes want to choose their own defaults, they simply override the method.

Also, this allows you to specifically mention those various argument options in the @param tag in the docblock for callApi().

Lastly, I'd suggest setting the constant values to simply be integers rather than strings. That way, since the values themselves will not be particularly informative, callers will be more likely to use the constant names when they do callApi(), thus making their own code more readable and less likely to pass unexpected values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top