How to adapt the Specification pattern to evaluate a combination of objects? - domain-driven-design

I know that the Specification pattern describes how to use a hierarchy of classes implementing ISpecification<T> to evaluate if a candidate object of type T matches a certain specification (= satisfies a business rule).
My problem : the business rule I want to implement needs to evaluate several objects (for example, a Customer and a Contract).
My double question :
Are there typical adaptations of the Specification patterns to achieve this ? I can only think of removing the implementation of ISpecification<T> by my specification class, and taking as many parameters as I want in the isSatisfiedBy() method. But by doing this, I lose the ability to combine this specification with others.
Does this problem reveal a flaw in my design ? (i.e. what I need to evaluate using a Customer and a Contract should be evaluated on another object, like a Subscription, which could contain all the necessary info) ?

In that case (depending on what the specification precisely should do, I would use one of the objects as specification subject and the other(s) as parameter.
Example:
public class ShouldCreateEmailAccountSpecification : ISpecification<Customer>
{
public ShouldCreateEmailAccountSpecification(Contract selectedContract)
{
SelectedContract = selectedContract;
}
public Contract SelectedContract { get; private set; }
public bool IsSatisfiedBy(Customer subject)
{
return false;
}
}

Your problem is that your specification interface is using a generic type parameter, which prevents it from being used for combining evaluation logic across different specializations (Customer,Contract) because ISpecification<Customer> is in fact a different interface than ISpecification<Contract>. You could use Jeff's approach above, which gets rid of the type parameter and passes everything in as a base type (Object). Depending on what language you are using, you may also be able to pull things up a level and combine specifications with boolean logic using delegates. C# Example (not particularly useful as written, but might give you some ideas for a framework):
ISpecification<Customer> cust_spec = /*...*/
ISpecification<Contract> contract_spec = /*... */
bool result = EvalWithAnd( () => cust_spec.IsSatisfiedBy(customer), () => contract_spec.IsSatisfiedBy( contract ) );
public void EvalWithAnd( params Func<bool>[] specs )
{
foreach( var spec in specs )
{
if ( !spec() )
return false; /* If any return false, we can short-circuit */
}
return true; /* all delegates returned true */
}

Paco's solution of treating one object as the subject and one as a parameter using constructor injection can work sometimes but if both objects are constructed after the specification object, it makes things quite difficult.
One solution to this problem is to use a parameter object as in this refactoring suggestion: http://sourcemaking.com/refactoring/introduce-parameter-object.
The basic idea is that if you feel that both Customer and Contract are parameters that represent a related concept, then you just create another parameter object that contains both of them.
public class ParameterObject
{
public Customer Customer { get; set; }
public Contract Contract { get; set; }
}
Then your generic specification becomes for that type:
public class SomeSpecification : ISpecification<ParameterObject>
{
public bool IsSatisfiedBy(ParameterObject candidate)
{
return false;
}
}

I don't know if I understood your question.
If you are using the same specification for both Customer and Contract, this means that you can send the same messages to both of them. This could be solved by making them both to implement an interface, and use this interface as the T type. I don't know if this makes sense in your domain.
Sorry if this is not an answer to your question.

Related

how to create models in nodejs

I am a .net developer, trying my hands on nodejs web api development.
I was wondering that whether we can create models in nodejs same as we create in asp.net web api.
For example
public class BaseResponse
{
public bool Success { get; set; }
public string ErrorMessage { get; set; }
}
public class MovieResponse : BaseResponse
{
public int MovieId { get; set; }
public string MovieName { get; set; }
}
This is how we do it in c#.
How can i create such models in nodejs.
Any npm package available?
There's good news and there's bad news. The bad news is the concept of classes and inheritance as you know it from other languages is not supported. The good news, JavaScript attempted to do something along that idea (although it did a miserable job implementing it). Below is an example of the code you provided using JavaScript:
function BaseResponse(success, errorMessage) {
this.success = success;
this.errorMessage = errorMessage;
}
function MovieResponse(success, errorMessage, movieId, movieName) {
BaseResponse.call(this, success, errorMessage); // Call the base class's constructor (if necessary)
this.movieId = movieId;
this.movieName = movieName;
}
MovieResponse.prototype = Object.create(BaseResponse);
MovieResponse.prototype.constructor = MovieResponse;
/**
* This is an example of an instance method.
*/
MovieResponse.prototype.instanceMethod = function(data) { /*...*/ };
/**
* This is an example of a static method. Notice the lack of prototype.
*/
MovieResponse.staticMethod = function(data) {/* ... */ };
// Instantiate a MovieResponse
var movieResInstance = new MovieResponse();
Mozilla has really good documentation on JavaScript and classes. In the code above, you are creating two functions BaseResponse and MovieResponse. Both of these functions act as constructors for an object with the appropriate "class" when you use the new keyword. You specify that MovieResponse inherits from BaseMovie with MovieResponse.prototype =Object.create(BaseResponse). This effectively sets MovieResponse's prototype chain equal to BaseResponse's prototype chain. You'll notice that immediately after setting MovieResponse's prototype chain I have to set its constructor to point to MovieResponse. If I didn't do this, every time you tried to initialize a MovieResponse, JavaScript would try to instead instantiate a BaseResponse (I told you they did a horrible job).
The rest of the code should be relatively straightforward. You can create instance methods on your brand new, shiny class by defining them on the prototype chain. If you define a function on BaseResponse that is not defined on MovieResponse but call the function on an instance of MovieResponse, JavaScript will "crawl" the prototype chain until it finds the function. Static methods are defined directly on the constructor itself (another weird feature).
Notice there is no concept of types or access modifiers (public/private). There are runtime tricks that you can implement to enforce types, but it's usually unnecessary in JavaScript and more prone to errors and inflexibility than adding such checks may justify.
You can implement the concept of private and protected members of a class in a more straightforward method than types. Using Node's require(), and assuming you wanted a private function called privateMethod you could implement it as:
function privateMethod() { /* privateMethod definition */ }
// Definition for MovieResponse's constructor
function MovieResponse() { /*...*/ }
module.exports = MovieResponse;
I will add a somewhat required commentary that I do not agree with: it is unnecessary to use inheritance in JavaScript. JavaScript uses a notion coined "duck typing" (if it looks like a duck and sounds like a duck, its a duck). Since JavaScript is weakly typed, it doesn't care if the object is a BaseResponse or MovieResponse, you can call any method or try to access any field you want on it. The result is usually an error or erroneous/error-prone code. I mention this here because you may come across the notion and its supporters. Know that such programming is dangerous and results in just bad programming practices.

DDD Invariants Business Rules and Validation

I am looking for advice on where to add validation rules for domain entities, and best practices for implementation. I did search and did not find what i was looking for, or i missed it.
I would like to know what the recommended way is for validating that properties are not null, in a certain range, or length, etc... I have seen several ways using an IsValid() and other discussions about enforcing in the constructor so the entity is never in an invalid state, or using preprocessing and postprocessing, and others using FluentValidation api, how invariants impact DRY and SRP.
Can someone give me a good example of where to put these sorts of checks, when using a App Service, Bounded Context, Domain Service, Aggregate Root, Entity layering. Where does this go, and what is the best approach?
Thanks.
When modeling your domain entity, it is best to consider real-world implications. Let's say you are dealing with a Employee entity.
Employees need a name
We know that in the real-world an employee must always have a name. It is impossible for an employee not to have a name. In other words, one cannot 'construct' an employee without specifying its name. So, use parameterised constructors! We also know that an employees name cannot change - so we prevent this from even happening by creating a private setter. Using the .NET type system to verify your employee is a very strong form of validation.
public string Name { get; private set; }
public Employee(string name)
{
Name = name;
}
Valid names have some rules
Now it starts to get interesting. A name has certain rules. Let's just take the simplistic route and assume that a valid name is one which is not null or empty. In the code example above, the following business rule is not validated against. At this point, we can still currently create invalid employees! Let's prevent this from EVER occurring by amending our setter:
public string Name
{
get
{
return name;
}
private set
{
if (String.IsNullOrWhiteSpace(value))
{
throw new ArgumentOutOfRangeException("value", "Employee name cannot be an empty value");
}
name = value;
}
}
Personally I prefer to have this logic in the private setter than in the constructor. The setter is not completely invisible. The entity itself can still change it, and we need to ensure validity. Also, always throw exceptions!
What about exposing some form of IsValid() method?
Take the above Employee entity. Where and how would an IsValid() method work?
Would you allow an invalid Employee to be created and then expect the developer to check it's validity with an IsValid() check? This is a weak design - before you know it, nameless Employees are going to be cruising around your system causing havoc.
But perhaps you would like to expose the name validation logic?
We don't want to catch exceptions for control flow. Exceptions are for catastrophic system failure. We also don't want to duplicate these validation rules in our codebase. So, perhaps exposing this validation logic isn't such a bad idea (but still not the greatest!).
What you could do is provide a static IsValidName(string) method:
public static bool IsValidName(string name)
{
return (String.IsNullOrWhiteSpace(value))
}
Our property would now change somewhat:
public string Name
{
get
{
return name;
}
private set
{
if (!Employee.IsValidName(value))
{
throw new ArgumentOutOfRangeException("value", "Employee name cannot be an empty value");
}
name = value;
}
}
But there is something fishy about this design...
We now are starting to spawn validation methods for individual properties of our entity. If a property has all kinds of rules and behavior attached to it, perhaps this is a sign that we can create an value object for it!
public PersonName : IEquatable<PersonName>
{
public string Name
{
get
{
return name;
}
private set
{
if (!PersonName.IsValid(value))
{
throw new ArgumentOutOfRangeException("value", "Person name cannot be an empty value");
}
name = value;
}
}
private PersonName(string name)
{
Name = name;
}
public static PersonName From(string name)
{
return new PersonName(name);
}
public static bool IsValid(string name)
{
return !String.IsNullOrWhiteSpace(value);
}
// Don't forget to override .Equals
}
Now our Employee entity can be simplified (I have excluded a null reference check):
public Employee
{
public PersonName Name { get; private set; }
public Employee(PersonName name)
{
Name = name;
}
}
Our client code can now look something like this:
if(PersonName.IsValid(name))
{
employee = new Employee(PersonName.From(name));
}
else
{
// Send a validation message to the user or something
}
So what have we done here?
We have ensured that our domain model is always consistent. Extremely important. An invalid entity cannot be created. In addition, we have used value objects to provide further 'richness'. PersonName has given the client code more control and more power and has also simplified Employee.
I built a library that can help you.
https://github.com/mersocarlin/ddd-validation

How do I call a method of an attribute derived from a generic interface, where the specific type is not known?

Core Question:
I have a generic interface IValidatingAttribute<T>, which creates the contract bool IsValid(T value); The interface is implemented by a variety of Attributes, which all serve the purpose of determining if the current value of said Field or Property they decorate is valid per the interface spec that I'm dealing with. What I want to do is create a single validation method that will scan every field and property of the given model, and if that field or property has any attributes that implement IValidatingAttribute<T>, it should validate the value against each of those attributes. So, using reflection I have the sets of fields and properties, and within those sets I can get the list of attributes. How can I determine which attributes implement IValidatingAttribute and then call IsValid(T value)?
background:
I am working on a library project that will be used to develop a range of later projects against the interface for a common third party system. (BL Server, for those interested)
BL Server has a wide range of fairly arcane command structures that have varying validation requirements per command and parameter, and then it costs per transaction to call these commands, so one of the library requirements is to easily define the valdiation requirements at the model level to catch invalid commands before they are sent. It is also intended to aid in the development of later projects by allowing developers to catch invalid models without needing to set up the BL server connections.
Current Attempt:
Here's where I've gotten so far (IsValid is an extension method):
public interface IValidatingAttribute<T>
{
bool IsValid(T value);
}
public static bool IsValid<TObject>(this TObject sourceObject) where TObject : class, new()
{
var properties = typeof(TObject).GetProperties();
foreach (var prop in properties)
{
var attributeData = prop.GetCustomAttributesData();
foreach (var attribute in attributeData)
{
var attrType = attribute.AttributeType;
var interfaces = attrType.GetInterfaces().Where(inf => inf.IsGenericType).ToList();
if (interfaces.Any(infc => infc.Equals(typeof(IValidatingAttribute<>))))
{
var value = prop.GetValue(sourceObject);
//At this point, I know that the current attribute implements 'IValidatingAttribute<>', but I don't know what T is in that implementation.
//Also, I don't know what data type 'value' is, as it's currently boxed as an object.
//The underlying type to value will match the expected T in IValidatingAttribute.
//What I need is something like the line below:
if (!(attribute as IValidatingAttribute<T>).IsValid(value as T)) //I know this condition doesn't work, but it's what I'm trying to do.
{
return false;
}
}
}
return true;
}
}
Example usage:
Just to better explain what I am trying to achieve:
public class SomeBLRequestObject
{
/// <summary>
/// Required, only allows exactly 2 alpha characters.
/// </summary>
[MinCharacterCount(2), MaxCharacterCount(2), IsRequired, AllowedCharacterSet(CharSets.Alpha))]
public string StateCode {get; set;}
}
And then, later on in code:
...
var someBLObj = SomeBLRequestObjectFactory.Create();
if(!someBLObj.IsValid())
{
throw new InvalidObjectException("someBLObj is invalid!");
}
Thank you, I'm really looking for a solution to the problem as it stands, but I'm more than willing to listen if somebody has a viable alternative approach.
I'm trying to go generic extension method with this because there are literally hundreds of the BL Server objects, and I'm going with attributes because each of these objects can have upper double digit numbers of properties, and it's going to make things much, much easier if the requirements for each object are backed in and nice and readable for the next developer to have to use this thing.
Edit
Forgot to mention : This Question is the closest I've found, but what I really need are the contents of \\Do Something in TcKs's answer.
Well, after about 6 hours and a goods nights sleep, I realized that I was over-complicating this thing. Solved it with the following (ExtValidationInfo is the class that the below two extensions are in.):
Jon Skeet's answer over here pointed me at a better approach, although it still smells a bit, this one at least works.
public static bool IsValid<TObject>(this TObject sourceObject) where TObject : class, new()
{
var baseValidationMethod = typeof(ExtValidationInfo).GetMethod("ValidateProperty", BindingFlags.Static | BindingFlags.Public);
var properties = TypeDataHandler<TObject>.Properties;
foreach (var prop in properties)
{
var attributes = prop.GetCustomAttributes(typeof(IValidatingAttribute<>)).ToList();
if (!attributes.Any())
{
continue; // No validators, skip.
}
var propType = prop.PropertyType;
var validationMethod = baseValidationMethod.MakeGenericMethod(propType);
var propIsValid = validationMethod.Invoke(null, prop.GetValue(sourceObject), attributes);
if(!propIsValid)
{
return false;
}
}
return true;
}
public static bool ValidateProperty<TPropType>(TPropType value, List<IValidatingAttribute<TPropType>> validators)
{
foreach (var validator in validators)
{
if (!validator.IsValid(value))
{
return false;
}
}
return true;
}

