Dependency on External Variables

Problem
You want to know how to best handle dependencies on external variables.

Answer
In general, the code inside a type should not reference any external variables. Apply this rule to global variables in a class or static fields or properties exposed by another type. Assign any value that a type needs to the type’s properties or pass them as arguments to its constructors or methods.

Comments
Why should you follow this rule? You should follow this rule because self-containment is the key to code reuse. If a type doesn’t depend on other types, then you can reuse the component in a different project with few or no side effects. By following this rule, it’s not possible to assign an invalid value to an external variable. Thus, the code in a type can’t break by accident or on purpose. Sometimes, you may want to relax this rule. This may be the case when you have complex object hierarchies. For example, you may have a class that contains all config settings for an assembly. In this scenario, the types may read values from static fields in the configuration class. If you can’t relax the rule, implement external values as properties instead of fields. This way, you can validate them and ensure they are never invalid. When a few (2-3) types depend on one another, mitigate this rule by storing them all in the same source file.

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s