Why/How to use passed constants in function?

社会主义新天地 提交于 2019-12-12 00:18:56

问题


I've seen classes where constants are passed to methods, I guess its done to define some kind of setting in that function. I cant find it anywhere now to try to find out the logic, so I though I could ask here. How and why do you use this concept and where can I find more information about it?

The example below is written in PHP, but any language that handles constants would do I guess..

// Declaring class
class ExampleClass{
  const EXAMPLE_CONST_1 = 0;
  const EXAMPLE_CONST_2 = 1;  

  function example_method($constant(?)){

     if($constant == ExampleClass::EXAMPLE_CONST_1)
       // do this
     else if($constant == ExampleClass::EXAMPLE_CONST_2)
       // do that

  }
}

// Using class
$inst = new ExampleClass();
$inst->example_method(ExampleClass::EXAMPLE_CONST_1);

To me its more clear to pass "ExampleClass::EXAMPLE_CONST_1" than to just pass "1", but it's that the only reason to pass constant?


回答1:


Simply passing 1 doesn't say much. By having a constant you can have a description about the settings in the name.

example: constant RAIN = 1;

method setWeather(RAIN);

Atleast that's how and why I use it.




回答2:


It is always a good idea to avoid literals being passed around. By assigning a name, anyone reading your code has a chance to understand what that value means - a number has no meaning. It might also help you maintaining your code: If for some requirement the value has to be changed, you can easily do it in one place, instead of checking each and every value occurrence.



来源:https://stackoverflow.com/questions/12384592/why-how-to-use-passed-constants-in-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!