vendredi 4 septembre 2015

How to avoid null checking wrapped objects for each of the methods implemented on a Wrapper Class

So I have 2 classes for the moment(there might be more in the future) that are similar they both represent data from a Track

private Track track;
private TrackSearchResult trackSearchResult;

These classes are auto-generated from Json Schema. They have no relation , but they contain similar methods.

So I have created a wrapper class to encapsulate both of them so I just have 1 class that I use for everything (Like playing a track).

public class ExoPlayerTrack implements IPlayerTrack {


private Track track;
private TrackSearchResult trackSearchResult;


public ExoPlayerTrack(Track track) {
    this.track = track;
}

public ExoPlayerTrack(TrackSearchResult trackSearchResult) {
    this.trackSearchResult = trackSearchResult;
}



@Override
public String getTrackName() {
    if (track != null) {
        return track.getName();
    } else if (trackSearchResult != null) {
        return trackSearchResult.getTrackName();
    } else {
        return null;
    }
}

I have defined an interface IPlayerTrack that has the common methods between the 2 similar Track Classes.

public interface IPlayerTrack {
    public String getTrackName();
    public String getReleaseName();
    public String getArtistName();
    public String getTrackId();
    public String getReleaseId();
    public String getArtistId();
    public String getImageUrl();
    public long getDuration();
    }

So I need to implement every method of the interface by checking first for null to see which from the two Track classes was used to initialise the Wrapper Class which is very nasty.
Is there any way this can be avoided without touching the auto-generated model classes??? Maybe using Java 8 or Guava or a design pattern?

@Override
    public String getReleaseName() {
        if (track != null) {   //AVOID
            return track.getReleaseName();
        } else if (trackSearchResult != null) {
            return trackSearchResult.getReleaseName();
        } else {
            return null;
        }
    }

 @Override
public String getTrackName() {
    if (track != null) {
        return track.getName();
    } else if (trackSearchResult != null) {
        return trackSearchResult.getTrackName();
    } else {
        return null;
    }
}

Note that also the method names are slightly different in some cases (getName/getTrackName).

Aucun commentaire:

Enregistrer un commentaire