Sunday, May 26, 2013

C# - Value type Vs Reference Type.

While writing a usual code in day-to-day development, we often avoid the minute details (plus and minus) between the two categories of an entity in C#.

Recently read about the subtleties included in the two types and some of the compelling reasons to compare the two options before creating a new entity. Most often we adhere to creating a Reference type (Class) thinking it to be scalable, performant (What is GC for?).

Post reading "Effective C# Programming", thought to document the details and to pay more attention in order to create the right type for my needs.

Why Value type?
1) Are created on Stack, does not involve GC.
2) Value types are copied when returned from a method or property. There is no danger of exposing internal structure (internals of an object).

Why not a Value type, always?
1) Limited support for OOPs! Remember, no inheritance, no polymorphism works here. Consider all as if they were sealed.
2) If backed by interface, would cost boxing.
3) Can not define a parameter less contructor (just to mention a limitation).
4) Since, passed by value, the whole object gets copied. Thus, not suggested to have a big value type.
5) Best suited to be Immutable only. There would be complication if not immutable, any user code may try to modify it but since copies are passed, the behaviour will not be right.
Why not a Reference type, always?
1) It involves heap allocation, and that too not inline. Which means there would be separate allocations (even if I am storing those objects in an array) for each object, which would eventually cause heap fragmentation, more garbage, more indirection (in terms of dereferencing).

Suggested rule of thumb:
You create value type, if
1) Type is only for data storage,
2) Public interface defined entirely by properties.
3) This type will never have subclasses.
4) This type will never be treated polymorphically.
As a side note (on comparison).
- Reference types default to null.
- Value types default to all 0s.
- Nullable is again a value type (struct) which allows storing null. It would be interesting to find out the implementation behind.

Saturday, May 18, 2013

C# Programming - Are you making use of basic features?

It takes me by surprise to realize that peer developers (.net,C#) are writing code but not making use of some of the native/simple features that could help in writing better (re-usable, maintainable, readable, and sometimes performing ) code!!

For instance, when was the last time you have seen (or written) an operator overloading in a custom class? A class written with private access modifier? Use of native attributes like Conditional, Flags ?

It's not necessary that a code written without making use of these features is bad, but then these features exists for some good reasons! I am stating below some of such features that I have been using and "miss" while reviewing others code. I am sure you will find scenarios in your existing code where you could use these features for good reasons.


1. implicit/explicit type casting operator.
I find it really useful for POCO scenario where I don't want the users to write scattered code to create a related type from instance of my class.

2. Conditional attribute.
I find it really useful to write a helper method that only stays in DEBUG code base (and hence is not deployed to production). It gives me assurance that the code would still be good without my method and the extra functionality would do the right thing while working in a DEBUG mode.

3. Private class.
I find it really useful to wrap the internal data structure for a utility code or for a business logic in a private class. Assuring that there won't be any external dependencies on my private class and I can alter this class any time. Plus, it keeps the encapsulation logic intact.

4. Resharper
If your company doesn't has licence, then you don't have a choice. But, if you have - then you "must" learn the basic shortcuts and enable them. It's really disappointing to work with a peer on a code review and get to notice that, instead of having it installed/licensed, it's not being used at all.

5. Explicit implementation of interface.
I have only heard of this term when it comes to interviews. It is a good flexibility available while dealing with interfaces. I use this implementation when I want to make sure that all my users are only working on the underlying interface. There are various good reasons to not distribute concrete implementation in an API, and this feature makes it more controlled.

6. Int32.TryParse
I hate to see a Int32.Parse(xx) code! and I see it every now and then. This one avoids the exception and is there for a good reasons. Note: Even if the parsing is mandatory I would like to use TryParse and throw user friendly exception if the parsing fails. Invalid case exception is annoying and doesn't leaves any business reasoning behind.

7. ToString()
I am also bad at this one! But it's such a pleasure to see object details while in debug mode. Especially when the details are will thought of, as in ToString with IFormatable and only provide basic details in default format.

8. Immutable classes
Damn the feature of auto-implemented properties... I always see peers using those properties without considering the existence of a field at all (I know, we can create auto-property with private get but that doesn't leaves the underlying field as readonly). There are real good reasons to write immutable classes (most selling one is when your class acts as a key). In my case, I even prefer to write a simple POCO as a immutable (if possible) class. It's such a delight to watch a class with all readonly fields, a contructor/factory to create a full instance, and then a set of getter properties.


Saturday, May 4, 2013

Unit Testing, the gherkin way.

Importance of unit test - not going to cover in this discussion.

The article is primarily focused on importance of structuring a unit test.

In my 4 years of unit testing experience the biggest challenge I have faced is in terms of writing an "almost" production quality unit tests. It gets important because the structure and quality of unit test derives how far the unit tests would be maintained!

Historically, I have been naming a unit test method by describing the logic that uni test is going to assert. That helped, but then the test was not just doing assertion... the method was also responsible for all three A's (AAA) Arrange-Act-Assert. Which kind of resulted in coupling and went against the DRY principle. We always need the same Arrange-Act across different unit tests, which was repetitive.

Found the following simple approach to arrange unit test in one of the Pluralsight videos:


public abstract class GivenWhenThen{
      [SetUp]
      public void Init(){
             Given();
             When();
    }

    public abstract void Given();

    public virtual void When(){}
}

Then, I use the following protocol to structure my tests:
Given = Namespace
When = Class
Then = Test method.

using Given_Order_Service{
//Sample Implementation:
public class When_an_empty_order_is_placed{
            private IOrderService _orderService;
            public override void Given(){
                      _orderService = new OrderService():
            }

            public override void When(){
                     _orderService.PlaceOrder(null);
            }
         
           [Test]
           [ExpectedException(typeof(EmptyBasketException)]
           public void Then_Exception_Is_thrown_with_Empty_basket_message(){
                    //assertion..
          }

      }
}