Should the implementation of value object be sealed? - oop

Following DDD practices, should the implementation of value object be sealed?
Imagine having some abstract ValueObject<T> and the concrete implementation given as Money : ValueObject<Money>. Should I seal Money?
public class Money : ValueObject<Money>
{
private Money()
{
}
private Money(decimal value, string currency)
{
Requires.NotEmpty(currency, nameof(currency));
Requires.That(value >= 0, $"{nameof(value)} must be greater or equals to 0.");
Value = value;
Currency = currency.ToUpper();
}
public decimal Value { get; private set; }
/// <summary>
/// ISO 4217 currency code
/// </summary>
public string Currency { get; private set; }
public static Money Dkk(decimal value) => new Money(value, "DKK");
public static Money Usd(decimal value) => new Money(value, "USD");
}

Generally it's best practices to avoid polymorphism due to the composition over inheritance advice. In the DDD context there are some cases where it's useful to allow future polymorphism but this usually includes entities.
Value object per definition should be immutable and to avoid further misuse, seal it.
Useful link: http://thepaulrayner.com/value-objects-and-immutability/

To me, Value Object vs other type of object makes little difference when considering sealing. Countless arguments have been made both for and against it over the years with complex enough considerations that you don't want to add another variable to the equation.
I can hardly see all VO's in a domain model being sealed but all other classes not sealed. If you're going to seal, it will primarily be for a whole different range of reasons (organizational, performance) that don't have much to do with the type of object in the DDD nomenclature.

Related

How to easily access widely different subsets of fields of related objects/DB tables?

