Course contentsShow
← Java
Lesson 948 of 2,87022. Generics: Bounds and WildcardsFree lesson

Practice: Refactoring Code to Apply PECS

Identifying opportunities to make existing generic methods more flexible using PECS principles.

Practice: Refactoring Code to Apply PECS

What you'll learn: How to spot and fix methods that could be more flexible by applying the Producer Extends, Consumer Super principle.

Recognizing Refactoring Opportunities

Now that you understand PECS, it's time to practice identifying where it applies. Look for methods with generic collection parameters — these are prime candidates. Ask yourself: Is this parameter producing values I read, consuming values I write, or both?

The Refactoring Process

Step 1: Identify the role

  • Does your method read from the collection? It's a producer → use <? extends T>
  • Does your method write to the collection? It's a consumer → use <? super T>
  • Does it both read and write? Leave it as <T> (no wildcard)

Step 2: Apply the wildcard

Before refactoring:

public void addAll(List<Number> dest, List<Number> src)

After applying PECS:

public void addAll(List<? super Number> dest, List<? extends Number> src)

Why? The src list produces numbers we read, and the dest list consumes numbers we write.

The Flexibility Gain

The refactored version now accepts:

  • addAll(List<Object>, List<Integer>) ✅
  • addAll(List<Number>, List<Double>) ✅
  • addAll(List<Serializable>, List<Long>) ✅

The original only accepted List<Number> for both — far too restrictive!

Common Pattern to Spot

Look for methods that transfer, copy, or combine elements between collections. These almost always benefit from PECS because one collection produces and the other consumes.

Key Takeaway: Refactoring existing generics code with PECS makes your APIs dramatically more flexible — use extends for parameters you read from (producers) and super for parameters you write to (consumers).