HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Nice design of my hash service class

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
designnicehashserviceclass

Problem

I would like to know, if my design of this class is good OOP.
Should I implement for every hash algorithm a separate class?
I'm asking this, because the HashService can be used with a KeyedHashAlgorithm which wouldn't work correctly?!

```
public class HashService : IDisposable
{
public HashService(HashAlgorithm algorithm)
{
HashAlgorithm = algorithm;
Encoder = Encoding.UTF8;
}

protected HashAlgorithm HashAlgorithm { get; set; }

///
/// The size, in bits, of the computed hash code.
///
public int HashSize
{
get { return HashAlgorithm.HashSize; }
}

///
/// Gets or sets the encoding for strings.
///
public Encoding Encoder { get; set; }

public string ComputeHash(string input)
{
byte[] bytes = Encoder.GetBytes(input);
byte[] hash = ComputeHash(bytes);
return ToHex(hash); // method impl. omitted
}

///
/// Computes the hash value for the specified byte array
///
/// The input to compute the hash code for.
/// The computed hash code.
public byte[] ComputeHash(byte[] buffer)
{
return HashAlgorithm.ComputeHash(buffer);
}

public byte[] ComputeHash(byte[] buffer, int offset, int count)
{
return HashAlgorithm.ComputeHash(buffer, offset, count);
}

public byte[] ComputeHash(Stream inputStream)
{
return HashAlgorithm.ComputeHash(inputStream);
}

#region Implementation of IDisposable

// omitted

#endregion

// ReSharper disable InconsistentNaming
public static HashService CreateMd5()
{
return new HashService(new MD5CryptoServiceProvider());
}

public static HashService CreateRIPEMD160()
{
return new HashService(new RIPEMD160Managed());
}

public static HashService CreateSHA256()
{
return new HashService(new SHA256Managed());
}

public static HashService CreateSHA384()
{
return new

Solution

Overall, its nice code. Easy to read and good use of white space.

I would move the creating of the HashService to a Factory class though. The way you are using it, I don't think it belongs in the class.

public class HashServiceFactory
{
    public Create(HashAlgorithm algorithm)
    {
        return new HashService(algorithm);
    }
}

// Usage

var factory = new HashServiceFactory();

var sha256Managed = factory.Create(new SHA256Managed());
var md5CryptoServiceProvider = factory.Create(new MD5CryptoServiceProvider());

Code Snippets

public class HashServiceFactory
{
    public Create(HashAlgorithm algorithm)
    {
        return new HashService(algorithm);
    }
}

// Usage

var factory = new HashServiceFactory();

var sha256Managed = factory.Create(new SHA256Managed());
var md5CryptoServiceProvider = factory.Create(new MD5CryptoServiceProvider());

Context

StackExchange Code Review Q#20134, answer score: 2

Revisions (0)

No revisions yet.