Rule # 1
Classes should always override the ToString() method. Objects should have a way to be represented as strings.
.NET calls the method whenever it needs to display object as string.
Rule # 2
Use constructors to guarantee initialization.
Bad Design
Customer cust = new Customer();
Cust.FirstName = "Sachin";
Cust.LastName = "Surana";
People who want to use Customer object need to be worried about how many fields are there, do I fill them all ? Very error prone way to do things.
Good Design
Force to supply values.
Customer cust = new Customer("Sachin", "Surana");
Rule # 3
In case of overloading, have one central contructor or central method. The other methods call the central method.
Rule # 4
If a class has static fields, guarantee initialization using static constructors.
Rule # 5
Declare constants as read-only fields.
i. It helps to define constant without embedding it within clients.
ii. You can initialise it using run-time constructor.
public class Globals {
public static readonly string AppHomeDir
Rule # 6
Use enum to define a set of related constants.
2. Consider
Rule # 7
All fileds should be private. Consider hiding data from unwarranted access. If access is needed, provide using properties.
Rule # 8
Consider overriding Equals(object obj)
.NET calls this method when searching.
Rule # 9
If override Equals, also override GetHashCode
1. Used internally by hashing algorithms.
2. If two objects are Equal, GHS they must return same value.
3. Define GHC in terms of same fields as Equals.
Rule # 10
Define Dispose() if your objects need cleanup.
Rule # 11
If class needs Dispose(), you should also need finalizer.
Rule # 12
Consider supplying a method for cloning objects. Use IClonable interface.
public class Customer : IClonable{
public object Clone(){
return new Customer("Sachin", "Surana");
}
}
Which is equivalent to
public class Customer : IClonable{
public object Clone(){
return this.MemberwiseClone(); // Creates a shallow copy
}
}
Since it is confusing if Clone uses shallow or deep copy, IClonable is deprecated.
public class Customer {
public Customer ShallowCopy()..
public Customer DeepCopy()...
}
3. Best Practices
Rule # 13
Throw exceptions. Do not return integer error code or bool.
No comments:
Post a Comment