PS learn PHP is just starting
My answer is not about how to write the code in three lines.
1 Function Name
Usually the verb is put at the beginning of the name: get, set, update, check, validate, etc. The name of the function / method should reflect what she / he is doing. Thus check_game_parameters
: checking game parameters.
2 Purpose of the function
Such an abundance of exit
in one function and without displaying error messages is not serious. Another couple of such functions and then tortured to run around the application with var_dump
.
If this is a validation / validation function, then it should at least return true
or false
. Thus: if the passed game parameters satisfy some predetermined conditions, then return true
. In all other cases, false
.
3 Function Arguments
At the input we have three arguments, each of which passes through two or three checks. Total for the current moment - 7 checks .
Almost always problems arise because of too long methods, often containing a lot of information, buried under complex logic, which they usually contain in themselves. The main type of refactoring here is the “Method Allocation”, as a result of which the code fragment becomes a separate method. - Martin Fowler .
In our case, not a method, but a function. Three arguments are three separate functions, from which we need either true
or false
.
4 Naming Arguments
$gameMode
- we check the parameters of the game, therefore the prefix game
superfluous.$level
fine.$betValue
- out of context, and so it is clear that this value.
echo '<pre>'; function check_game_parameters($mode, $level, int $bet) { return validate_mode($mode) && validate_level($level) && validate_bet($bet); } function validate_mode($mode) { return in_array($mode, [ 'real', 'demo' ]); } function validate_level($level) { return in_array($level, [ 'easy', 'medium', 'hard' ]); } function validate_bet(int $bet) { return $bet >= 15 && $bet <= 500; } if (!check_game_parameters('real', 'hard', 15)) { echo 'Проверка не пройдена<br>'; exit(); } echo 'Проверка пройдена<br>';
lowerCamelCase
, just like your variables. And so, there is nothing particularly to optimize on the code, except to throw everything into one condition - it’s worth duplicatingexit();
? - InDevX$levels = ['easy','medium','hard']; if ( !in_array($level,$levels) ) {...}
$levels = ['easy','medium','hard']; if ( !in_array($level,$levels) ) {...}
again, it is very difficult to influence the performance of your example - InDevX