Coding Tip 2 – Fields Change

wpid-wpid-bulb-2007-11-19-12-49-2007-11-19-12-49.jpgTip 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.

Example:

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
static DateTime privateField = DateTime.Now;
//Correct because it is a private field.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s