Working with fields which can mutate or be new instances altogether
Structs are usually used for immutable data, eg a phone number, which does not mutate, but instead you get a new one (eg the number 000 becoming 0001 would mean two seperate numbers).
However, pieces of information like Name, a string, can either mutate (company abc changing its name to abcdef, or being given a new name like def). For fields like this, I assume they should reside in the mutable class and not an immutable structure?
My way of structuring code is to have an immutable concept, like Address (any change is a new address completely), in a struct and then reference it from a class like Customer, since Customer always has an address. So I would put CompanyName, or Employer, in the class as it is mutable. But a name can either mutate and so be the same 1 instance, or a new name setup and while the company still owning the first name too.
Would the correct pattern for assigning a new instance (eg a new company name but the old name still owned by the company) be?:
string name = "";
string newName = new string();
newName = "new";
name = newName;
A开发者_运维技巧nd a mutation just the standard assignment pattern?
Thanks
I would not worry about mutability/immutability on this level. Just write your code to be straight forward.
One thing about your code sample:
string newName = new string();
newName = "new";
The above code will create two different string instances; first an empty string will be assigned to newName
, then a new string ("new"
), will be assigned. Most likely the assignment of the empty string instance will be optimized away since it is clearly never used. Just assign the string where it should be:
string name = "new";
精彩评论