MET08-J. Preserve the equality contract when overriding the equals() method

Similar documents
The class Object. Lecture CS1122 Summer 2008

Programming Languages and Techniques (CIS120)

Methods Common to all Classes

Software Engineering Design & Construction

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000

Equality. Michael Ernst. CSE 331 University of Washington

MSC07-J. Prevent multiple instantiations of singleton objects

Equality. Michael Ernst. CSE 331 University of Washington

equals() in the class Object

Super-Classes and sub-classes

java.lang.object: Equality

Chapter 11: Collections and Maps

Creating an Immutable Class. Based on slides by Prof. Burton Ma

Programming Languages and Techniques (CIS120)

For this section, we will implement a class with only non-static features, that represents a rectangle

Expected properties of equality

CSE 331 Software Design & Implementation

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

CSE 331 Software Design & Implementation

C12a: The Object Superclass and Selected Methods

Collections. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

COMP 250. Lecture 30. inheritance. overriding vs overloading. Nov. 17, 2017

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

The Liskov Substitution Principle

Uguaglianza e Identità. (no, non avete sbagliato corso )

Object-Oriented Programming in the Java language

Principles of Software Construction: Objects, Design and Concurrency. Polymorphism, part 2. toad Fall 2012

Programming Languages and Techniques (CIS120e)

Introduction to Object-Oriented Programming

Effective Java. Object Equality. - Case Studies - Angelika Langer. Trainer/Consultant.

Programming Languages and Techniques (CIS120)

Java Fundamentals (II)

Software Engineering Design & Construction Dr. Michael Eichberg Fachgebiet Softwaretechnik Technische Universität Darmstadt

Principles of Software Construction: Objects, Design and Concurrency. Inheritance, type-checking, and method dispatch. toad

Canonical Form. No argument constructor Object Equality String representation Cloning Serialization Hashing. Software Engineering

Announcements. Equality. Lecture 10 Equality and Hashcode. Announcements. CSE 331 Software Design and Implementation. Leah Perlmutter / Summer 2018

Elementary Symbol Tables

Programming Languages and Techniques (CIS120)


Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

Abstract Classes and Interfaces

Programming Languages and Techniques (CIS120)

Rules and syntax for inheritance. The boring stuff

Defective Java Code: Turning WTF code into a learning experience

COMP 250 Fall inheritance Nov. 17, 2017

Inheritance (Part 5) Odds and ends

Today. Book-keeping. Inheritance. Subscribe to sipb-iap-java-students. Slides and code at Interfaces.

Software Engineering Design & Construction Dr. Michael Eichberg Fachgebiet Softwaretechnik Technische Universität Darmstadt

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

ELEMENTARY SEARCH ALGORITHMS

1 Shyam sir JAVA Notes

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

MIT EECS Michael Ernst Saman Amarasinghe

Big software. code reuse: The practice of writing program code once and using it in many contexts.

Programming Languages and Techniques (CIS120)

Defective Java Code: Turning WTF code into a learning experience

Polymorphism. return a.doublevalue() + b.doublevalue();

More about inheritance

Software Development (cs2500)

INSTRUCTIONS TO CANDIDATES

Overloaded Methods. Sending Messages. Overloaded Constructors. Sending Parameters

CLASS DESIGN. Objectives MODULE 4

Advanced Topics on Classes and Objects

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Practice for Chapter 11

cs2010: algorithms and data structures

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

Implementing Object Equivalence in Java Using the Template Method Design Pattern

CMSC 132: Object-Oriented Programming II

Chapter 5 Object-Oriented Programming

CIS 110: Introduction to computer programming

Programming Languages and Techniques (CIS120)

Conversions and Casting

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Charlie Garrod Michael Hilton

CMSC 132: Object-Oriented Programming II. Effective Java. Department of Computer Science University of Maryland, College Park

COP 3330 Final Exam Review

CSE1720. General Info Continuation of Chapter 9 Read Chapter 10 for next week. Second level Third level Fourth level Fifth level

Principles of Software Construction: Objects, Design, and Concurrency. Testing and Object Methods in Java. Josh Bloch Charlie Garrod Darya Melicher

JAVA MOCK TEST JAVA MOCK TEST III


Introduction to Java.net Package. CGS 3416 Java for Non Majors

Project 6 Due 11:59:59pm Thu, Dec 10, 2015

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

Java: advanced object-oriented features

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

Inheritance -- Introduction

