Define OpaqueData/OpaqueObject hashCode/equals
[mdsal.git] / binding / yang-binding / src / main / java / org / opendaylight / yangtools / yang / binding / AbstractOpaqueData.java
1 /*
2  * Copyright (c) 2019 PANTHEON.tech, s.r.o. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.binding;
9
10 import com.google.common.annotations.Beta;
11 import com.google.common.base.MoreObjects;
12 import com.google.common.base.MoreObjects.ToStringHelper;
13 import org.eclipse.jdt.annotation.NonNull;
14
15 /**
16  * Utility class for {@link OpaqueData} implementations. This class provides baseline implementation of
17  * {@link #hashCode()} and {@link #equals(Object)} as specified by {@link OpaqueData}. For cases where the object
18  * model's objects do not provide a usable implementation of hashCode/equals, this class is expected to be subclassed
19  * to provide alternative implementation of {@link #dataHashCode()} and {@link #dataEquals(Object)} methods. Such
20  * class should be made public in a convenient place. Note such customized methods are required to maintain consistency
21  * between hashCode and equals, as well as the <i>reflexive</i>, <i>symmetric</i>, <i>transitive</i> and
22  * <i>consistent</i> properties as detailed in {@link Object#equals(Object)}.
23  *
24  * @param <T> Data object model type
25  */
26 @Beta
27 public abstract class AbstractOpaqueData<T> implements OpaqueData<T> {
28     @Override
29     public final int hashCode() {
30         return 31 * getObjectModel().hashCode() + dataHashCode();
31     }
32
33     @Override
34     public final boolean equals(final Object obj) {
35         if (this == obj) {
36             return true;
37         }
38         if (!(obj instanceof OpaqueData)) {
39             return false;
40         }
41         final OpaqueData<?> other = (OpaqueData<?>) obj;
42         return getObjectModel().equals(other.getObjectModel()) && dataEquals(other.getData());
43     }
44
45     @Override
46     public final String toString() {
47         return addToStringAttributes(MoreObjects.toStringHelper(this).add("objectModel", getObjectModel())).toString();
48     }
49
50     protected ToStringHelper addToStringAttributes(final ToStringHelper helper) {
51         return helper.add("data", getData());
52     }
53
54     /**
55      * Determine hashCode of the data. The default implementation uses the data object's {@code hashCode} method.
56      *
57      * @return Hash code value of data
58      */
59     protected int dataHashCode() {
60         return getData().hashCode();
61     }
62
63     protected boolean dataEquals(final @NonNull Object otherData) {
64         return getData().equals(otherData);
65     }
66 }