When to prefer value semantics

When should you design a type to support value semantics?

While they are convenient, whether they’re appropriate depends on what the type is supposed to model.

Value semantics are good for representing inert, descriptive data. For example: numbers; strings; physical quantities like angle, length, and color; mathematical objects like vectors and matrices; pure binary data; collections of such values; and finally, large rich structures made from such values, like media.

Reference semantics are good for representing distinct items in your program or in the world. For example: constructs within your program such as specific buttons or memory buffers; an object which plays a specific role in coordinating certain other objects; or a particular person or physical object in the real world.

The underlying logic here is that the referenceable items are all objects, meaning they all have a distinct identity. Two people could be alike in all physical attributes, but they are still distinct people. Two buffers could hold equal byte patterns, but they are still distinct buffers.

But the items on the value semantics list are all values. They lack identity, so it is meaningless to talk about two things being equal but distinct. If we agree x equals five, there is no further question about which five it equals. Five is five.

A common pattern is to see a model type like Person defined as a reference type to reflect that it is an object with identity, while it is loaded with various value properties like age, hairColor, and so on, which describe that object.

When a program must represent many distinct items (like Persons), or when different parts of a program need to coordinate around the same item (like the UIApplication itself), reference types are the natural tool for representing those items

Reference types are used throughout UIKit because one of the main things running application code needs to refer to is other pieces of code. So you have UIView which describes a view on screen, UIScreen for the screen, NSNotificationCenter for objects providing framework services, and so on.

results matching ""

    No results matching ""