Sharp Architecture Value Objects - domain-driven-design

I'm checking out Sharp Architecture's code. So far it's cool, but I'm having problems getting my head around how to implement DDD value objects in the framework (doesn't seem to be anything mentioning this in the code). I'm assuming the base Entity class and Repository base are to be used for entities only. Any ideas on how to implement value objects in the framework?

In Sharp Arch there is a class ValueObject in namespace SharpArch.Domain.DomainModel. This object inherits from BaseObject and overrides the == and != operators and the Equals() and GetHashCode() methods. The method overrides just calls the BaseObject versions of those two methods which in turn uses GetTypeSpecificSignatureProperties() method to get the properties to use in the equality comparison.
Bottom line is that Entity's equality is determined by
Reference equality
Same type?
Id's are the same
Comparison of all properties decorated with the [DomainSignature] attribute
For ValueObjects, the BaseObject's Equals method is used
Reference equality
Same type?
Compare all public properties
This is a little bit simplified, I suggest you get the latest code from github and read through the code in the mentioned 3 classes yourself.
Edit: Regarding persistence, this SO question might help. Other than that, refer to the official NH and Fluent NH documentation

Value objects are simple objects that don't require a base class. (The only reason entities have base classes is to provide equality based on the identity). Implementing a value object just means creating a class to represent a value from your domain. A lot of times value objects should be immutable and provide equality comparison methods to determine equality to other value objects of the same type. Take a look here.

Related

Is it safe to use Class level Predicate in Multithreading Application

I am trying to understand if there could be any issues with Predicate defined at class level in multithreaded application. ? We have defined such predicates in our services and using them up different methods of same class. Currently we have not seen any issue but I am curious to understand our class level Predicate object is going to function. will there be any inconsistency in the behaviour?
eg:
class SomeClass{
Predicate<String> check = (value) -> value.contains("SomeString");
// remaning impl. of the class.
}
The predicate in your example is categorically thread-safe. It is calling a method on an intrinsicly thread-safe (and immutable) object.
This does not generalize to all predicates though. For example
Predicate<StringBuilder> check = (value) -> value.indexOf("SomeString") >= 0;
is not thread-safe. Another thread could mutate the contents of the StringBuilder argument while this predicate is checking it. The predicate could also be vulnerable to memory model related inconsistencies.
(The StringBuilder class is not thread-safe; see javadoc.)
It is not clear what you mean by "class level". Your example shows a predicate declared as a regular field, not a static (class level) field.
With a variable declared as a (mutable) instance field, it is difficult to reason about the thread-safety of the field in isolation. This can be solved by declaring the field as final.

Mockito discourages mocking VO and DTOs ? A good reason why [duplicate]

In the book GOOS. It is told not to mock values, which leaves me confused. Does it means that values don't have any behavior?
I dont' much knowledge about the value object but AFAIK the value objects are those which are immutable. Is there any heuristic on deciding when to create a value object?
Not all immutable objects are value objects. By the way, when designing, consider that the ideal object has only immutable fields and no-arg methods.
Regarding the heuristic, a valid approach can be considering how objects will be used: if you build an instance, invoke some methods and then are done with it (or store it in a field) likely it won't be a value object. On the contrary, if you keep objects in some data structure and compare them (with .equals()) likely you have a value object. This is especially true for objects that will be used to key Maps
Value objects should be automatic-tested themselves (and tests are usually a pleasure to read and write because are straightforward) but there's no point in mocking them: the main practical reasons for mocking interfaces is that implementation classes
are usually difficult to build (need lot of collaborators)
are expensive to run (access the network, the filesystem, ...).
Neither apply to value objects.
Quoting the linked blog post:
There are a couple of heuristics for when a class is not worth mocking. First, it has only accessors or simple methods that act on values it holds, it doesn't have any interesting behaviour. Second, you can't think of a meaningful name for the class other than VideoImpl or some such vague term.
The implication of the first point, in the context of a section entitled "Don't mock value objects", is that value objects don't have interesting behaviour.

Using interfaces directly in C#

I recently read in "Professional C# 4 and .NET 4" that:
You can never instantiate an interface.
But periodically I see things like this:
IQuadrilateral myQuad;
What are the limitations in using interfaces directly (without having a class inherit from the interface)? How could I use such objects (if they can even be called objects)?
For example instead of using a Square class that derives from IQuadrilateral, to what extent could I get away with creating an interface like IQuadrilateral myQuad?
Since interfaces don't implement methods, I don't think I could use any methods with them. I thought interfaces didn't have fields to them (only properties), so I'm not sure how I could store data with them.
The answer is simple, you can't instantiate an interface.
The example you provided is not an example of instantiating an interface, you are just defining a local variable of the type IQuadrilateral
To instantiate the interface, you would have to do this:
IQuadrilateral myQuad = new IQuadrilateral();
And that isn't possible since IQuadrilateral does not have a constructor.
This is perfectly valid:
IQuadrilateral myQuad = new Square();
But you aren't initiating IQuadrilateral, you are initiating Square and assigning it to a variable with the type IQuadrilateral.
The methods available in myQuad would be the methods defined in the interface, but the implementation would be based on the implementation in Square. And any additional methods in Square that are not part of the IQuadrilateral interface would not be available unless you cast myQuad to a Square variable.
You can't create an instance of an interface.
The code you showed defines a variable of type IQuadrilateral. The actual instance this variable points to will always be of a concrete class implementing this interface.
Background Knowledge
Think of an interface as a contract. In a contract between two people, it defines what is capable, what is expected from the parties involved. In programming, it works the same way. The interface defines what to expect, what must exist for you to conform to that interface. Therefore, since it only defines what to expect, it itself, doesn't provide the implementation, the "code under the covers" so to speak, does.
A property behaves like a field, but allows you to intercept when someone assigns a value to it or reads the value. You can also deny reading or writing to it, your choice when you define the property. Interfaces work with properties instead of fields because of this. Since the "contract" is just defining what property should be there (name and type), and if it should allow a read or write capabilities, it leaves it up to the implementer to provide this.
Take for example the IEnumerator interface from the .NET framework. This interface was designed to allow iteration over a collection of objects. The purpose is not to change items, or randomly access them, it's just for getting object A and moving to the next, and the next, and the next, as many times as needed. Many collection type classes implement this: Queue, ArrayList, SortedList, Stack, etc. All these types of objects store many objects and now they all share the common "contract": the ability to iterate one-by-one over them.
However, you can see that the IEnumerator interface has a MoveNext() method declared. Why? This is because the items may not be served in the same manner. For example, people will generally access the ArrayList from the first item to the last. But a Stack was designed opposite, for people to access the last object down to the first.
Questions Answered
With all this knowledge, the limitation of declaring a variable as the interface type as opposed to the class type that implemented the interface is that you only get access to what the interface (the contract) says should be there. The benefit though is that you can assign to this variable any class type that implements the interface.

How do I access Core Data Attribute validation information from code?

I have a string attribute in a Core Data entity whose Max Length value is 40. I'd like to use this value in code and not have to re-type the value "40." Is this possible?
As #K.Steff says in the comments above, you are better off validating in your code and not setting a max length in your core data model. To add on to that comment, I would also advise you to look at using a custom NSManagedObject subclass for this entity type, and within that subclass overriding the validateValue:forKey:error: or implementing a key-specific validation method for this property.
The value of this approach is that you can do things like "coerce" the validation by truncating strings at validation time. From the NSManagedObject documentation:
This method is responsible for two things: coercing the value into an appropriate
type for the object, and validating it according to the object’s rules.
The default implementation provided by NSManagedObject consults the object’s entity
description to coerce the value and to check for basic errors, such as a null value when
that isn’t allowed and the length of strings when a field width is specified for the
attribute. It then searches for a method of the form validate< Key >:error: and invokes it
if it exists.
You can implement methods of the form validate< Key >:error: to perform validation that is
not possible using the constraints available in the property description. If it finds an
unacceptable value, your validation method should return NO and in error an NSError object
that describes the problem. For more details, see “Model Object Validation”. For
inter-property validation (to check for combinations of values that are invalid), see
validateForUpdate: and related methods.
So you can implement this method to both validate that the string is not too long and, if necessary, truncate it when it is too long.
From NSManagedObject you can access the NSEntityDescription via entity. In there you can grab the array properties and a dictionary propertiesByName, either of which will get you to NSPropertyDescriptions. Each property description has a property, validationPredicates that will return an array of NSPredicates. One of those will be the condition that your string length must be at most 40.
Sadly predicates are a lot of hassle to reverse engineer — and doing so can even be impossible, given that you can create one by supplying a block. Hopefully though you'll just have an NSComparisonPredicate or be able to get to one by tree walking downward from an NSCompoundPredicate or an NSExpression.
From the comparison predicate you'll be able to spot from the left and right expressions that one is string length and the other is a constant value.
So, in summary:
Core Data exposes validation criteria only via the very general means of predicates;
you can usually, but not always, rebuild an expression (in the natural language sense rather than the NSExpression sense) from a predicate; and
if you know specifically you're just looking for a length comparison somewhere then you can simplify that further into a tree walk for comparison predicates that involve the length.
It's definitely not going to be pretty because of the mismatch of the specific and the general but it is possible.

Shared Domain Logic?

Take for example:
CreateOrderTicket(ByVal items As List(Of OrderItems)) As String
Where would you put this sort of logic given:
CreateOrder should generate a simple list ( i.e. Item Name - Item Price )
PizzaOrderItem
SaladBarOrderItem
BarOrderItem
Would you recommend:
Refactoring common to an abstract class/interface with shared properties a method called CreateOrderTicket
Or,
Creating a common service that exposes a CreateOrderTicket
We obviously would not want three createOrderTicket methods, but adding methods, inheriting, overloading and using generics seem like a high cost just to abstract one behaviour..
Assume for the sake of a simple example that (currently) there is no OrderItem baseclass or interface..
Help!! :)
p.s. Is there a way to overload without forcing all inheriting objects to use the same name?
Abstract base class sounds like the best option in this situation. Of course it all depends on what kind of shared behaviour these items have. Without knowing more, I'd guess all of these order items have Name and Price for example - and in future you might add more common stuff.
Without a shared base class which contains the Name and Price properties, you'll probably have troubles implementing a CreateOrderTicket method which takes a list containing more than 1 kind of orders.
Also I don't think inheriting from an abstract base class would be that high cost as technically the objects already derive from the Object base class. (Though I don't think this is completely equal to a custom base class.)
VB.Net can implement methods from an interface using a different name than the one specified in the interface but don't think the same goes for overriding abstract functionality.

Resources