Skip to content

Instantly share code, notes, and snippets.

@zharro
Last active April 22, 2018 05:13
Show Gist options
  • Save zharro/35ef90a04ee1193310aaa618fc2d582c to your computer and use it in GitHub Desktop.
Save zharro/35ef90a04ee1193310aaa618fc2d582c to your computer and use it in GitHub Desktop.
Value object simple example and base class. Base class comes from @vkhorikov (https://github.com/vkhorikov/DddInAction/tree/master/DddInPractice.Logic/Common)
using System;
class DateTimeRange : ValueObject<DateTimeRange>
{
public DateTime Start { get; }
public DateTime End { get; }
public DateTimeRange(DateTime start, DateTime end)
{
Start = start;
End = end;
}
public DateTimeRange(DateTime start, TimeSpan duration)
{
Start = start;
End = start.Add(duration);
}
// Business logic
public int DurationInMinutes()
{
return (End - Start).Minutes;
}
public bool Overlaps(DateTimeRange dateTimeRange)
{
return Start < dateTimeRange.End &&
End > dateTimeRange.Start;
}
// Useful factory methods
public static DateTimeRange CreateOneDayRange(DateTime day)
{
return new DateTimeRange(day, day.AddDays(1));
}
public static DateTimeRange CreateOneWeekRange(DateTime startDay)
{
return new DateTimeRange(startDay, startDay.AddDays(7));
}
// Equality comparison
protected override bool EqualsCore(DateTimeRange other)
{
return Start == other.Start
&& End == other.End;
}
protected override int GetHashCodeCore()
{
var hashCode = Start.GetHashCode();
hashCode = (hashCode * 397) ^ End.GetHashCode();
return hashCode;
}
}
public abstract class ValueObject<T>
where T : ValueObject<T>
{
public override bool Equals(object obj)
{
var valueObject = obj as T;
if (ReferenceEquals(valueObject, null))
return false;
return EqualsCore(valueObject);
}
protected abstract bool EqualsCore(T other);
public override int GetHashCode()
{
return GetHashCodeCore();
}
protected abstract int GetHashCodeCore();
public static bool operator ==(ValueObject<T> a, ValueObject<T> b)
{
if (ReferenceEquals(a, null) && ReferenceEquals(b, null))
return true;
if (ReferenceEquals(a, null) || ReferenceEquals(b, null))
return false;
return a.Equals(b);
}
public static bool operator !=(ValueObject<T> a, ValueObject<T> b)
{
return !(a == b);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment