I'm creating an application which's architecture is based on Uncle Bob's Clean Architecture concepts and DDD. Note that it is BASED on DDD, so I gave myself the freedom to differ from strict DDD.
To create this application, I am using C# with .Net Standard 2.0
One of the principles of DDD relates to Value Objects. The definition for Value Objects, according to Wikipedia is as follows:
Value Object
An object that contains attributes but has no conceptual identity. They should be treated as immutable.
Example: When people exchange business cards, they generally do not distinguish between each unique card; they only are concerned about the information printed on the card. In this context, business cards are value object
Now, I want that my Value Objects does not allow their creation if some validation does not succeed. When it happens, an exception would be thrown during the instantiation. I really meant to throw an exception there, because the core of the architecture really does not expect any invalid data to reach that point.
Before going further on this question, to give you guys some more background, here is my architecture (NOTE: still incomplete):
The rules I am following in this architecture is:
- A layer can only know about its immediate innermost neighbor layer's interfaces
- A layer cannot know anything about any outermost layer
- All communications between layers MUST be done through interfaces
- Each layer must be independently deployable
- Each layer must be independently developable
To better understand the arrows in this diagram, I recommend reading those Stack Exchanges's questions:
https://stackoverflow.com/questions/1874049/explanation-of-the-uml-arrows
Now, the challenge I'm facing right now, is finding a good way to use the validators. I'm not satisfied with my architecture in this point. The problem is the following:
Since I can have thousands of Value Objects being instantiated at a given time, I don't want each instance of the Value Objects to have an instance method to perform the validation. I want the validation method to be static, since it's logic will be the same for every instance. Also, I want the validation logic to be available for the upper layer of the architecture to use to perform validations without trying to instantiating the Value Objects, thus causing an expensive exception to be thrown.
The problem is: C# DOES NOT ALLOW polymorphism with static methods, so I can't do something like:
internal interface IValueObject<T>
{
T Value { get; }
static bool IsValid(T value);
}
How can I achieve this functionality without relying on static methods polymorphism and, at the same time, not wasting memory?