When to use a class versus a struct

Now that you know the differences and similarities between a class and a struct, you may be wondering “How do I know which to use?”

Values vs. objects

While there are no hard and fast rules, one strategy is to think about value versus reference semantics and use structures as values and classes as objects. An object is an instance of a reference type. Such instances have identity. This means that every object is unique and no two objects are considered equal just because they hold the same state. This is why you had to use === to see if objects are truly equal and not just containing the same state. This is in contrast to instances of value types, which are values and are by definition considered equal if they are the same value.

For example: A delivery range is a value and should be implemented as a struct, while a student is an object and should be implemented as a class. No two students should be considered equal just because they have the same name!

Speed

Speed considerations may also come into play, as structs rely on the (faster) stack while classes rely on the (slower) heap. If you will have many instances of a type created (hundreds to many thousands), or if these instances will only exist in memory for a very short time, then you should generally lean towards using a struct. If your instance will have a longer lifecycle in memory, or if you will create relatively few instances, then creating class instances on the heap generally won’t create much overhead.

For instance, you may want to use a struct to calculate the total distance of a running route using many GPS-based waypoints, like the Location struct you used in Chapter 11. Not only will you create many waypoints, but they will also be created and destroyed quickly as you modify the route.

Conversely, you could use a class for an object to store route history as you’ll only have one object for each user, and you would likely use the same history object for the lifetime of the user.

Minimalist approach

Another approach is to use only what you need. If your data will never change or you need a simple data store, then use structures. If you need to update your data and you need it to contain logic to update its own state, then use classes. Often, it’s best to begin with a struct. If later you need the added capabilities of a class, then convert the struct to a class.

Structures vs. classes recap

Let’s review the attributes of structs and classes:

Structures

  • Useful for representing values
  • Implicit copying of values
  • Data is immutable
  • Fast memory allocation (stack)

Classes

  • Useful for representing objects
  • Implicit sharing of objects
  • Data is mutable
  • Slower memory allocation (heap)

results matching ""

    No results matching ""