Monday, April 13, 2009

To "I" or not to "I"

I read about this in Agile Principles, Patterns, and Practices in C#, the author - Robert Martin says that if you use the "I" prefix for interfaces then you might run into problem if you later decide to change the interface to an abstract class.

In which case you cannot continue to use the "I" prefix name, so you will have to rename it wherever you have referenced it - so, you should not use the prefix.

Microsoft seems to have ignored this issue, they want a interface/class pair to be distinguished but the letter "I" for the interface : http://msdn.microsoft.com/en-us/library/ms229040.aspx

Wednesday, April 08, 2009

C# Properties

There are 2 types of properties :
  1. parameterless - normal properties
  2. parameterful - indexers
Why use properties ? coz working with fields breaks data encapsulation/corrupt data.

Why should we excapsulate access to field?
  1. execute some side effect
  2. cache some value
  3. lazily create some internal object
  4. access in thread safe way
  5. return value which needs to be calculated on fly
To achieve this you may use a method that wraps the field - accessor methods.
But there are some disadvantages with this :
you have to write a method and users have to call that method.

Another way is to use properties : they can be static, instance, abstract, virtual, with any access specifier, with an interface, however they cannot be overloaded and they cannot have void return type

Properties compile down to methods.

Why not to use Properties :
Because as against fields they break the following assumptions:
  1. fields are always read and write, not properties
  2. fields never throw exception
  3. fields can be passed as out or ref
  4. field access completes immediately
  5. field always return same value
  6. field never has side-effects
  7. field always works on original object.
Compiler might inline property.
Cannot have static indexers