Friday, June 14, 2013

Let's talk about patterns

Patterns are recipes, they are well known solution to a known problem.

Thinking about them as recipes can give us some insight on how they should be used.

Let's think about the kitchen.  In the kitchen, recipes are used, in a similar way, explaining how to cook a particular dish.

And indeed, you expect novice cooks to follow recipes to the letter.  However, a chef knows many different recipes,

but rarely follows one. 

To the chef recipes are just guidelines of things that work or don't work.  But he can mix and match or change the recipe as needed.

Bringing this back to software the software development world, advanced developers should be a chefs!  You should be aware of the patterns but not necessarily follow it to the letter.

Because patterns are not treated like this, but rather are made into a “holy” thing that must be used and must be followed to the letter, or else …, I have come to consider all patterns anti-patterns until proven otherwise.

Be the best chefs you can be, and may your dishes always be tasty!!!

Saturday, August 20, 2011

Generating an IEnumerable of Prime Numbers

A while back I was working on solving some math problems from the Project Euler site.  In order to solve the math problems I needed a Primes Number Sequence Generator.  So, I wrote a small class to generate an open ended IEnumerable of Prime Numbers.

The idea is as follows:

  1. Starting with 2 and 3 as known primes
  2. For each known prime create an open ended IEnumerable that enumerates over multiples of that prime.
  3. Find the next prime by advancing each of the Known Primes Multiples Enumerators until the multiple of the prime is greater or equal to the next candidate.
    1. If one of the Known Primes Multiples Enumerator values is equal to the current candidate, it is not prime.
    2. If all Known Primes Multiples Enumerators advance past the current candidate, then it is a prime and a new Known Primes Multiples Enumerator is added to the collection.

Because all the IEnumerators are implemented using the yield return mechanism, the enumerations can be open ended, advanced in parallel and be resumed.

So here is the implementation:

public class PrimesIterator
{
    private static List<KeyValuePair<long, IEnumerator<long>>> knownPrimes;
 
    static PrimesIterator()
    {
        knownPrimes = new List<KeyValuePair<long, IEnumerator<long>>>();
        AddKnownPrime(knownPrimes, 2);
        AddKnownPrime(knownPrimes, 3);
    }
 
    public static IEnumerable<long> NewEnumeration(long maxValue)
    {
        long current = 1;
        foreach (var knownPrimeStepper in knownPrimes) {
            current = knownPrimeStepper.Key;
            if (maxValue > 0 && current > maxValue) {
                yield break;
            }
            yield return current;
        }
        for (current = NextPrimeAfter(current); maxValue == 0 || current <= maxValue; current = NextPrimeAfter(current)) {
            yield return current;
            AddKnownPrime(knownPrimes, current);
        }
    }
 
    private static long NextPrimeAfter(long current)
    {
        while (true) {
            current += 2;
 
            double currentRoot = Math.Sqrt(current);
 
            foreach (var primeMultiplesStepper in knownPrimes) {
                if (primeMultiplesStepper.Key > currentRoot) {
                    return current;
                }
                while (primeMultiplesStepper.Value.Current < current) {
                    primeMultiplesStepper.Value.MoveNext();
                }
                if (primeMultiplesStepper.Value.Current == current) {
                    // not a prime.  Is a multiple of primeMultiplesStepper.Key.
                    break;
                }
            }
        }
    }
 
    private static void AddKnownPrime(List<KeyValuePair<long, IEnumerator<long>>> knownPrimes, long prime)
    {
        IEnumerator<long> newPrimeEnumerator = MathHelpers.SteppingItrator(prime).GetEnumerator();
        newPrimeEnumerator.MoveNext();
        knownPrimes.Add(new KeyValuePair<long, IEnumerator<long>>(prime, newPrimeEnumerator));
    }
}

And here is a Unit Test that shows usage by extracting the 1000000th Prime Number:



[TestMethod()]
public void NewEnumerationTest()
{
    IEnumerable<long> primes = PrimesIterator.NewEnumeration(0);
    var actual = primes.ElementAt(1000000);
    var expected = 15485867L;
    Assert.AreEqual(expected, actual);
}

Monday, March 17, 2008

Thoughts inspired by ASP.NET MVC Programming model

I have been reading Scott Guthrie's and Scott Hanselman's posts on ASP.NET MVC and it got me thinking.  Here are a few points that I think would be interesting to discuss further:

  1. Quite soon after I started developing Business Web Applications, circa 2001, I came to the conclusion that the programming model offered at the time did not suite a Business Application so well.  HTML, then ASP, and finally ASP.NET, had serious shortcomings as far as developing Business Applications.  This is not to say that it was not possible to develop them.
    The programming model that came to my mind was as follows:

    1. UI happens in HTML in the Browser (no back and forth postbacks for updating the UI).

    2. Navigation happens in the Browser (no need to go to the server to navigate to a new page).

    3. You only go to the server for Business Processing and Data. (Well, this is kind of like AJAX)
      Wait a second; now that I think of it, this model reminds me of something!  Hmmm...
      This looks a lot like Smart Client Application, or Silverlight, but developed in HTML.  Wow, what do you know, the programming models for Business Applications are merging ...


    Of course, none of the tools of the time supported the model I had in mind very well.
    In my opinion, ASP.NET MVC takes a huge step in the right direction.  However, it is not quite there yet. 
    For instance, regarding Navigation, when you initiate a POST or a GET from the browser, it is the decision of the browser where to put the returning HTML.  This does not seem to sit so well with the notion that the ASP.NET MVC Controller decides which View to render on the server.
    Furthermore, if your navigation is done from the server by Rendering a new View, does this mean that we will go back to whole pages refreshing every time you go to the server?  I thought we were on the verge of resolving this problem with AJAX.
  2. ASP.NET MVC is NOT ASP.NET!  In all the blog posts and presentations I saw coming out from Microsoft about ASP.NET MVC they make a point to say that it is an extension on top of ASP.NET and that the two models will play well together.  I think that in reality, this is not the case.  If the ASP.NET MVC programming model catches on, it will completely deprecate ASP.NETASP.NET is about the controls and their event handling model.  But the ASP.NET controls are a no no in ASP.NET MVC because no Post Back is allowed (or supported).  This is just the same as the fact that you can still use ASP style programming in your ASP.NET pages, however, no one in their right mind does.
  3. ASP.NET MVC does a great job in regard to "Separation Of Concerns".  However, when I originally learned about the MVC Pattern it was suggested that an implementation would allow sharing the business part of the application between Web and WinForms based UI implementations of the same application.  I am not sure ASP.NET MVC is suitable for this (or was intended to do this).  So, this brings up a couple of questions:
    1. Is it possible to share the business part of the application between a WinForms implementation and a Web implementation of the UI?  How much customization would that require?
    2. How much further does the model need to be changed to support this inherently?

In summary, I would like to say that these are just my thoughts.  I hope that they will contribute to a fruitful discussion and to a better implementation.