There is a php code:

public static function load() : void { $config = new ...; $config = $config->getData(); $throw = function() : void { throw new \ConfigException ("Invalid config."); }; self::$param1 = $config["core"]["param1"] ?? ($throw)(); self::$param2 = $config["core"]["param2"] ?? ($throw)(); self::$param3 = $config["module"]["param3"] ?? ($throw)(); self::$param4 = $config["module"]["param4"] ?? ($throw)(); } public static function getParam1() : bool { return self::$param1; } public static function getParam2() : string { return self::$param2; } public static function getParam3() : int {...} /*и т.д.*/ 

It checks the values ​​in the array, and if they are not there, it throws an exception ($throw)() , if there is, then this value is assigned to the static property of the class.

In my opinion, now checking the value and throwing an exception looks awful. How can this be done better?

  • Well, make some type of config via [ 'param1' => "core.param1", ... ] - teran
  • one
    What is the meaning of this static class? You already have a config class with the getData method ... - vp_arth
  • @vp_arth is apparently engaged in reading exclusively. In general, the dumbest thing here is that the param1 parameter names, etc. - teran
  • The names of the parameters, I hope, are just an example. I'm confused by type-hinting in getters and the lack of type checking during parsing) - vp_arth
  • code inspection - aleksandr barakin

1 answer 1

They say that the best code is not the one to which there is nothing to add, but the one from which there is nothing to remove. If you want to validate the structure of the config array, making sure that it contains the necessary keys - do just that. If you want to validate the values ​​of the parameters you are going to work with - do just that. In the end, no matter how you throw an exception, it is important why and why you throw it.

Make the error message more informative (which key is missing, in which config file). Make sure your checks are really necessary in this suspicious class. Get rid of unnecessary dependencies. Make sure that the suspicious class itself is needed.

  • Starting with the last sentence, you can save a lot of time) - vp_arth