Md. Adil Akhter's Weblogs

Me, My Thoughts and My Journey ....

April 2008 - Posts

Passing Parameter to a Predicate in .Net2.0

In this post, we will see how to pass parameter to a method representing Predicate.

Let's say, we have a collection of SprintBacklogItem and we want to filter all the SprintBacklogItem with Title start's with, let say "QA" or "Dev Task" depending on a input parameter. Now from the previous post we know that , predicate only have 1 parameter of type T.

image

Then, how to pass a input parameter _HeaderToSearch in Predicate?

1. To do that, we need to a new object called ListMatcher -

public class ListMatcher 
   { 
       private string _HeaderToSearch; 
       public ListMatcher(string headerToSearch) 
       { 
           _HeaderToSearch = headerToSearch; 
       }  

       public bool Predicate(SprintBacklogItem item) 
       { 
           return item.Title.StartsWith(_HeaderToSearch, StringComparison.InvariantCultureIgnoreCase); 
       }  

   }  


2. Next , I initialized the ListMatcher object and use the HeaderToSearch  to filter the items-

ListMatcher matcher = new ListMatcher("QA"); 
this.FindAll(matcher.Predicate);


Done.:)

Posted: Apr 18 2008, 04:34 PM by Adil Akhter | with 4 comment(s)
Filed under: ,
TDD - In a Nutshell
"One Picture's  Worth Thousands Words"

 image

 Benefits( from my personal experience):
1. Development can be done much quicker. You already jot down all the test cases before writing codes. By that way, you are giving much time in thinking how to solve problem. Codes become much more standard and organized because of the brainstorming.
2. Quality of code is far better and deterministic.
3. Tests are the first class document for how your code will eventually work. Any developer/tester can go through the test cases you covered and get the idea how the system should work in different cases. J Isn’t it too cool ?
4. Easier and risk free to change the code - you just need to run the tests, you will get to know where there might be some problem. 


And so on...

 

Why Unit Testing is so important?

Why writing unit tests are so important - lets consider a development team developing a module( call it - [A])did not consider the unit testing that seriously. What happens to that module -

1. [A] produced lot of Bugs in the development phase since it was not tested adequately. And while fixing it- [A] produced severe impact on other modules too because integration was failing again and again. So, the dependent module had to change as well to stabilize whole Delivery.

2. That's not the end of misery. In the release testing, huge amount of bugs identified which also produced from the uncertain behavior of [A]  and fixing those become a hell of a job for the developers. Just to show you one old basic diagram of software development life cycle -

image

3. After the deliverable delivered to the client - Developers could not take pride for that because they were not confident whether they delivered a Good Product( from a developers perspective, I think its really crucial to deliver something from which you can take pride).

4. [A] became more susceptible and fragile day by day. And developers become really reluctant and was not comfortable to change the codes for any change request because of the code's inherent fragility.

5. Refactoring become very error-prone and troublesome.

So, after some time - Developers started calling [A] as "Dead Zone" or Legacy Code because [A] become quite impossible to manage.

Now if we go back to the days when the developers were planing or starting the development process using our Time Traveler- what would you advise them?  :)

The situation that I just described,  its not new to most of the developers developing for a long time. That's why some intelligent people in agile world sit together and come up with some basic rules and practices that we must follow to make our product worth taking pride. One of them is writing Unit Tests for your codes considering all the test criteria considering -

1. Unit Tests are the first users of your Unit who ensure that your own Creation  is working that way you wanted to. Remember - "Taking pride". It become much easier to achieve.In addition, Learning Curve become much higher -because, you get to know very explicitly what are the cases you missed while writing unit tests initially that produce bugs. That way it makes you much mature developer day by day.

2. Unit Tests are the living description how the Unit should work. Any one new to your unit as a developer , should just need some time to go through the Unit Tests to get the Idea how the unit should work.

3. Unit Tests are the tools that make integration much easier.

4.Last but not that least - Refactoring was never been so much easier if there were Unit Tests.

Any comments or suggestions on this post is most welcome.

Using Predicate & Action of .Net2.0

While I started developing software, I faced this situation over and over again where I had to iterate thorough the whole collection and perform some action on each of the element of the collection or filter elements depending on some logic. It was really annoying to  write same for/foreach loop again and again.

.Net framework2.0 resolve this issue where we can just tell the collection how to filter / how to perform some action on each element of the collection and it take care of the iteration part.  Let's check out the List<T> Class of System.Collections.Generic and what support it provides -

image

