ABSTRACT
A standard practice in object-oriented programming is to implement an operation, called equals in Java, for testing the equality of two objects. The equals method should be defined for every new Java class, but because of the intricacies of inheritance, casting, and dynamic typing, equals is often quite difficult to write correctly. And unfortunately many textbooks present flawed implementations of this operation. In this paper, we present a semantically correct technique for testing object equivalence, a technique that simultaneously brings together important mathematical foundations (equivalence relations), practical programming issues (inheritance, casting, dynamic typing), and sound software design (design patterns) in a natural and compelling way. While Java is used to demonstrate how the semantic flaws are corrected and the design improved using our techniques, the design is general enough that it will be clear how the same ideas could easily be extended to other languages such as C++.
- Bergin, J. Canonical Form of a Java Class. http://csis.pace.edu/~bergin/patterns/CanonicalJava.html.Google Scholar
- Bloch, J. Effective Java Programming Language Guide. Addison-Wesley (2001). Google ScholarDigital Library
- Cohen, T. How Do I Correctly Implement the equals() Method? Dr. Dobb's Journal, May (2002).Google Scholar
- Gamma, E., Helm, R., Johnson, R., and Vlissides, J. Design Patterns: Elements of Reuseable Object-Oriented Software. Addison-Wesley Publishing (1995). Google ScholarDigital Library
- Horstmann, C., and Cornell, G. Core Java 2: Volume I - Fundamentals. Sun Microsystems Press (2001). Google ScholarDigital Library
- Stevenson, D.E., and Phillips, A.T. A Template Design for Correctly Overriding the Operator== in C++. UW-Eau Claire Computer Science Technical Report, August (2002).Google Scholar
Index Terms
- Implementing object equivalence in Java using the template method design pattern
Recommendations
Implementing object equivalence in Java using the template method design pattern
A standard practice in object-oriented programming is to implement an operation, called equals in Java, for testing the equality of two objects. The equals method should be defined for every new Java class, but because of the intricacies of inheritance, ...
Design Pattern for Reusing Immutable Methods in Object-Oriented Languages
EuroPLoP '23: Proceedings of the 28th European Conference on Pattern Languages of ProgramsContext. Features and styles inspired by functional programming have grown in popularity in the world of object-oriented programming. Immutability is a core concept of functional programming, which brings advantages to software development. However, ...
Comments