When should you prefer PECS principle and when should you avoid it?

The PECS (Producer Extends, Consumer Super) principle is a key concept in Java generics. It helps to decide when to use wildcards with generics in a way that ensures code is both flexible and type-safe. Here's when to prefer and avoid using PECS:

When to Prefer PECS

  • Producer Scenario: When you have a method that produces values, use the "?> wildcard. For example, if you have a method that returns a list of fruits, and you want it to be able to return a specific type of fruit or a superclass.
  • Consumer Scenario: When your method consumes values, use the "?> wildcard. This is useful when you want to add items to a collection.

When to Avoid PECS

  • Complex Structures: If your use case is complex and involves multiple levels of inheritance, using PECS might complicate your code rather than simplify it.
  • Clarity: If applying PECS makes your code less readable or harder to understand, it's better to stick with explicit types and collections.

Example


    import java.util.ArrayList;
    import java.util.List;

    // Producer Extends Example
    public class FruitBasket {
        private List fruits = new ArrayList<>();

        public void addFruit(T fruit) {
            fruits.add(fruit);
        }

        public List getFruits() {
            return fruits;
        }
    }

    // Consumer Super Example
    public void addAllFruits(List super Apple> list) {
        list.add(new Apple());
    }
    

PECS Java Generics Producer Extends Consumer Super Generics Best Practices