Huge support for Searching, Sorting and Filtering!!! If we look at the declaration of let's say - FindAll and ForEach  -

public List<T> FindAll(Predicate<T> match);public void ForEach(Action<T> action);

Here Predicate and Actor are the generic delegate which gives us the flexibility to provide a way to filter the collection or perform action to each and every element of the List. Let's dig deeper inside them -

Inside Predicate:

Predicate is a Generic Delegate which takes support from the new generic feature of .Net Framework2.0. It is defined -

delegate bool Predicate<T>(T obj)

As per definition of MSDN, Predicate -

"represents a method that defines a set of criteria and determines whether the specific object meets this criteria."

In short, Predicate is just a generic delegate that takes T as object and check whether the object fulfill some criteria and depending on that return true|false.

Example

In this example, by using Predicate, we are going to tell the Collection how to filter and Collection will handle the whole iteration and filtering process -

Let's say, we have a collection of SprintBacklogItem and we want to filter them depending on there State == Closed, we can do it using predicate -

1. Define a method that represents the Predicate -

private bool HasStateClosed(SprintBacklogItem item) 
        { 
            if (item.State == SprintBackLogStatesStrings.CLOSED) 
                return true; 
            return false; 
        }

This method simply checks whether the SprintBacklogItem's state is closed or not and depending on that , return true or false. Now, if we look at the declaration of the method , we are affirmative that we can use Predicate to represent this method.

2.  Following line of code filters all the closed SprintBacklogItems -

List<SprintBacklogItem> closedItems= _SprintBackLogsItems.FindAll(HasStateClosed);

Inside Action:

Similar to Predicate,

"Action is also one kind of generic delegate which represents a method that take the object as input and perform some operation on that."

Definition of Action delegate-

delegate void Action<T>(T obj);

From the signature of the delegate, it can represent the method with signature that must have one parameter passed to it and void as return type.

In List<T> , the method represented by the Action delegate takes an input obj and perform actions on that.

Example

In this example, by using Action, we are going to perform some predefined actions( initializing ActualHour = 10) on each elements of the List -

1. Define the method that will be represented by Action -

public void InitActualHour(SprintBacklogItem item) 
        { 
            item.ActualHour = 10; 
        }

2. Following line of code initialize all the elements' Actual hour to 10 of the List -

this.ForEach(InitActualHour);

Isn't it pretty cool and slick ? Instead of implementing methods for Actor and Predicate , we could have used Anonymous Delegate. I will cover that topic in my future posts. Bye for now. :)

Posted: Apr 16 2008, 06:30 PM by Adil Akhter | with 3 comment(s) |
Filed under: ,
Designing Efficient Immutable .Net2.0 Objects

What is an immutable object?

By definition immutable object is the object whose state can not be changed after it is created. That means, after creating the object, its publicly exposed members can not be changed from their initial assigned values. On the contrary, mutable objects are objects whose state can be changed at any point of time.

Every developer has to take a important decision whether to make a class mutable or immutable while designing the domain model.
While taking this decision, careful considerations can make us avoid the potential pitfall of using immutable object. 
 Why & How using immutable .Net object – is our today’s discussion. Let’s begin with How part . 

How to implement .Net Immutable Object?

 The way I would implement an immutable .Net class –           

-          Make the fields private readonly.
-          Provide a Public property with get accessor.
-          If the class is no longer needed to inherited – making it sealed. 

Like in the following example, I am implementing an immutable class  UserContact which will be inherited in User  

classdiagram1.jpg

 Here is the Implementation of the Immutable classes –     

    public class UserContact

    {

        private readonly string _Name;

        public string Name   

        {

            get { return _Name; }

        }

        private readonly string _EmailAddress;

        public string EmailAddress

        {

            get { return _EmailAddress; }

        }

        public UserContact( string name , string emailAddress)

        {

            _EmailAddress = emailAddress;

            _Name = name;

        }

    }

UserContact get inherited by User as follows [Since User class is no longer inherited – we make it sealed] -

 

    public sealed class User : UserContact

    {

        private readonly string _UserName;

        public string UserName

        {

            get { return _UserName; }

        }

        public User(string name, string email, string userName)

            : base(name, email) { }

    }


So, isn’t it really easy to implement a Truly Immutable class in .Net framework? J Now the question pops into our mind – why we will be using immutable .net objects , what would be benefits of that ? Let’s explore that –  

 

 

Why use immutable object?

 Protection:

