WordPress filters are a useful (though frequently underutilized) feature. They allow code outside of your plugin or theme to change data in a structured way, but they can also be used to get data from a plugin in a safer way than using a constant or a function.
If your plugin exposes a value through a constant or a function then it’s easy for another plugin or theme to use the value.
SomeClass::CONSTANT_VALUE;
// or
SomeClass::getConstantValue();
But what about if your plugin gets deactivated? Now any calls to the constant or function will throw an error and likely cause the site to break.
Sure, the calls can be wrapped in a check but that adds a bunch of noise and often adds an extra level of indentation which makes the code more complex and harder to read.
If you expose your value via a filter however, if your plugin is deactivated then the plugin or theme that uses the value simply gets the default value:
$value = apply_filters('some_class/constant_value', null);
You can support this in your plugin with a small snippet like this:
add_filter('some_class/constant_value', function($_) { return 1; });
We use the $_
variable as a hint that the argument isn’t used and the return value is hard-coded for simplicity.