
com.usefulmilk.support.domain.DomainObject Maven / Gradle / Ivy
The newest version!
/*
* Copyright 2016 UsefulMilk
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.usefulmilk.support.domain;
import com.usefulmilk.support.Validate;
import java.util.Objects;
/**
* It is a base class for domain objects.
* {@link DomainObject} is a super class of {@link Entity} class and {@link ValueObject} class.
* The idea behind this class is supply a default way to create identities by using generics.
*/
abstract class DomainObject {
private T id;
/**
* Set an identity for this object.
* @param id The identity of this object.
*/
public void setId(T id){
if(this.id != null && !this.id.equals(id)){
throw new IllegalStateException("Id was already set. You cannot change it.");
}
this.id = Validate.nonNullArgument(id);
}
/**
* Get an identity of this object.
* @return The identity of this object.
*/
public T getId() {
return id;
}
@Override
public abstract int hashCode();
@Override
public abstract boolean equals(Object obj);
/**
* Check if two {@link DomainObject} instances are equals.
* @param domainObject1 A {@link DomainObject} to be compared.
* @param domainObject2 A {@link DomainObject} to be compared.
* @return Return true it they are equals.
*/
static boolean idEquals(DomainObject> domainObject1, DomainObject> domainObject2) {
if (domainObject1 == null && domainObject2 == null){
return false;
}
if (domainObject1 == domainObject2){
return true;
}
if (domainObject1 == null ||
domainObject2 == null ||
domainObject1.getClass() != domainObject2.getClass()){
return false;
}
return Objects.equals(domainObject1.getId(), domainObject2.getId());
}
/**
* Get the hashCode of Id.
* @param domainObject The {@link DomainObject} owner of Id.
* @return Return the hashCode of Id.
*/
static int getIdHashCode(DomainObject> domainObject) {
return Objects.hash(domainObject.getId());
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy