Defining Fields appropriately - Backing Fields

Fields hold the data in our application, so defining fields appropriately helps ensure that data is
correctly identified and retained.

Fields can by variable or Constance, read-only or write-only, public or private, built in or types define by the classes we write.

Backing Fields

Variable in a class

Becking fields are the most common types of fields that we use in our class.

Holds data for each object

A backing field is simply a variable in a class that holds the data for each object we instantiate from that class.

Data Encapsulation/ Information Hiding

Because much of the data for our application, including
company proprietary and operational data are stored in beaking fields, one best practice is to follow the principle of data encapsulation, also known as information hiding.

The principle of data encapsulation specifies that an object's
data should be accessible only to that object.
so the backing fields that hold that data are private.
the data is accessible outside of the class only through property getter and setters.

 private string description;
 private int productId;
 private string productname;
 private vandor productVendor;

Here are the backing fields for the product 
  • description
  • id
  • name
  • the vendor that supplies the product

Accessibility Modifier

Each backing field has an optional accessibility modifier.
as per the principle of data encapsulation, the accessibility modifier on backing fields is normally private.

Data Type

Next is the data type which can be a built-in .net type such as int, string, or it can be a custom class defined by a class such as a vendor type.

Name

After the data type is the field name.
the field case is normally camelCase with the first letter of the name in lowercase, and each appended word capitalized.

Optional initialization

optionally we can initialize the value of the field in the declaration.


Backing Field Best Practices

Do:  

Naming 
  • Define a meaningful name
  • use camelcasing
Keep fields private
use properties to provide access to the fields 

Avoid

Naming 
  • Single character name 
  • Abbreviations
Initializing to the field's default value

Comments

Popular posts from this blog

Constant vs Read-Only

Constants

FAQ: