2 years ago

#5402

test-img

Aguid

How to refactor to reduce the duplicated code?

I have the main abstract class GLSubBuffer to model a subpart of a buffer :

@Getter(value = AccessLevel.PROTECTED)
public abstract class GLSubBuffer<T extends Buffer> {

  private final T buffer;
  private final int position;
  private final int capacity;

  public GLSubBuffer(T buffer, int position, int capacity) {
    this.buffer = buffer;
    this.position = position;
    this.capacity = capacity;
  }

}

Here the class for a subpart of FloatBuffer

public class GLSubFloatBuffer extends GLSubBuffer<FloatBuffer> {

  public GLSubFloatBuffer(FloatBuffer buffer, int position, int capacity) {
    super(buffer, position, capacity);
  }

  public void update(float[] values) {

    int min = Math.min(values.length, getCapacity());
    for (int i = 0; i < min; i++) {
      getBuffer().put(i + getPosition(), values[i]);
    }
  }
}

And the class for a subpart of IntBuffer

public class GLSubIntBuffer extends GLSubBuffer<IntBuffer> {

  public GLSubFloatBuffer(IntBuffer buffer, int position, int capacity) {
    super(buffer, position, capacity);
  }

  public void update(int[] values) {

    int min = Math.min(values.length, getCapacity());
    for (int i = 0; i < min; i++) {
      getBuffer().put(i + getPosition(), values[i]);
    }
  }
}

How to refactor the method update() to be able to move it to the main class and remove the two child classes ?

java

generics

primitive

0 Answers

Your Answer

Accepted video resources