MixedRealityToolkit-Unity icon indicating copy to clipboard operation
MixedRealityToolkit-Unity copied to clipboard

Public vs explicit implementation in handler methods

Open aalmada opened this issue 9 years ago • 6 comments

IMO, 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.

aalmada avatar Dec 30 '16 12:12 aalmada

Personally I agree with this. I believe you updated this in some PR?

NeerajW avatar Jan 05 '17 18:01 NeerajW

We should continue to investigate this.

david-c-kline avatar Mar 23 '18 20:03 david-c-kline

+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.

luis-valverde-ms avatar Apr 03 '19 15:04 luis-valverde-ms

#4766

Yoyozilla avatar Jun 07 '19 05:06 Yoyozilla

@keveleigh did you want to investigate this for GA or just keep it open for tracking for future?

Yoyozilla avatar Jun 10 '19 06:06 Yoyozilla

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.

Zee2 avatar Aug 04 '21 17:08 Zee2