#520 – Choosing Between a struct and a Class
February 15, 2012 2 Comments
A struct and a class both encapsulate data and methods in a new type. When you are creating a new type, you’ll generally create a new class. But there are cases when a struct is the better choice.
Create a struct, rather than a class, when all of the following is true:
- You want value type semantics, that is–a variable of this type directly contains the data and a copy is made whenever you assign the value to a new variable or pass the variable to a method
- Data stored in the struct won’t be modified after an instance is created or does not change very often
- You don’t need to inherit from another type (a struct inherits only from System.ValueType)
- You need to store only a small amount of data in the type
While reading this, I also came across “Parameter Object” refactoring.
Here is a class example:
class DateRange {
DateRange (Date start, Date end) {
_start = start;
_end = end;
}
Date getStart() {
return _start;
}
Date getEnd() {
return _end;
}
private final Date _start;
private final Date _end;
boolean includes (Date arg) {
return (arg.equals(_start) ||
arg.equals(_end) ||
(arg.after(_start) && arg.before(_end)));
}
The code and the articles is from: http://sourcemaking.com/refactoring/introduce-parameter-object
I was wondering could this class be created as a Struct, and if that would be advantageous or not, with some explanation if possible.
Yes, probably a good candidate for a struct, rather than class, especially since the class is meant to be immutable.