Impure Method in Java
☰Fullscreen
Table of Content:
Impure Method
An impure method is one that does not adhere to the principles of purity. It might:
-
Have Side Effects: It can modify external state or variables, such as changing class-level variables, performing I/O operations, or modifying static variables.
-
Non-Deterministic: The method's output can vary even with the same input values, depending on external factors or states.
-
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 theCounter
object. - Non-Deterministic: The output of
getCount
depends on the history of calls toincrement
. - Dependence on External State: The behavior relies on the internal state of the object.