Tip 2 – Non-constant fields should NOT be visible
Static fields that are neither constants nor read-only are not thread-safe. Access to such a field must be carefully controlled and requires advanced programming techniques for synchronizing access to the class object. Because these are difficult skills to learn and master, and testing such an object poses its own challenges, static fields are best used to store data that does not change. This rule applies to libraries; applications should not expose any fields.
Static fields that are neither constants nor read-only are not thread-safe. Access to such a field must be carefully controlled and requires advanced programming techniques for synchronizing access to the class object. Because these are difficult skills to learn and master, and testing such an object poses its own challenges, static fields are best used to store data that does not change. This rule applies to libraries; applications should not expose any fields.
Example:
WRONG: public static DateTime publicField = DateTime.Now;
//This is wrong because the field is public and not a literal
CORRECT:
WRONG: public static DateTime publicField = DateTime.Now;
//This is wrong because the field is public and not a literal
CORRECT:
public static readonly DateTime literalField = DateTime.Now;
//Correct because it is a literal read-only field
//Correct because it is a literal read-only field
static DateTime privateField = DateTime.Now;
//Correct because it is a private field.
1 comment:
Post a Comment