开发者

class design for for a dynamic GetHash function

开发者 https://www.devze.com 2023-02-20 03:10 出处:网络
I have the requirement to calculate an internal hashcode of instances of several types (some types are derived from each other). Two aspect开发者_开发知识库s are dynamic here and can vary independentl

I have the requirement to calculate an internal hashcode of instances of several types (some types are derived from each other). Two aspect开发者_开发知识库s are dynamic here and can vary independently. Only the client that requests the hash knows what hash algorithm is to be used and what properties are to be included.

  1. The actual algorithm that is used for the hash caluctation can change.
  2. What members for each type should be take into account for the hash calculation can change.

How would you design your types around these requirement?


First, require all "hashable" objects to implement the same interface, with one method: getHash().

Second, introduce an Abstract Factory instantiating hash Strategies.

Example (Java 1.6):

public class Foo implements Hashable {
  private String field;
  @Override
  public String getHash() {
    HashFactory.INSTANCE.getMD5Strategy().hash(this.field);
  }
}

Proper encapsulation of decision making inside your objects, and an effective decoupling of strategies and objects.


Here are some guidelines for GetHashCode() from Eric Lippert.

http://ericlippert.com/2011/02/28/guidelines-and-rules-for-gethashcode/

An excerpt:
Rule: the integer returned by GetHashCode must never change while the object is contained in a data structure that depends on the hash code remaining stable

It is permissible, though dangerous, to make an object whose hash code value can mutate as the fields of the object mutate. If you have such an object and you put it in a hash table then the code which mutates the object and the code which maintains the hash table are required to have some agreed-upon protocol that ensures that the object is not mutated while it is in the hash table. What that protocol looks like is up to you.

In short, if the algorithm for generating the hash code can change, then you need to make sure that it doesn't change while the object is in your collection.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号