From the definition we know, Immutable objects can not be changed after its being initialized. So, while using inside application, immutable object can flow in different layers of the application without getting worried about being altered by different layers.  

Performance:

Copying object will be much easier, we just need to copy the reference instead of copying the whole object. It would be much faster to copy reference than the whole object.

User user = new User("adil", "adil.bd@hotmail.com", "adak");
User userTemp = user; 

In case of mutable object, we would need to create defensive copy of the object and in .Net term, we need to create a Deep Copy of object otherwise, changing a property in the actual mutable object would reflect everywhere where the object is referenced. For example, let’s consider User as mutable; then changing any thing in user object will have same impact on userTemp as well which is not intended.

To avoid this situation, in case of mutable object, we need to make a Deep Copy of the object which is a costly operation. However, for immutable object, copying the reference would be enough since its state can’t be changed. 

Scalability:

Thread synchronization is an issue of concern while designing multithreaded application. Overhead of synchronizing immutable object is far less than mutable object. By default , an individual immutable object does not need to be synchronized as its state will be not be modified by any thread. However, since the immutable object will still be accessed thorough reference , it would require some synchronization. In complex sync scenarios, immutable object would perform far better then mutable version.   

Consistency: 

If we consider inheritance hierarchy, immutability provides a way for the sub-class to maintain consistency in inheritance hierarchy. Consider following mutable objects–

 

classdiagram2.jpg

When we instantiate the StudentMutable object, the AccountType is automatically set to Student Account –

public StudentMutable(string name , string email , string userName )
: base(name ,email , userName,"Student Account"){}

 Now, we can write following lines by which the AccountType property could be anything other than "Student Account” which is completely inconsistent -   

StudentMutable mutable = new StudentMutable("Adil", "Adil.bd@hotmai.com", "adil");   
mutable.AccountType = "whatever account";   

But if we use Immutable object in inheritance – the object hierarchy will always be consistent.:) 

 

 

What to consider while designing Immutable objects?

Intantiation of immutable object might be considered an operation that will be done more frequently. Then the allocation and freeing the resource for the immutable object would be the most recurrent opertaion which might result as performace overhead. Incase of regular objects , it seems that syncronization is far more costly operation from CPU perspective than allocating and freeing resource.  

For objects that require significant time to initialize , we may consider to implement Object Pool or Flyweight pattern to enhance reusability.  

Conclusion

 So , We can achive much faster and efficient code if we use Immutable object. But by saying all this , definitly we need to design accordingly and carefully so that immutable object can perform to its best. In this article , we learn how to implement immutable object in .Net and what’s its benefits and what we need to consider while implementing immutable object. In my next post , I am thinking to write something about reusing the immutable object to enhance efficiency. Thanks for visiting the the blog. Let me know your comments and feedbacks. Bye J .  

kick it on DotNetKicks.com
Visual Studio2008 Themes
del.icio.us Tags:

If you are also fond of changing the look and feel of Visual Studio using cools themes, here is some cool links for you -

1. A list of Cool themes in Scott Hanselman's blog
2. Dark Visual Studio
3. ZenBurn-based Visual Studio 2005 theme supporting HTML,CSS and XML
4. Join the Dark Side of Visual Studio by Dave Reed
5. TextMate Theme For Visual Studio, Take 2

del.icio.us Tags:

How to change your Visual Studio 2008 Theme -

1. Changing your colors in Visual Studio.NET - Black versus White By Scott Hanselman
2. Dark Visual Studio - By Brad Wilson
3. Pimp MY IDE by Jeff Atwood
4. Code Colorizing and readability by Jeff Atwood

Download LInks -

1. Download Jeff's scheme
2. Download "Zenburn" scheme
3. OrenEllenbogen_DarkSchema.rar (58 KB)
4. Is You IDE HOT or Not?

How to change your themes :

Step - 1 : Click on the Import And Export Settings :

image

Step -2:  Select Import Selected Environment settings and click on Next

image

 

Step -3: You get the option to save your current setting. I would suggest to save it.

image

Step-4: Click Browse and select the *.vssettings file and click Next -

image

Step-5: Check the boxes the setting you want to change and click finish. You are done with you brand new theme.

image

 

If any error occurs or you dont feel like using your new theme, you can always get back to your old setting by getting upto Step4 and setting your themes to import is the one you saved in step - 3 -

image

 

And you also have the option to reset all the settings [Step-1].

Have fun with the themes.

Posted: Apr 16 2008, 06:22 PM by Adil Akhter | with no comments
Filed under: ,
More Posts