Skip to content

Commit

Permalink
feat : add valueObject
Browse files Browse the repository at this point in the history
  • Loading branch information
Nikoo-Asadnejad committed Oct 28, 2023
1 parent 1584e30 commit cb498f9
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 3 deletions.
3 changes: 0 additions & 3 deletions Src/Product.Domain/Entities/BaseModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,23 +23,20 @@ public virtual void Create(string? ip = null , long? createdBy = null)
ValidateIp(ip);
this.CreateIp = ip;
}

public virtual void Update(string? ip = null, long? updatedBy = null)
{
this.UpdateDate = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
this.UpdatedBy = updatedBy;
ValidateIp(ip);
this.UpdateIp = ip;
}

public virtual void Delete(string? ip = null, long? deletedBy = null)
{
this.DeleteDate = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
this.DeletedBy = deletedBy;
ValidateIp(ip);
this.DeleteIp = ip;
}

void ValidateIp(string? ip)
{
if(string.IsNullOrWhiteSpace(ip))
Expand Down
6 changes: 6 additions & 0 deletions Src/Product.Domain/ValueObjects/IPAddress.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace Product.Domain.ValueObjects;

public class IPAddress
{

}
47 changes: 47 additions & 0 deletions Src/Product.Domain/ValueObjects/ValueObject.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
namespace Product.Domain.ValueObjects;

public abstract class ValueObject : IEquatable<ValueObject>
{
public static bool operator ==(ValueObject one, ValueObject two)
=> EqualOperator(one, two);


public static bool operator !=(ValueObject one, ValueObject two)
=> !EqualOperator(one, two);


public bool Equals(ValueObject? other)
=> other is not null && ValuesAreEqual(other);


public override bool Equals(object? obj)
{
if (obj is null || obj.GetType() != GetType())
return false;

return obj is ValueObject other && ValuesAreEqual(other);
}

public override int GetHashCode()
=> GetEqualityComponents()
.Select(x => x is not null ? x.GetHashCode() : 0)
.Aggregate((x, y) => x ^ y);


protected static bool EqualOperator(ValueObject? left, ValueObject? right)
{
if (left is null && right is null)
return true;

if (left is null || right is null)
return false;

return ReferenceEquals(left, right) || left.Equals(right);
}

protected abstract IEnumerable<object> GetEqualityComponents();

private bool ValuesAreEqual(ValueObject? other)
=> other is not null && GetEqualityComponents().SequenceEqual(other.GetEqualityComponents());

}

0 comments on commit cb498f9

Please sign in to comment.