Table of Contents

    Impure Method in Java

    Impure Method

    An impure method is one that does not adhere to the principles of purity. It might:

    1. Have Side Effects: It can modify external state or variables, such as changing class-level variables, performing I/O operations, or modifying static variables.

    2. Non-Deterministic: The method's output can vary even with the same input values, depending on external factors or states.

    3. Depend on External State: It may rely on or interact with external variables, class-level state, or other methods.

    Example:

    
    public class Counter {
        private int count = 0;
    
        public void increment() {
            count++; // Modifies the state of the object
        }
    
        public int getCount() {
            return count; // Depends on the internal state
        }
    }
    
    
    • Side Effects: The increment method modifies the internal state of the Counter object.
    • Non-Deterministic: The output of getCount depends on the history of calls to increment.
    • Dependence on External State: The behavior relies on the internal state of the object.