Values, Data, Objects

The classes and structs we create can be considered one of three categories: Values, data and objects.

Values

Don’t just give your numbers a good name and assume that prevents you from mixing them up. You’re a programmer. When you’re reasoning how to make 2 algorithms work nicely with 7 business rules, you don’t want to trip over something as stupid as having added a temperature to a weight in kilogram – so just create a struct to encapsulate it!

You also prevent conversion errors this way. Don’t create LengthInMeter – create Length, make the constructor private and only allow it to be created by specifying the unit you’re creating it with. Now adding Meters to centimeters can never go wrong again.

This sounds like so much more work than it actually is, because it makes you think of how often you use primitive values in your code. As soon as you go over your code however, you will notice that they all fall into a small handful of categories. This number is also logarithmic to the project size – where a small 300 lines of code console app might already have 4 different types of values, a 10K lines of code project might very well not need more than 15. Plus, once you got e.g. the first int value done, you can just copy-paste and reuse that for other int values.

Data

Data is the next higher-level construct. Data is encapsulated into data holders, which are is made up of values and other data holders.

Data holders do not have an identity. That means if I have a data holder
Employee with name, age and address and I create two of them with the same data “Tom Scott, 31, Alleystreet 123”, then those two are the same thing. Because of that, they can be encapsulated as structs, but because structs tend to surprise programmers, it is advised to use classes with overridden equality operators.

Objects

Objects are, again, the next higher-level construct. The combine data and behavior.

In general, the data “belongs” to the object, which does not allow others to change it. Working with the encapsulated data happens through methods.

That makes an object “something that does something”, which in turn causes objects to often have names that end in “-er” or “-or”, like Serializer, Presenter or WebConnector.

Next Article: Constructors don’t do work