mercredi 5 octobre 2016

Is there any way or pattern to avoid this kind of java code duplication

Hi i want to know if there are some pattern to avoid code repetition and ifs in cases like this for Java.

   public void updateSequence( DN dn, long seq, long countDescriptorId, int mode ) {
Collection<ResyncNECountSequenceDescriptor> sequencesCollection = sequences.get( dn );
ResyncNECountSequenceDescriptor neDescSeq = new ResyncNECountSequenceDescriptor( countDescriptorId, seq );
if ( sequencesCollection != null && sequencesCollection.size() > 0 ) {
    boolean foundSeq = false;
    for ( ResyncNECountSequenceDescriptor sequence : sequencesCollection ) {
    if ( sequence.getCountDescriptorId() == countDescriptorId ) {
        if ( mode == LAST_CREATED_DATFILE_SEQUENCE ) {
        sequence.setLastCreatedDatfileSequence( seq );
        } else {
        if ( seq > sequence.getLastCreatedDatfileSequence() ) {
            seq = 0;
        }
        sequence.setNextDatfileToProcessSequence( seq );
        }
        foundSeq = true;
    }
    }
    if ( !foundSeq ) {
    sequencesCollection.add( neDescSeq );
    }
} else {
    Collection<ResyncNECountSequenceDescriptor> col = new ArrayList<ResyncNECountSequenceDescriptor>();
    col.add( neDescSeq );
    sequences.putIfAbsent( dn, col );
}
}

In this method for example, I want to get rid of the mode parameter and do two methods instead. The thing is only thing that changes is the inner if condition and logic, but all the rest is identical. How to avoid or minimize code duplication in this case ?

Aucun commentaire:

Enregistrer un commentaire