Imagine we have a number of related objects (equivalently DB tables), for example:
public class Person {
private String name;
private Date birthday;
private int height;
private Job job;
private House house;
..
}
public class Job {
private String company;
private int salary;
..
}
public class House {
private Address address;
private int age;
private int numRooms;
..
}
public class Address {
private String town;
private String street;
..
}
How to best design a system for easily defining and accessing widely varying subsets of data on these objects/tables? Design patterns, pros and cons, are very welcome. I'm using Java, but this is a more general problem.
For example, I want to easily say:
I'd like some object with (Person.name, Person.height, Job.company, Address.street)
I'd like some object with (Job.company, House.numRooms, Address.town)
Etc.
Other assumptions:
We can assume that we're always getting a known structure of objects on the input, e.g. a Person with its Job, House, and Address.
The resulting object doesn't necessarily need to know the names of the fields it was constructed from, i.e. for subset defined as (Person.name, Person.height, Job.company, Address.street) it can be the array of Objects {"Joe Doe", 180, "ACompany Inc.", "Main Street"}.
The object/table hierarchy is complex, so there are hundreds of data fields.
There may be hundreds of subsets that need to be defined.
A minority of fields to obtain may be computed from actual fields, e.g. I may want to get a person's age, computed as (now().getYear() - Person.birtday.getYear()).
Here are some options I see:
A SQL view for each subset.
Minuses:
They will be almost the same for similar subsets. This is OK just for field names, but not great for the joins part, which could ideally be refactored out to a common place.
Less testable than a solution in code.
Using a DTO assembler, e.g. http://www.genericdtoassembler.org/
This could be used to flatten the complex structure of input objects into a single DTO.
Minuses:
I'm not sure how I'd then proceed to easily define subsets of fields on this DTO. Perhaps if I could somehow set the ones irrelevant to the current subset to null? Not sure how.
Not sure if I can do computed fields easily in this way.
A custom mapper I came up with.
Relevant code:
// The enum has a value for each field in the Person objects hierarchy
// that we may be interested in.
public enum DataField {
PERSON_NAME(new PersonNameExtractor()),
..
PERSON_AGE(new PersonAgeExtractor()),
..
COMPANY(new CompanyExtractor()),
..
}
// This is the container for field-value pairs from a given instance of
// the object hierarchy.
public class Vector {
private Map<DataField, Object> fields;
..
}
// Extractors know how to get the value for a given DataField
// from the object hierarchy. There's one extractor per each field.
public interface Extractor<T> {
public T extract(Person person);
}
public class PersonNameExtractor implements Extractor<String> {
public String extract(Person person) {
return person.getName();
}
}
public class PersonAgeExtractor implements Extractor<Integer> {
public int extract(Person person) {
return now().getYear() - person.getBirthday().getYear();
}
}
public class CompanyExtractor implements Extractor<String> {
public String extract(Person person) {
return person.getJob().getCompany();
}
}
// Building the Vector using all the fields from the DataField enum
// and the extractors.
public class FullVectorBuilder {
public Vector buildVector(Person person) {
Vector vector = new Vector();
for (DataField field : DataField.values()) {
vector.addField(field, field.getExtractor().extract(person));
}
return vector;
}
}
// Definition of a subset of fields on the Vector.
public interface Selector {
public List<DataField> getFields();
}
public class SampleSubsetSelector implements Selector {
private List<DataField> fields = ImmutableList.of(PERSON_NAME, COMPANY);
...
}
// Finally, a builder for the subset Vector, choosing only
// fields pointed to by the selector.
public class SubsetVectorBuilder {
public Vector buildSubsetVector(Vector fullVector, Selector selector) {
Vector subsetVector = new Vector();
for (DataField field : selector.getFields()) {
subsetVector.addField(field, fullVector.getValue(field));
}
return subsetVector;
}
}
Minuses:
Need to create a tiny Extractor class for each of hundreds of data fields.
This is a custom solution that I came up with, seems to work and I like it, but I feel this problem must have been encountered and solved before, likely in a better way.. Has it?
Edit
Each object knows how to turn itself into a Map of fields, keyed on an enum of all fields.
E.g.
public enum DataField {
PERSON_NAME,
..
PERSON_AGE,
..
COMPANY,
..
}
public class Person {
private String name;
private Date birthday;
private int height;
private Job job;
private House house;
..
public Map<DataField, Object> toMap() {
return ImmutableMap
.add(DataField.PERSON_NAME, name)
.add(DataField.BIRTHDAY, birthday)
.add(DataField.HEIGHT, height)
.add(DataField.AGE, now().getYear() - birthday.getYear())
.build();
}
}
Then, I could build a Vector combining all the Maps, and select subsets from it like in 3.
Minuses:
Enum name clashes, e.g. if Job has an Address and House has an Address, then I want to be able to specify a subset taking street name of both. But how do I then define the toMap() method in the Address class?
No obvious place to put code doing computed fields requiring data from more than one object, e.g. physical distance from Address of House to Address of Company.
Many thanks!
Over in-memory object mapping in the application, I would favor database processing of the data for better performance. Views, or more elaborate OLAP/datawarehouse tooling could do the trick. If the calculated fields remain basic, as in "age = now - birth", I see nothing wrong with having that logic in the DB.
On the code side, given the large number of DTOs you have to deal with, you could use classless dynamic (available in some JVM languages) or JSON objects. The idea is that when a data structure changes, you only need to modify the DB and the UI, saving you the cost of changing a whole bunch of classes in between.

OOP creating and copying an object that depends on one value

I am sorry but I didn't know what to call this post (if you have a better title please tell me in a comment).
Say for instance you have the following Object whose purpose is to create chart series of the data specified in the Constructor:
/**
* Helper to generate chart series
*/
public class ChartHelper
{
public System.Windows.Forms.DataVisualization.Charting.Chart ChartType { get; set; }
public String TimeType { get; set; }
private readonly List<IObject> _datalist;
private readonly TimeType _timeType;
private readonly DateTime _stopDate;
private readonly DateTime _startDate;
public ChartHelper(List<IObject> dataList, TimeType timeType, DateTime startDate, DateTime stopDate)
{
_startDate = startDate;
_stopDate = stopDate;
_datalist = dataList;
_timeType = timeType;
}
public System.Windows.Forms.DataVisualization.Charting.Chart GetChart()
{
CreateSeries(_startDate);
return ChartType;
}
private void CreateSeries(DateTime seriesTime)
{
//Do something
}
//More internal private methods
}
Now say for instance you have a program that creates 10 different Charts but only the value of the List<IObject> dataList changes.
Then you could do one of two things:
Create 10 different ChartHelper Objects
Use the same Object and change the dataList value
This is of course an example of how the problem could be presented when developing (ive met this problem several times)
My question is, is there a design pattern that helps you solve this issue ? Or is there a best practice method that would be useful for these situations? It is important for me to learn these methods as I wish to improve my own skills.
If only the data is different then I would recommend using the same class and creating 10 different objects from it.
If however the implementation of the CreateSeries would be different depending on the type of data, than this would be a candidate for the Strategy pattern. In that case you would extract the creation of the series behind an interface and provide implementations for the different kinds of series. You could then also have a factory that picks the correct strategy depending on the data and composes a chart (helper).

