mavlink / MAVSDK-Java

MAVSDK client for Java.
68 stars 40 forks source link

Implemented translate to rpc method in enums with constant-specific method implementations #74

Closed divyanshupundir closed 2 years ago

divyanshupundir commented 2 years ago

The translate to rpc methods in enums used to switch on their own values, which is fragile implementation. (Refer: Effective Java Vol 2: Item 30: Enum type that switches on its own value - questionable)

Therefore the enum template has been edited to generate methods that use constant-specific method implementation. (Refer: Effective Java Vol 2: Item 30: Enum type with constant-specific method implementations)

For example, this generates enums that are as follows:

public enum VideoStreamStatus {

  NOT_RUNNING {
    @Override
    protected CameraProto.VideoStreamInfo.VideoStreamStatus rpcVideoStreamStatus() {
       return CameraProto.VideoStreamInfo.VideoStreamStatus.VIDEO_STREAM_STATUS_NOT_RUNNING;
    }
  }, 
  IN_PROGRESS {
    @Override
    protected CameraProto.VideoStreamInfo.VideoStreamStatus rpcVideoStreamStatus() {
      return CameraProto.VideoStreamInfo.VideoStreamStatus.VIDEO_STREAM_STATUS_IN_PROGRESS;
    }
  };

  protected static VideoStreamStatus translateFromRpc(CameraProto.VideoStreamInfo.VideoStreamStatus rpcVideoStreamStatus) {
    switch (rpcVideoStreamStatus) {
      case VIDEO_STREAM_STATUS_NOT_RUNNING:
      default: 
        return VideoStreamStatus.NOT_RUNNING;
      case VIDEO_STREAM_STATUS_IN_PROGRESS:

        return VideoStreamStatus.IN_PROGRESS;}
  }

  protected abstract CameraProto.VideoStreamInfo.VideoStreamStatus rpcVideoStreamStatus();
}

The behaviour at the call site will be exactly the same as before. But there are certain benefits to it:

  1. The enums hold a strong reference to their own translation functions, therefore the checks due to branching (switch) are not required.
  2. The redundant default branch is not present.
  3. Since default is removed, any mismatch will be caught at compile-time and those bugs won't propagate to run-time.