- Clean Code in C#
- Jason Alls
- 248字
- 2021-06-18 18:28:11
Data structures should expose data and have no methods
Structures differ from classes in that they use value equality in place of reference equality. Other than that, there is not much difference between a struct and a class.
There is a debate as to whether a data structure should make the variables public or hide them behind get and set properties. It is purely down to you which you choose, but personally I always think it best to hide data even in structs and only provide access via properties and methods. There is one caveat in terms of having clean data structures that are safe, and that is that once created, structs should not allow themselves to be mutated by methods and get properties. The reason for this is that changes to temporary data structures will be discarded.
Let's now look at a simple data structure example.
An example of data structure
The following code is a simple data structure:
namespace CH3.Encapsulation
{
public struct Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Person(int id, string firstName, string lastName)
{
Id = id;
FirstName = firstName;
LastName = lastName;
}
}
}
As you can see, the data structure is not that much different from a class in that it has a constructor and properties.
With this, we come to the end of the chapter and will now review what we've learned.
- INSTANT Mock Testing with PowerMock
- Git Version Control Cookbook
- Xcode 7 Essentials(Second Edition)
- MongoDB for Java Developers
- Scala Design Patterns
- 正則表達式經典實例(第2版)
- Learning FuelPHP for Effective PHP Development
- Learning Laravel's Eloquent
- CoffeeScript Application Development Cookbook
- TMS320LF240x芯片原理、設計及應用
- SwiftUI極簡開發
- 數據科學中的實用統計學(第2版)
- Elasticsearch Blueprints
- Android高級開發實戰:UI、NDK與安全
- Mastering PowerCLI