Object typing and subtypes

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Declarations and Access Control SCJP tips

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Chair of Software Engineering. Languages in Depth Series: Java Programming. Prof. Dr. Bertrand Meyer. Exercise Session 10

Introduction to Programming Using Java (98-388)

Equality in.net. Gregory Adam 07/12/2008. This article describes how equality works in.net

Object-Oriented Concepts

Transcription:

MET08-J. Preserve the equality contract when overriding the equals() method Composition or inheritance may be used to create a new class that both encapsulates an existing class and adds one or more fields. When one class extends another in this way, the concept of equality for the subclass may or may not involve its new fields. That is, when comparing two subclass objects for equality, sometimes their respective fields must also be equal, and other times they need not be equal. Depending on the concept of equality for the subclass, the subclass might override equals(). Furthermore, this method must follow the general contract for equal s(), as specified by The Java Language Specification (JLS) [ JLS 2015]. An object is characterized both by its identity (location in memory) and by its state (actual data). The == operator compares only the identities of two objects (to check whether the references refer to the same object); the equals() method defined in java.lang.object can be overridden to compare the state as well. When a class defines an equals() method, it implies that the method compares state. When the class lacks a customized equals() method (either locally declared or inherited from a parent class), it uses the default Object.equals() implementation inherited from Object. The default Object.equals() implementation compares only the references and may produce unexpected results. The equals() method applies only to objects, not to primitives. Enumerated types have a fixed set of distinct values that may be compared using == rather than the equals() method. Note that enumerated types provide an equals() implementation that uses == internally; this default cannot be overridden. More generally, subclasses that both inherit an implementation of equals() from a superclass and lack a requirement for additional functionality need not override the equals() method. The general usage contract for equals(), as specified by the JLS, establishes five requirements: 1. It is reflexive: For any reference value x, x.equals(x) must return true. 2. It is symmetric: For any reference values x and y, x.equals(y) must return true if and only if y.equals(x) returns true. 3. It is transitive: For any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) m ust return true. 4. It is consistent: For any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals() comparisons on the object is modified. 5. For any non-null reference value x, x.equals(null) must return false. Never violate any of these requirements when overriding the equals() method. Noncompliant Code Example (Symmetry) This noncompliant code example defines a CaseInsensitiveString class that includes a String and overrides the equals() method. The CaseInsensitiveString class knows about ordinary strings, but the String class has no knowledge of case-insensitive strings. Consequently, the CaseInsensitiveString.equals() method should not attempt to interoperate with objects of the String class.

