Is it allowed to modify value of the Value Object on construction - domain-driven-design

Assuming that I want that following Value Object contains always capitalized String value. Is it eligible to do it like this with toUpperCase() in constructor?
class CapitalizedId(value: String) {
val value: String = value.toUpperCase()
// getters
// equals and hashCode
}

In general, I do not see a problem of performing such a simple transformation in a value object's constructor. There should of course be no surprises for the user of a constructor but as the name CapitalizedId already tells you that whatever will be created will be capitalized there is no surprise, from my point of view. I also perform validity checks in constructors to ensure business invariants are adhered.
If you are worried to not perform operations in a constructor or if the operations and validations become too complex you can always provide factory methods instead (or in Kotlin using companion, I guess, not a Kotlin expert) containing all the heavy lifting (think of LocalDateTime.of()) and validation logic and use it somehow like this:
CapitalizedId.of("abc5464g");
Note: when implementing a factory method the constructor should be made private in such cases

Is it eligible to do it like this with toUpperCase() in constructor?
Yes, in the sense that what you end up with is still an expression of the ValueObject pattern.
It's not consistent with the idea that initializers should initialize, and not also include other responsibilities. See Misko Hevery 2008.
Will this specific implementation be an expensive mistake? Probably not

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.

Strategies for mutation operations of immutable value objects

According to DDD principles, it's often advised that value objects be used to encode values which don't have a life cycle of their own, but are merely values. By design, such objects are made immutable. They often replace primitives, which makes the code more semantic and error-safe.
The rationale is very sensible, but sometimes it leads to some cumbersome operations. For example, consider the case where an address is encoded as a value object along the lines of:
class Address extends ValueObject {
public Address(String line1, String line2, String postalCode, String String country) {
...
}
...
}
In an application, it wouldn't be unusual for a user to change only one field of an address. In order to achieve that in code, one would have to do something like:
String newCity = ...;
Address newAddress = new Address(
oldAddress.getLine1(),
oldAddress.getLine2(),
oldAddress.getPostalCode(),
newCity,
oldAddress.getCountry());
This could lead to some very repetitive and overly verbose code. What are some good strategies for avoiding this, while keeping immutable value objects?
My own ideas:
Private setters, which could enable helper methods like this:
public Address byChangingPostalCode(String newPostalCode) {
Address newAddress = this.copy();
newAddress.setPostalCode(newPostalCode);
return newAdress;
}
A downside is that the object now isn't immutable anymore, but as long as that's kept private, it shouldn't be a problem, right…?
Make the value object a full-fledged entity instead. After all, the need for fields to be modified over a longer time indicates that it does have a life cycle. I'm not convinced by this though, as the question regards developer convenience rather than domain design.
I'll happily receive your suggestions!
UPDATE
Thanks for your suggestions! I'll go with private setters and corrective methods.
There's nothing wrong with having immutable values return other immutable values.
Address newAddress = oldAddress.correctPostalCode(...);
This is my preferred approach within the domain model.
Another possibility is to use a builder
Address new Address = AddressBuilder.from(oldAddress)
.withPostalCode(...)
.build()
I don't like that one as much, because build isn't really part of the ubiquitous language. It's a construction I'm more likely to use in a unit test, where I need a whole address to talk to the API but the test itself only depends on a subset of the details.
Private setters, which could enable helper methods like this:
This is my preferred solution for changing a Value object. The naming of the method should be from the ubiquitous language but this can be combined to a team/programming language convention. In PHP there is a known convention: immutable command method names start with the word "with". For example withCorrectedName($newName).
The object must not be fully constant but only act as such in order to be considered immutable.
Make the value object a full-fledged entity instead. 
It wouldn't be a ValueObject anymore, so don't!
I would solve this with derive methods:
Address newAddress = oldAddress.derive( newPostalCode);
Address newAddress = oldAddress.derive( newLine1 );
And so on...

Domain Driven Design; Can ValueObject contains invariants or specifications?

I'm starting to play with Domain Driven Design and have a question about ValueObjects :
Can they contains invariants or other specifications ?
Consider an immutable ValueObject :
ValueObject (
prop integer: Int
prop string: String
// Value and copy constructor
// Observers for integer and string
// Equality methods on integer and string value
)
Can I add some invariants such that integer > 0 & < 42. Or do they have to be simple transfer without any logic ?
I hope they can but need a confirmation.
A value object (VO) encapsulates a value and its business requirements . This is its purpose: to model a business concept (with its constraints) which happens to be a simple (not always single) value.
A VO is not a Data transfer object (DTO) precisely because it defines a business concept that is valid only in the containing bounded context, while a DTO is meant to cross boundaries.
Value objects should handle the invariants for the data that they encapsulate, or at least as much of it as they can. I tend to do the following, which is actually similar to entities except for the immutable bit:
Constructors should make sure it is created in a valid state
The VO's state is encapsulated, and all changes to it are done through controlled methods/etc
Because value objects are immutable, method changes return a new value object rather than updating the existing state
Having the value objects own their own business logic really helps clean up the code in the entities that use these value objects. This can become a problem with big aggregates\entities, so look for opportunities to pull this behavior out into value objects.
It also makes unit testing lots of edge cases MUCH easier, as you are testing the value object on its own.
Your entity may need to do validation across multiple value objects before decides a change CAN happen, but then the value object is responsible for the change itself.

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.

Resources