State Pattern and Domain Driven Design

We often use simple enumerations to represent a state on our entities. The problem comes when we introduce behaviour that largely depends on the state, or where state transitions must adhere to certain business rules.
Take the following example (that uses an enumeration to represent state):
public class Vacancy {
private VacancyState currentState;
public void Approve() {
if (CanBeApproved()) {
currentState.Approve();
}
}
public bool CanBeApproved() {
return currentState == VacancyState.Unapproved
|| currentState == VacancyState.Removed
}
private enum VacancyState {
Unapproved,
Approved,
Rejected,
Completed,
Removed
}
}
You can see that this class will soon become quite verbose as we add methods for Reject, Complete, Remove etc.
Instead we can introduce the State pattern, which allows us to encapsulate each state as an object:
public abstract class VacancyState {
protected Vacancy vacancy;
public VacancyState(Vacancy vacancy) {
this.vacancy = vacancy;
}
public abstract void Approve();
// public abstract void Unapprove();
// public abstract void Reject();
// etc.
public virtual bool CanApprove() {
return false;
}
}
public abstract class UnapprovedState : VacancyState {
public UnapprovedState(vacancy) : base(vacancy) { }
public override void Approve() {
vacancy.State = new ApprovedState(vacancy);
}
public override bool CanApprove() {
return true;
}
}
This makes it easy to transition between states, perform logic based on the current state or add new states if we need to:
// transition state
vacancy.State.Approve();
// conditional
model.ShowRejectButton = vacancy.State.CanReject();
This encapsulation seems cleaner but given enough states, these too can become very verbose. I read Greg Young's post on State Pattern Misuse which suggests using polymorphism instead (so I would have ApprovedVacancy, UnapprovedVacancy etc. classes), but can't see how this will help me.
Should I delegate such state transitions to a domain service or is my use of the State pattern in this situation correct?
To answer your question, you shouldn't delegate this to a domain service and your use of the State pattern is almost correct.
To elaborate, the responsibility for maintaining the state of an object belongs with that object, so relegating this to a domain service leads to anemic models. That isn't to say that the responsibility of state modification can't be delegated through the use of other patterns, but this should be transparent to the consumer of the object.
This leads me to your use of the State pattern. For the most part, you are using the pattern correctly. The one portion where you stray a bit is in your Law of Demeter violations. The consumer of your object shouldn't reach into your object and call methods on it's state (e.g. vacancy.State.CanReject()), but rather your object should be delegating this call to the State object (e.g. vacancy.CanReject() -> bool CanReject() { return _state.CanReject(); }). The consumer of your object shouldn't have to know that you are even using the State pattern.
To comment on the article you've referenced, the State pattern relies upon polymorphism as it's facilitating mechanism. The object encapsulating a State implementation is able to delegate a call to whichever implementation is currently assigned whether that be something that does nothing, throws an exception, or performs some action. Also, while it's certainly possible to cause a Liskov Substitution Principle violation by using the State pattern (or any other pattern), this isn't determined by the fact that the object may throw an exception or not, but by whether modifications to an object can be made in light of existing code (read this for further discussion).