WCF method that updates object passed in

Am I correct in thinking that if I have a WCF OperationContract takes in an object and needs to set a property on that object so the client gets the update, I need to declare it to return the object.
e.g. given a datacontract:
[DataContract]
public class CompositeType
{
[DataMember]
public int Key { get; set; }
[DataMember]
public string Something { get; set; }
}
this will not work with WCF:
public void GetDataUsingDataContract(CompositeType composite)
{
composite.Key = 42;
}
this will work:
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
composite.Key = 42;
return new CompositeType
{
Key = composite.Key,
Something = composite.Something
};
}
IMO, authoring methods that produce output via side-effects is a "bad" thing. Having said that however, are there circumstances that necessitate this model? Yes.
Certainly C# programming model permits this, is WCF broken? No. At a certain point, one must realise they are consuming WCF, and as a framework it attempts to satisfy a majority of use-cases [for instance, replicating all input parameters on all round trips to preserve implicit side effect semantics is, in a word, silly].
Of course, there are ways to work around this - C# also provides for explicit declaration of these scenarios and WCF supports these as well!
For instance
// use of "ref" indicates argument should be returned to
// caller, black-eye and all!
public void GetDataUsingDataContract (ref CompositeType composite)
{
composite.Key = 42;
}
Give it a go!
Hope this helps :)
If you use 'out of the box' WCF, you are actually using a form of webservices, that uses serialized versions of the objects that are sent from client to server.
This is the reason you cannot 'by reference' change properties on objects. You will always have to use a request / response pattern.

VS2010's "Public Property <PropertyName> As <DataType> vs. Public var

