Equals vs the Encapsulation Boundary

From CSSEMediaWiki
(Difference between revisions)
Jump to: navigation, search
(New page: If we make the assumption the Object encapsulation is preferred we end up in a slight conundrum... Java's Object class provides a over-ridable method 'equals(...)' in which the current obj...)
 
Line 7: Line 7:
  
 
== What is the problem? ==
 
== What is the problem? ==
In Java, two classes can compare if they are equivalent by comparing the relevant data fields in each class. This breaks object encapsulation.
+
In Java, two classes can be compared if they are equivalent by comparing the relevant data fields in each class. This breaks object encapsulation.
  
 
== How can we solve this? ==
 
== How can we solve this? ==

Revision as of 04:52, 30 July 2009

If we make the assumption the Object encapsulation is preferred we end up in a slight conundrum... Java's Object class provides a over-ridable method 'equals(...)' in which the current object compares itself with a provided object for equality and/or equivalence. We assume an ideal language.

Contents

What is equality?

Equality/equivalence (they are slightly different) can fall into two distinct categories:

  • Two objects are 'equal' if they are the same object. (Equality)
  • Two objects are 'equal' if certain properties of each object have the same values. (Equivalence)

What is the problem?

In Java, two classes can be compared if they are equivalent by comparing the relevant data fields in each class. This breaks object encapsulation.

How can we solve this?

Various options exist:

  • We can decide that object encapsulation is bad.
  • We can decide that object encapsulation is good, but provide an exception.
  • We can decide that object encapsulation is good.

If object encapsulation is good:

  • We can provide a subclass-able Comparator class that can provide comparisons of equality between two provided objects of a class. This means that any fields that need to be compared need to be made accessible, probably in the form of getters.
  • Other solutions?

Is this a more general problem?

Is this a more general problem with object encapsulation? Is it not a problem at all?

Personal tools