Public vs explicit implementation in handler methods
See original GitHub issueIMO, handler methods should be private or protected but never public. These are not supposed to be called explicitly by the user.
Handlers have to implement interfaces (for example IInputClickHandler) which forces the methods to be public:
public class MyHandler: MonoBehaviour, IInputClickHandler
{
public void OnInputClicked(InputEventData eventData)
{
...
}
}
Or implemented explicitly:
public class MyHandler: MonoBehaviour, IInputClickHandler
{
void IInputClickHandler.OnInputClicked(InputEventData eventData)
{
...
}
}
When implemented explicitly, the method is still public but a bit hidden. They are only available for references of that interface type but, in that case, you explicitly want to call those methods anyway.
Unity does an awkward thing with its methods (Awake, Start, OnDestroy and so on) that calls them although they can be private and without them being defined in MonoBehaviour or any other interface (against all strongly-typed compiler rules) but to achieve more performance. Unless it does the same optimizations for the public interface methods, I would favor the use of explicit interface implementation.
The use of explicit implementation also makes it easier, when reading the code, to understand what interface is being implemented.
Issue Analytics
- State:
- Created 7 years ago
- Reactions:3
- Comments:6 (4 by maintainers)
Top GitHub Comments
+1 to the idea of implementing interfaces explicitly. Besides the advantages already mentioned, implementing an interface explicitly means that removing something (e.g.: method or property) from the interface automatically triggers a build error in implementations instead of silently leaving them with stale code.
Moving forward we will be trying to de-emphasize handler methods; for any we will still need, we will make sure that they are extensible + overridable in the relevant scenarios, in addition to following the current Unity patterns.