In VS2008, I used to type
Public Property <PropName> As <dataType>
and hit the Enter key and the IDE editor would automatically expand it out to a full blown property block.
Now, from what I understand, a new feature of 2010 is that the compiler automatically "expands" the short syntax above into the same IL code that you would get with the full property GET AND SET sub methods that were are accustomed to seeing before in the editor.
But functionality, how the heck is this any different than just having a Public class level variable? If the only diff is what it compiles to and if otehrwise there is no functional difference, isn't the new way less efficient than the old since it involves more code than just having a class level memory variable?
Public <Variable> as <DataType>
I thought that if you weren't going to have code behind your properties that they were essentially the same. I guess the diffrenece is that they just added the keyword "Property" but functionality, their is no diff, eh?
It makes little difference in this particular case, but I never use Public data members - anything that needs exposing outside the class is always done with properties. This means a little more work when declaring them, but when later on you wish that you had a property / accessor methods because you need to implement some code, it's a lot easier knowing that everywhere else in the code is already using your property...
Before someone pulls me up on this, no - it's not the same anyhow... You could manipulate a public member using a reference for instance...
This heavily ties into why properties are useful. They provide a level of isolation between the class implementation and the client code that uses it. When you use a public field, you cannot easily refactor the way the field behaves, the client code references it directly. Changing the field to a property for example requires recompiling all client code that uses it.
The usefulness of an automatic property is that it doesn't force you to decide up front that a field may need to be refactored some day. You can postpone the decision and change it from an automatic property to an explicit property with custom behavior any time you like. Without having to make any changes in the client code.
The JIT compiler ensures that an automatic property is just as efficient as a field, it inlines the accessor method call. The new automatic property syntax makes it just as efficient on your wrists as a public field. This is a complete win-win, it just doesn't make any sense anymore to ever use a public field again.
I am not sure, if I understand your question correctly.
But the need of a public class level variable vs property is already discussed here.
EDIT: Also, the IDE/Compiler makes it easy for you to reduce the code, if you are simply doing get/set
e.g.
public string Name { get; set; }, which doesn't require you to declare a backing field.
But then,you will have to access this member (even inside the class) using the property. Because, the compiler generates a backing field for you & the name of it is unknown.
One other difference is that properties are accessed from other controls such as DataGridView, that can read public property values but not variables.
The major difference between Auto-Implemented Properties (VB) and public Fields are interface definitions.
Codes that are using your class with Auto-Implemented Properties does not need to change if in the future you decide to add logic to the property, whereas if you're using fields you will have to modify the interface definition to a property.
So Auto-Implemented Properties uses the simple syntax of a public Field (without the full blown property declaration) but with the flexibility of a property.
A little bit of example:
Current code (C#):
class PersonA {
public int Age;
public int BirthYear;
}
class PersonB {
public int Age { get; set; }
public int BirthYear { get; set; }
}
Usage:
var john = new PersonA { Age = 30, BirthYear = 1980 };
var jane = new PersonB { Age = 20, BirthYear = 1990 };
If in the future you decide to scrap Age setter and derive the value from BirthYear, you can easily update your class without breaking any of the current client code.
class PersonA {
public int Age { get { return Date.Now.Year - BirthYear; }; set { } };
public int BirthYear;
}
class PersonB {
public int Age { get { return Date.Now.Year - BirthYear; }; set { } };
public int BirthYear { get; set; }
}
Usage:
var john = new PersonA { Age = 30, BirthYear = 1980 }; // broken when not recompiled
var jane = new PersonB { Age = 20, BirthYear = 1990 };

WCF DataContract serialization of read-only properties?

Whenever I use WCF, I always try to make immutable classes that end up going over the wire (i.e. parameters set in constructor, properties are read-only). However, this gets in the way of WCF serialization, which demands that all properties be Public get/set (which makes sense, because it has to deserialize them)
Even in this related post, I see that their solution ended up making everything Public, which violates my sense of good programming. Is there any way around this? Do I have to just settle for this solution or something like popsicle immutability and be happy with it?
The other thing I tried was something like this, where I'd have a base class for everything and a derived class that made the set useless:
/// <summary>
/// This represents a discovered virtual-machine template that can be
/// instantiated into a RunningVirtualMachine
/// </summary>
[DataContract]
[XmlRoot("VMTemplate")]
public class VirtualMachineTemplateBase
{
[DataMember]
public virtual ulong SizeInBytes { get; set; }
}
/// <summary>
/// This class is the real guts of VirtualMachineTemplate that we're hiding
/// from the base class.
/// </summary>
[XmlInclude(typeof(VirtualMachineTemplateBase))]
public class VirtualMachineTemplate : VirtualMachineTemplateBase, IXmlPicklable, IEnableLogger
{
ulong _SizeInBytes;
public override ulong SizeInBytes {
get { return _SizeInBytes; }
set { }
}
}
If you use the DataContractSerializer (which is the default for WCF), you can serialize anyhting that's decorated with the [DataMember] attribute - even a read-only field:
[DataContract]
public class VirtualMachineTemplate : VirtualMachineTemplateBase, IXmlPicklable, IEnableLogger
{
[DataMember]
ulong _SizeInBytes;
}
But you need to use the DataContractSerializer - not the XML serializer. The XML serializer can ONLY serialize public properties (and it will, unless you put a [XmlIgnore] on them).
The DataContractSerializer is different:
it doesn't need a parameter-less default constructor
it will only serialize what you explicitly mark with [DataMember]
but that can be anything - a field, a property, and of any visibility (private, protected, public)
it's a bit faster than XmlSerializer, but you don't get a lot of control over the shape of the XML - you only get a say in what's included
See this blog post and this blog post for a few more tips and tricks.
Marc
To ensure both immutability and easy implementation at the same time add a private setter for the property to serve deserialization. A lot happens under the bonnet, but it works.