public final class CaseInsensitiveString { private String s; public CaseInsensitiveString(String s) { if (s == null) { throw new NullPointerException(); this.s = s; // This method violates symmetry if (o instanceof CaseInsensitiveString) { return s.equalsignorecase(((caseinsensitivestring)o).s); if (o instanceof String) { return s.equalsignorecase((string)o); // Comply with MET09-J public int hashcode() {/*... */ public static void main(string[] args) { CaseInsensitiveString cis = new CaseInsensitiveString("Java"); String s = "java"; System.out.println(cis.equals(s)); // Returns true System.out.println(s.equals(cis)); // Returns false By operating on String objects, the CaseInsensitiveString.equals() method violates the second contract requirement (symmetry). Because of the asymmetry, given a String object s and a CaseInsensitiveString object cis that differ only in case, cis.equals(s)) ret urns true, while s.equals(cis) returns false. Compliant Solution In this compliant solution, the CaseInsensitiveString.equals() method is simplified to operate only on instances of the CaseInsensitiv estring class, consequently preserving symmetry:

public final class CaseInsensitiveString { private String s; public CaseInsensitiveString(String s) { if (s == null) { throw new NullPointerException(); this.s = s; return o instanceof CaseInsensitiveString && ((CaseInsensitiveString)o).s.equalsIgnoreCase(s); public int hashcode() {/*... */ public static void main(string[] args) { CaseInsensitiveString cis = new CaseInsensitiveString("Java"); String s = "java"; System.out.println(cis.equals(s)); // Returns false now System.out.println(s.equals(cis)); // Returns false now Noncompliant Code Example (Transitivity) This noncompliant code example defines an XCard class that extends the Card class. public class Card { private final int number; public Card(int number) { this.number = number; if (!(o instanceof Card)) { Card c = (Card)o; return c.number == number; public int hashcode() {/*... */

class XCard extends Card { private String type; public XCard(int number, String type) { super(number); this.type = type; if (!(o instanceof Card)) { // Normal Card, do not compare type if (!(o instanceof XCard)) { return o.equals(this); // It is an XCard, compare type as well XCard xc = (XCard)o; return super.equals(o) && xc.type == type; public int hashcode() {/*... */ public static void main(string[] args) { XCard p1 = new XCard(1, "type1"); Card p2 = new Card(1); XCard p3 = new XCard(1, "type2"); System.out.println(p1.equals(p2)); // Returns true System.out.println(p2.equals(p3)); // Returns true System.out.println(p1.equals(p3)); // Returns false // violating transitivity

In the noncompliant code example, p1 and p2 compare equal and p2 and p3 compare equal, but p1 and p3 compare unequal, violating the transitivity requirement. The problem is that the Card class has no knowledge of the XCard class and consequently cannot determine that p2 and p3 have different values for the field type. Compliant Solution (Delegation) Unfortunately, in this case it is impossible to extend the Card class by adding a value or field in the subclass while preserving the equals() cont ract. This problem is not specific to the Card class but applies to any class hierarchy that can consider equal instances of distinct subclasses of some superclass. For such cases, use composition rather than inheritance to achieve the desired effect [ Bloch 2008]. This compliant solution adopts this approach by adding a private card field to the XCard class and providing a public viewcard() method. class XCard { private String type; private Card card; // Composition public XCard(int number, String type) { card = new Card(number); this.type = type; public Card viewcard() { return card; if (!(o instanceof XCard)) { XCard cp = (XCard)o; return cp.card.equals(card) && cp.type.equals(type); public int hashcode() {/*... */ public static void main(string[] args) { XCard p1 = new XCard(1, "type1"); Card p2 = new Card(1); XCard p3 = new XCard(1, "type2"); XCard p4 = new XCard(1, "type1"); System.out.println(p1.equals(p2)); // Prints false System.out.println(p2.equals(p3)); // Prints false System.out.println(p1.equals(p3)); // Prints false System.out.println(p1.equals(p4)); // Prints true

Compliant Solution (Class Comparison) If the Card.equals() method could unilaterally assume that two objects with distinct classes were not equal, it could be used in an inheritance hierarchy while preserving transitivity: public class Card { private final int number; public Card(int number) { this.number = number; if (!(o.getclass() == this.getclass())) { Card c = (Card)o; return c.number == number; public int hashcode() {/*... */ Noncompliant Code Example (Consistency) A uniform resource locator (URL) specifies both the location of a resource and a method to access it. According to the Java API documentation for Class URL [ API 2014]: Two URL objects are equal if they have the same protocol, reference equivalent hosts, have the same port number on the host, and the same file and fragment of the file. Two hosts are considered equivalent if both host names can be resolved into the same IP addresses; else if either host name can't be resolved, the host names must be equal without regard to case; or both host names equal to null. The defined behavior for the equals() method is known to be inconsistent with virtual hosting in HTTP. Virtual hosting allows a web server to host multiple websites on the same computer, sometimes sharing the same IP address. Unfortunately, this technique was unanticipated when the URL class was designed. Consequently, when two completely different URLs resolve to the same IP address, the URL class considers them to be equal. Another risk associated with the equals() method for URL objects is that the logic it uses when connected to the Internet differs from that used when disconnected. When connected to the Internet, the equals() method follows the steps described in the Java API; when disconnected, it performs a string compare on the two URLs. Consequently, the URL.equals() method violates the consistency requirement for equals(). Consider an application that allows an organization's employees to access an external mail service via http://mailwebsite.com. The application is designed to deny access to other websites by behaving as a makeshift firewall. However, a crafty or malicious user could nevertheless access an illegitimate website http://illegitimatewebsite.com if it were hosted on the same computer as the legitimate website and consequently shared the same IP address. Even worse, if the legitimate website were hosted on a server in a commercial pool of servers, an attacker could register multiple websites in the pool (for phishing purposes) until one was registered on the same computer as the legitimate website, consequently defeating the firewall.

public class Filter { public static void main(string[] args) throws MalformedURLException { final URL allowed = new URL("http://mailwebsite.com"); if (!allowed.equals(new URL(args[0]))) { throw new SecurityException("Access Denied"); // Else proceed Compliant Solution (Strings) This compliant solution compares the string representations of two URLs, thereby avoiding the pitfalls of URL.equals() : public class Filter { public static void main(string[] args) throws MalformedURLException { final URL allowed = new URL("http://mailwebsite.com"); if (!allowed.tostring().equals(new URL(args[0]).toString())) { throw new SecurityException("Access Denied"); // Else proceed This solution still has problems. Two URLs with different string representation can still refer to the same resource. However, the solution fails safely in this case because the equals() contract is preserved, and the system will never allow a malicious URL to be accepted by mistake. Compliant Solution ( URI.equals() ) A Uniform Resource Identifier (URI) contains a string of characters used to identify a resource; this is a more general concept than an URL. The j ava.net.uri class provides string-based equals() and hashcode() methods that satisfy the general contracts for Object.equals() and Object.hashCode() ; they do not invoke hostname resolution and are unaffected by network connectivity. URI also provides methods for normalization and canonicalization that URL lacks. Finally, the URL.toURI() and URI.toURL() methods provide easy conversion between the two classes. Programs should use URIs instead of URLs whenever possible. According to the Java API Class URI documentation [ API 2014]: A URI may be either absolute or relative. A URI string is parsed according to the generic syntax without regard to the scheme, if any, that it specifies. No lookup of the host, if any, is performed, and no scheme-dependent stream handler is constructed. This compliant solution uses a URI object instead of a URL. The filter appropriately blocks the website when presented with any string other than http://mailwebsite.com because the comparison fails.

public class Filter { public static void main(string[] args) throws MalformedURLException, URISyntaxException { final URI allowed = new URI("http://mailwebsite.com"); if (!allowed.equals(new URI(args[0]))) { throw new SecurityException("Access Denied"); // Else proceed Additionally, the URI class performs normalization (removing extraneous path segments such as "..") and relativization of paths [ API 2014], [ Dar win 2004]. Noncompliant Code Example ( java.security.key) The method java.lang.object.equals() by default is unable to compare composite objects such as cryptographic keys. Most Key classes lack an equals() implementation that would override Object's default implementation. In such cases, the components of the composite object must be compared individually to ensure correctness. This noncompliant code example compares two keys using the equals() method. The comparison may return false even when the key instances represent the same logical key. private static boolean keysequal(key key1, Key key2) { if (key1.equals(key2)) { return true; Compliant Solution ( java.security.key) This compliant solution uses the equals() method as a first test and then compares the encoded version of the keys to facilitate provider-independent behavior. For example, this code can determine whether a RSAPrivateKey and RSAPrivateCrtKey represent equivalent private keys [ Sun 2006].

private static boolean keysequal(key key1, Key key2) { if (key1.equals(key2)) { return true; if (Arrays.equals(key1.getEncoded(), key2.getencoded())) { return true; // More code for different types of keys here. // For example, the following code can check if // an RSAPrivateKey and an RSAPrivateCrtKey are equal: if ((key1 instanceof RSAPrivateKey) && (key2 instanceof RSAPrivateKey)) { if ((((RSAKey)key1).getModulus().equals( ((RSAKey)key2).getModulus())) && (((RSAPrivateKey) key1).getprivateexponent().equals( ((RSAPrivateKey) key2).getprivateexponent()))) { return true; Exceptions MET08-J-EX0: Requirements of this rule may be violated provided that the incompatible types are never compared. There are classes in the Java platform libraries (and elsewhere) that extend an instantiable class by adding a value component. For example, java.sql.timestamp extends java.util.date and adds a nanoseconds field. The equals() implementation for Timestamp violates symmetry and can cause erratic behavior when Timestamp and Date objects are used in the same collection or are otherwise intermixed [ Bloch 2008]. Risk Assessment Violating the general contract when overriding the equals() method can lead to unexpected results. Rule Severity Likelihood Remediation Cost Priority Level MET08-J Low Unlikely Medium P2 L3 Automated Detection Tool Version Checker Description CodeSonar 4.5p1 FB.BAD_PRACTICE.EQ_GETCLASS_AND_CLASS_CONSTANT FB.CORRECTNESS.OVERRIDING_EQUALS_NOT_SYMMETRIC equals method fails for subtypes equals method overrides equals in superclass and may not be symmetric SonarQube Java Plugin 4.11 S2162

Related Guidelines MITRE CWE CWE-697, Insufficient Comparison Bibliography [ API 2014] Class URI Class URL (method equals() ) [ Bloch 2008] Item 8, "Obey the General Contract When Overriding equals" [ Darwin 2004] Section 9.2, "Overriding the equals Method" [ Harold 1997] [ Sun 2006] [ Techtalk 2007 ] Chapter 3, "Classes, Strings, and Arrays," section "The Object Class (Equality)" Determining If Two Keys Are Equal (JCA Reference Guide) "More Joy of Sets"