avoiding type switching

If you're in a team and a programmer gives you an interface with create, read, update and delete methods, how do you avoid type switching?
Quoting Clean Code A Handbook of Agile Software Craftsmanship:
public Money calculatePay(Employee e)
throws InvalidEmployeeType {
switch (e.type) {
case COMMISSIONED:
return calculateCommissionedPay(e);
case HOURLY:
return calculateHourlyPay(e);
case SALARIED:
return calculateSalariedPay(e);
default:
throw new InvalidEmployeeType(e.type);
}
}
There are several problems with this function. First, it’s large, and when new
employee types are added, it will grow. Second, it very clearly does more than one thing.
Third, it violates the Single Responsibility Principle7 (SRP) because there is more than one reason for it to change. Fourth, it violates the Open Closed Principle8 (OCP) because it must change whenever new types are added. But possibly the worst problem with this
function is that there are an unlimited number of other functions that will have the same
structure. For example we could have
isPayday(Employee e, Date date),
or
deliverPay(Employee e, Money pay),
or a host of others. All of which would have the same deleterious structure.
The book tells me to use the Factory Pattern, but in way that it makes me feel that I shouldn't really use it.
Quoting the book again:
The solution to this problem (see Listing 3-5) is to bury the switch statement in the
basement of an ABSTRACT FACTORY,9 and never let anyone see it.
Is the switch statement ugly?
In reality, the employee object should have its own calculate pay function that will give you the pay. This calculate pay function would change based on what type of employee it was.
That way it is up to the object to define the implementation, not the user of the object.
abstract class Employee
{
public abstract function calculatePay();
}
class HourlyEmployee extends Employee
{
public function calculatePay()
{
return $this->hour * $this->pay_rate;
}
}
class SalariedEmployee extends Employee
{
public function calculatePay()
{
return $this->monthly_pay_rate;
}
}
When you build the Factory, THEN you do the switch statement there, and only once, to build the employee.
Lets say Employee was in an array, and the type of employee was held in $array['Type']
public function buildEmployee($array)
{
switch($array['Type']){
case 'Hourly':
return new HourlyEmployee($array);
break;
case 'Salaried':
return new SalariedEmployee($array);
break;
}
Finally, to calculate the pay
$employee->calculatePay();
Now, there is no need for more than one switch statement to calculate the pay of the employee based on what type of employee they are. It is just a part of the employee object.
Disclaimer, I'm a minor, so I'm not completely positive on how some of these pays are calculated. But the base of the argument is still valid. The pay should be calculated in the object.
Disclaimer 2, This is PHP Code. But once again, the argument should be valid for any language.
You can totally remove the switch by using a Map of some kind to map the type of an employee to it's corresponding pay calculator. This depends on reflection and is possible in all languages I know.
Assuming the pay calculation is not a responsibility of an employee, we have an interface PayCalculation:
interface PayCalculation {
function calculatePay(Employee $employee);
}
There's an implementation for each category of employee:
class SalariedPayCalculator implements PayCalculation {
public function calculatePay(SalariedEmployee $employee) {
return $employee.getSalary();
}
}
class HourlyPayCalculator implements PayCalculation {
public function calculatePay(HourlyEmployee $employee) {
return $employee.getHourlyRate() * e.getHoursWorked();
}
}
class CommissionedPayCalculator implements PayCalculation {
public function calculatePay(CommissionedEmployee $employee) {
return $employee.getCommissionRate() * $employee.getUnits();
}
}
And the pay calculation would work something like this. Reflection becomes important for this to look at an object and determine it's class at run-time. With this, the switch loop can be eliminated.
public class EmployeePayCalculator implements PayCalculation {
private $map = array();
public function __construct() {
$this->map['SalariedEmployee'] = new SalariedPayCalculator();
$this->map['HourlyEmployee'] = new HourlyPayCalculator();
$this->map['CommissionedEmployee'] = new CommissionedPayCalculator();
}
public function calculatePay(Employee $employee) {
$employeeType = get_class($employee);
$calculator = $this->map[$employeeType];
return $calculator->calculatePay($employee);
}
}
Here we are initializing the map in the constructor, but it can easily be moved outside to an XML configuration file or some database:
<payCalculation>
<category>
<type>Hourly</type>
<payCalculator>HourlyPayCalculator</payCalculator>
</category>
<category>
<type>Salaried</type>
<payCalculator>SalariedPayCalculator</payCalculator>
</category>
...
</payCalculation>
I read it somewhere, that if you're using a switch, then it's suspect that there's too much variation. And when we have too much variation, we should try to encapsulate the variation behind an interface, thereby decoupling the dependencies between objects. Having said that, I think that you should try to create an SalaryType lightweight base class object that will encapsulate this type of logic. Then you make it a member of class Employee and rid yourself of the switch construct. Here's what I mean in a nutshell:
abstract class SalaryType
{
function calculatePay() {}
}
class CommissionedType extends SalaryType
{
function calculatePay() {}
}
class HourlyType extends SalaryType
{
function calculatePay() {}
}
class SalaryType extends SalaryType
{
function calculatePay() {}
}
class Employee
{
private $salaryType;
public function setType( SalaryType emp )
{
$this->salaryType = emp;
}
public function calculatePay()
{
$this->salaryType->calculatePay();
}
}
Btw, a lot of your example code does not seem very "PHP-ish". There are no return types in PHP nor is there really any type safety. Keep in mind also that PHP is not truly polymorphic, so some of the polymorphic behavior found in typical type-safe languages may not work as expected here.

Resources