Kurser och utbildning av IT-proffs och systemutvecklare

i Sök

Cornerstones utvecklarblogg

Alla Taggar

All Tags » C#   (RSS)

  • .NET 4.0 is to Lazy

    With .NET 4.0 there is a new class added to the System namespace called Lazy<T>. This class is what the name applies, lazy. Here is an example where Lazy is used:

    var lazy = new Lazy(IList<OrderRow>>(
                                    () =>
                                    {
                                            var rows = //get order rows;
                                            return rows;
                                    });
    
    var rows = lazy.Value;
    .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }


    The Lazy<T>’s constructor can take a Func<T> as an argument, the function passed as an argument to the contractor will first be invoked when the Value property of the Lazy<T> class is used, but not invoked the next time the Value property is used. The code above will first execute the function passed as an argument when the we request the value of the Lazy<T>, the returned value of the function will be cached. The next time Value is used, the function will not be invoked, instead the cached value will be returned. This class  can for example be used when we want some kind of Lazy Loading.

    I’m on twitter: http://www.twitter.com/fredrikn

  • Map Objects to one Object

    In my previous post I wrote about how we could use Dynamic Compilation for mapping object to object in a configuration file. I spend a few minutes to see if I could do something more to it. It ended up that I can use it to several things, like creating Factories, or send in different kind of objects and map several into one. Here is how I for example can send in more domain object to map them into a PresentationCustomer:

    var presentationCustomer = map.Map<PresentationCustomer>(
                                        "CustomerToPresentationCustomer", 
                                        customer, 
                                        address);


    My configuration file look like this:

    public PresentationCustomer CustomerToPresentationCustomer(Customer customer, Address address)
    {
           return new PresentationCustomer()
                      {
                           ID = customer.ID,
                           CompanyName = customer.CompanyName,
                           FirstName = customer.FirstName,
                           LastName = customer.LastName,
                           Street = address.Street
                      };
    }


    Some comments I got was also to automatically map properties from object with the same name, so I added an extension method called MapTo, to make that possible, it will also open up support for mapping specific properties manually:

    public PresentationCustomer CustomerToPresentationCustomer(Customer customer, string lastName)
    {
          var presentationCustomer = new PresentationCustomer();
    
          customer.MapTo(presentationCustomer);
    
          presentationCustomer.FullName = customer.FirstName + " " + customer.LastName;
    
          return presentationCustomer;
    }


    I did also add support so other developers can simply add their own code which could be used by the configuration file. It's done by adding the namespace and an assembly of the code to the mapper.

    DynamicMapper map = new DynamicMapper();
    
    map.Assemblies.Add("MyHelper.dll");
    map.Namespaces.Add("MyHelper");
    
    var presentationCustomer = map.Map<PresentationCustomer>(
                                                   "CustomerToPresentationCustomer", 
                                                    customer, 
                                                    "Normén");


    Here is the MyHelper:


    namespace MyHelper
    {
        public static class MyExtension
        {
            public static string GetName(this string value)
            {
                return "Fredrik";
            }
        }
    }


    I can now use this extension method in my configuration file:


    public PresentationCustomer CustomerToPresentationCustomer(Customer customer, string Name)
    {
           return new PresentationCustomer()
                      {
                           ID = customer.ID,
                           CompanyName = customer.CompanyName,
                           FirstName = name.GetName(),
                           LastName = customer.LastName,
                           Street = address.Street
                      };
    }


    Because I can pass in several objects and map them to one single object, I can also pass in XmlDocument, DataSet, DataTable and SqlDataReaders etc and map them to an object:


    var presentationCustomer = map.Map<PresentationCustomer>(
                                        "CustomerToPresentationCustomer", 
                                        customer, 
                                        sqlReader);
    public PresentationCustomer CustomerToPresentationCustomer(Customer customer, SqlDataReader reader)
    {
           return new PresentationCustomer()
                      {
                           ID = customer.ID,
                           CompanyName = customer.CompanyName,
                           FirstName = customer.FirstName,
                           LastName = customer.LastName,
                           Street = reader["Street"]
                      };
    }


    I can think of using this solution if I don't use an ORM but still want to bind data from a SqlDataReader to an object, or combine several object and use formatting and specifying default values which could be changed over time, and when it does I don't need to recompile my code, only change the configuration file.

  • Multiple Return Values - Part 2 ;)

    Because of so many good comments on my previous post about Multiple Return values (Tuples) I need to write a new post, I think this kind of discussion is relevant to the .Net Community and I’m so glad that so many have spend the time about their thoughts and ideas etc about this topic. People can call me stupid, that I can’t develop apps, or have a bad design if I need multiple values, well it’s my idea of a replacement for out parameters, and also avoid creating some kind of container to hold more values to only support single point of return. My new post will probably make more people upset ;)

    So many people that don’t like Multiple Returns (Tuples), I can sort of understand why. But have you ever tried to use it in a real project and also together with Agile? I hated the multiple returns when I first saw it, but after using it in a project, or at least the Framework I used which had several helper methods where they use multiple returns, I started to like it. The main reason I liked it was that I could avoid creating different type of structs, arrays, using hashtables and create objects which only should hold few information and in some cased never been reused. The problem with an Array and Hashtable is that I need of extra documentation, like what value is in index 0 and in index 1 of the returned array (An Array with different type of objects aren’t typed), and what keys do I use to fill the Hashttable etc. A method which will return multiple values need of course some documentation too, but the same with a method that returns a struct or object etc, or use out parameters. If we create objects, structs etc to hold info, to not make the code plotter with different type of structs we need to reuse them. But some methods which should only return x,y can’t use a struct which have x,y and z. Because the developer that uses this method don’t know if the z shouldn’t be used etc.  So in this case multiple return values can be useful. Multiple values are often not logically related, so you can't define a sensible class to pack the values into. And if you did define such a class, it might only be used once. I know that some of you don’t agree with me, but hey everyone can’t like everything another people like ;) But I think you are going to like it (or at least some of you), when you use a language which will support it. I have worked with OOP since 1994, and think I know the concept now ;) and how to write code. For 2 years ago I first started to work with LUA, which is a dynamic language which uses the Multiple Returns, and by using it in a real project, I started to like it. The multiple returns can for example be used in functional programming. And remember that C# is a Hybrid. I read an interesting book where two developers uses TDD and eXtream Programming. When the project was done, they didn’t even used OOP at all, it was functional based. There was no need of using OO. Once again there is no Silver Bullet.

    Today I notice that other people have blogged about Multiple Returns and came across some articles, you can read their thoughts here:
    Take a look at this forum, some C# developers are also talking about Tuples, it seems they have adiscussion if JAVA Should support Tuples or not, don’t know if they have add it, or will not add it. But it was interesting to see that a language like JAVA have it under consideration.

    http://forums.java.net/jive/thread.jspa?messageID=16969&tstart=0

    This one was good ;):

    “Something I have never seen is an argument why a method should only return one value, when nobody argues that a method should only take one parameter. Why should there be a difference?”

    http://cairographics.org/manual/bindings-return-values.html

    http://onthethought.blogspot.com/2004/12/multiple-return-statements.html

    http://www.informatik.uni-kiel.de/~scheme/doc/mzscheme/node7.htm

     

  • Remove code smell with AOP

    During the last years you have probably heard about Aspect Oriented Programming (AOP). Different people like or don’t like AOP. I’m one of them who like AOP. As you may now VB.Net and C# are object orientated languages and with object oriented programming (OOP) you want to reduce code duplication, code duplications smells badly. If you need to do code duplication you are probably doing something wrong with the implementation of your domain model. With OOP you can generally eliminating code duplication, but there are some cases where we can’t avoid it, for example take a look at this code:

    public class MyClass
    {

           public void MyBusinessMethod1()
           {
                 CheckSecurity();
                 //Place your code here
           } 

           public void MyBusinessMethod2()
           {
                 CheckSecurity ();

                 //Place your code here
           } 

           public void CheckSecurity ()
           {
                //Place the code for the security check here
           }
    }

    The code above has code duplications, where CheckSecurity method is added to each business method. This code duplication is not only painful to write, it could also make the code smell bad and make the code less maintainable. With the refactoring Move Method "A method is, or will be, using or used by more features of another class than the class on which it is defined", the CheckSecurity method could be moved into the infrastructure and the new class where the method is located will be the only place where the CheckSecurity is located. Centralization of code will make it easier to maintain the code. Even if you use the Move Method, the MyClass still use code duplication. Unfortunately, OO doesn’t help us removing the code duplication. You could of course use code generation to manually avoid adding the CheckSecurity to each method where the security check needs to be done.

    AOP crosscutting can be used to address concerns such as the security checks and of course other application specific concerns too, for example, you could make Lazy Load work without needing to have a dependency to your Repository or data mapper within the domain objects. With AOP, you could remove the code duplication from the code example above, and create a method interceptor where you add the CheckSecurity method. The following is a pseudo code of an interceptor:

    public class MySecuirtyInterceptor : MethodInterceptor
    {
          public object Invoke(MethodInvocation invocation)
          {
                CheckSecurity (); 

                //Call next interceptor
                Return invocation.Proceed();
          }
    }

    By using an AOP framework where you could define a set of methods (pointcuts) that should use the security interceptor, you could easy remove the code duplication, and remove the security concern from the developer, and add it later, if it’s required. The The MyClass in the first example could look like this if we use AOP and the MySecurityInterceptor above:

    public class MyClass
    {
           public void MyBusinessMethos1()
           {
                 //Place your code here
           }

           public void MyBusinessMethos2()
           {
                 //Place your code here
           }
    }

    Developers don’t need to add the CheckSecurity method. If we need to have a security check before executing the method, you could add a pointcut later for the methods that should call the CheckSecurity. Some sophisticated AOP frameworks can use regular expression or other wildcard syntax for the pointcuts. Pointcuts is a set of Method, Fields or Throws (When a particular exception is thrown) that should invoke the interceptor method. Those pointcuts could for example be specified within a XML file.

    You can also use AOP to do some logging or other operations before or after a method has bean invoked, or a field has been set, or even when en exception was thrown. The developer who are creating the business methods, don’t need to call a method that will for example log a message, it’s something that could be specified within an XML file. By using AOP you could solve problems that could not be done with OOP. You can not only reduce the smell of bad code, you could also reduce time it takes to add the duplication of codes etc. I hope this post gave you some more information about how you can use AOP to solve some problems that can’t be easily done with OOP.

  • Multiple return values, I want this in C#

    I so badly want to have support for multiple return values in C# instead of using out parameters.

    Note: The following is only an example, we can use a struct or an object to create a data structure which will hold the value, but I only use this code for demonstration purpose.

    int x,y,z;
    bool isHidden;

    GetCords("MyElement", out x, out y, out z, out isHidden);


    Instead of the code above, I want to do something like this:

    Return 10,11,10,true;

    var x,y,z,isHidden = GetCords("MyElement");

    If I don’t care about the y and z return values I can instead write:

    var x,,,isHidden = GetCords("MyElement");

    Isn’t this beautiful?

    hmm,  when I’m thinking of beauty, I start to think about "The beauty is in the eye of the beholder" ;)

    To confess something, the language LUA support this and I loved it when I created an add-on for World Of Warcraft.


Den här bloggen

Syndication