Junior — Middle
Can you explain the main ideas of the PECS principles in software development?
sobes.tech AI
Answer from AI
The PECS principle (Producer Extends, Consumer Super) helps to correctly use generics in Java, especially when working with collections. It states:
- Producer Extends: If an object acts as a data source (producer), use
? extends T. This allows reading data of type T or its subtypes. - Consumer Super: If an object acts as a data consumer, use
? super T. This allows writing data of type T or its subtypes.
For example, if you have a method that reads elements from a list, the parameter will be List<? extends Number>, and if the method writes elements, then List<? super Integer>.
Example:
void processProducer(List<? extends Number> list) {
Number num = list.get(0); // can read
// list.add(10); // error, cannot add
}
void processConsumer(List<? super Integer> list) {
list.add(10); // can add
// Integer num = list.get(0); // error, cannot guarantee type when reading
}
This helps to avoid type errors and makes the code more flexible and safe.