Relevant link
Github solution: exercism-solutions/authentication-system
Exercism #41: C# exercises on Exercism
Learning Goal
Constants, Defensive Copying, Readonly Collections
Relevant Information
Constant
The const modifier can be (and generally should be) applied to any field where its value is known at compile time and will not change during the lifetime of the program.
Use const when:
- The value will never change
- It’s universal truth(e.g., Pi, conversion factors, fixed strings)
Readonly
The readonly modifier can be (and generally should be) applied to any field that cannot be made const where its value will not change during the lifetime of the program and is either set by an inline initializer or during instantiation (by the constructor or a method called by the constructor
Use readonly when:
- The value should not change after the object is created, but you need flexibility to compute or pass it in at runtime.
Defensive copying
In security sensitive situations (or even simply on a large codebase where developers have different priorities and agendas) you should avoid allowing a class’s public API to be circumvented by accepting and storing a method’s mutable parameters or by exposing a mutable member of a class through a return value or as an out parameter.
Readonly Collections
While the read-only modifier prevents the value or reference in a field from being overwritten, it offers no protection for the members of a reference type.
To ensure all members of a reference type are protected the fields can be made read-only and automatic properties can be defined without a set accessor.
The base class library (BCL) provides some read-only versions of collections where there is a requirement to stop members of a collections being updated. These comes in the form of wrappers:
- ReadOnlyDictionary<T> expose a Dictionary<T> as read-only.
- ReadOnlyCollection<T> exposes a List<T> as read-only.
Task # 1: Set appropriate fields and properties to const
In the authenticator class I changed all fields of the EyeColor class to const.
The properties of Authenticator class and Identity struct have set accessor so impossible to make them const.
Task #2: Set appropriate fields to read-only
Note: The read-only keyword cannot be used for properties in C#.
I made the admin variable of type identity read-only but ended up with an error in the Admin property.
Task 3: Ensure that the class cannot be changed once it has been created
I corrected the earlier method by removing the set accessor of the Admin property, by that making it read-only.
Task 4: Ensure that the admin cannot be tampered with
I returned a defensive copy of identity in the getter to prevent callers from modifying the internal admin instance.
Task 5: Ensure that the developers cannot be tampered with
I returned a defensive copy in the GetDeveloppers method to prevent external code to clear, add, or overwrite entries.
Share your thoughts about this exercise with me in the comment section.
