Archive Page 2

31
Dec
07

Imperative and Declerative

Some time ago, satisfied with my Algoliness, I found out that Haskell, LISP people seem a bit more intellectual, a bit more more academic. They seem to behave like they know something no one else knows. Well, they knew about grocery lists.

The Differnce

How do you iterate over a list of 10 items?

Imperative:

  1. create a temp variable i = 0
  2. loop:
  3. use THAT to process it
  4. advance,
  5. is end?
  6. terminate / return to loop.

Declarative:

  • Make me a list from 1 to 10. Use THAT to process each.
  • So the first one is imperative, just as the name suggests. Its a grocery list, and you’re the one doing the shopping. In every step of the way you’re telling the compiler what to do. Its far from the concept we’re trying to realize.

    The second one is declarative, its essentially the concept itself. Make me a list, you do the shopping. Why not let the compiler worry some more?.

    And that is the reason for the personality those people adopt. They don’t just act like they know better, they really do. They’re programming much closer to the concept.

    In a way this is somewhat like the difference between C and Assembly. You can conceptualize and write ‘if’ clauses, and you can code it out with jmps and cmps.

    Sidenote: Recursion Is Hard?

    While analyzing recursion, if you loose track, you sink. However I’ve long learned to use the “leap of faith” with recursion, because I had to – that was the only way to not sink. Originally read from a Prolog book, the “leap of faith” means “because its abstract, you should not pick into the detail”. Trust the recursion and you’ll curse away the evil.

    29
    Dec
    07

    Book: TDD by Example

    Or more formally known as Beck’s TDD, is a very lucid book, in the sense that I’ve read it in one swell foop. It took me from morning, through eye-drying moments, to late evening, but I just couldn’t stop reading it.

    This book is mostly fun, and you get the side-values of learning a lot of important lessons in TDD and development in general.

    Just as a brain teaser, Beck philosophically speculates that flexibility only comes where you need change, this is his “triangulation” mantra.

    [spoiler alert]

    In short, it means that to implement a function that adds two numbers, we write a test:

    Assert(4, add(2,2))

    And we implement it as:

    function add(a b): return 4

    How well do we know the add function? from kinder garden we also know that 3+4 = 7 so we re-implement:

    Assert(4, add(2,2))

    Assert(7, add(3,4))

    And we “triangulate” the code:

    function add(a b): return a+b

    We applied the minimal possible change to the code that makes the tests pass which means it is now as simple as it gets = elegant.

    We took things in baby steps which means we have less margin for error.

    We left little for speculation.

    This is test-driven development.

    Ofcourse, this book also gets my rare 10/10.

     

    29
    Dec
    07

    Eclipse: Parallel Source Hirarchies

    My current endeavor into eclipse plugin development requires storing metadata in a file-structure very similar to the existing one. For each source file I create a ’shadow’ meta-file.

    This way, **/myproject/src/model/databaseapp.java becomes **/myproject/META/src/model/databaseapp.java.meta

    Path and Resource manipulation is so great in eclipse, I was able to easily do that:

    private IPath createMetaDirectoryPath(IResource file)
    {
    IPath projectPath = file.getProject().getLocation();
    IPath fileRelativePath = file.getProjectRelativePath();

       return projectPath.append(Strings.METADATA_DIR).append(fileRelativePath)
    .addFileExtension(Strings.METADATA_FILE_EXT);
    }

    I use getProjectRelative() to get the middle part of the path, append my own path to the project path via Resource.getProject().getLocation(), and then glue it all togather.

    29
    Dec
    07

    Generic Delegates

    A delegate is a type and is also a class, so we can create generic classes of that, thus generic delegates. I’ll examine what good comes from that. With functional programming becoming a streamlined concept in C# 3.0, delegates come up as very important for code readability and reuse, for everyday code and not just events / threading.

    Crash course into delegates:

    We want to use functions like variables, pass them around and refer to them dynamically. If you’re familiar with C/C++, this is function pointers. The classic example is that of a calculator, with functions: Add, Subtract. When the user select addition, you fetch the Add function object, assign into your delegate, and invoke it. The code invoking the delegate is always there, you change behavior only by assignment.

    In C#, delegates are simply types. The syntax needs getting used to – remember - its all just a declaration and nothing more. It looks like a hybrid of a variable, class, and method declaration!.

    delegate <return type> <DelegateName> (arguments)

    It looks like a variable because thats how you declare it.

    It looks like a class because you later new it.

    And, it looks like a method because the definition is similar.

    so declaring one would be:

    delegate int MyDelegate(string mystring, int myint)

    And using it would be:

    MyDelegate myd = new MyDelegate(yourfunction/otherfunction/anyfunction);

    myd(“hello”, 999); //call like your original function, do you know which of the functions are called?

    Notice that using delegate inference you can also do:

    MyDelegate myd = yourfunction/otherfunction/anyfunction;

    directly!.

    yourfunction, or anyfunction would need to match the signature of MyDelegate to be assigned to its ctor.

    And thats all there is to it, you can now use myd to hold any function from the set of all functions that obey that signature!.

    How about the set of all functions that have the same return type, and same number of arguments (we dont care about their type)? That one is a bigger set, and it needs more generalization, this is where generics comes into play.

    case study: the Action<> generic delegate.

    We want to express a delegate for a function that will take something and perform action on it, without returning anything. Therefore we only need to know the type of that something which is the parameter type.

    We can go ahead and write a specialization for each case:

    delegate void StringAction(String param)

    delegate void IntAction(int param)

    delegate void BooleanAction(bool param)

    delegate void FileAction(File param)

    etc..

    But what we can do is somewhat like function templates in C++. We use the wildcard just to express the method parameter type.

    delegate void Action<T> ( T param)

    So, Action<string> simply becomes:

    delegate void Action(string param)

    Now Action<T> conceptually represents *all* of the delegates for functions who take a single parameter and return nothing.

    Anonymous Methods

    As an extra bonus, we don’t really have to remember the delegate name (in the example MyDelegate) to use it. If you provide an appropriate signature, you can use an anonymous method (like anonymous inner class in Java, but easier to the fingers), where ever a delegate is expected.

    myList.ForEach( delegate ( string mystring) { do stuff with mystring } );

    This is an overload of the delegate keyword. The compiler will take all of the housekeeping like generating a delegate and assigning the method to it, and notice the return type would need to be inferred.

    If you use lambdas everything is inferred:

    myList.ForEach(mys => do stuff with mys);

    If you want to be really creative, try dropping the parens after the delegate keyword. You’ll be creating a function that works with ANY signature.

    .. = delegate { anything you want to do} ;

    We can now use action in any function that repeatedly applies an action on an item, such as for example, a program that would read a list of URLs, download each, and extract links from each page.

    21
    Dec
    07

    On Keyboards and Programming

    Recently I had a disaster, rendering my favorite keyboard useless. In an on-going research, I was able to define a good programming keyboard checklist.

    1. Short key travel, springness that easily transmits that a key was pressed.  This means laptop-like keys. And keys that are not ‘mushie’.
    2. Home-row safety. The keyboard must be short (left to right) so that travels to the mouse back and forth are minimized. Further, accessibility to Home/End/Arrows must be within right pinky’s reach.
    3. Meta-keys. Shift, Ctrl, Enter must be big and wide, preferably on both sides.
    4. Left CTRL-SHIFT combination with a letter should not be hard. Same for left SHIFT+letter and right SHIFT+letter.
    5. Right SHIFT+braces should not be hard
    6. Backspace should be rapidly accessible with pinky.
    7. Optional: flat keyboard. No media buttons.

    Sadly enough, no keyboard that I’ve checked accomplishes every thing on this list.

    I cannot find BTC6100 in my country anymore.

    I’ve tried Logitech Ultra Flat, but this failed me due to mushie keys, and short meta keys.

    I’m currently using MS Comfort Curve 2000. Key feedback is really, really great. The downside is that its way too big, each travel to the mouse taxes a lot in time, as well as each travel to Home/End/Arrows. Further my country uses the 105 keys layout which comes at the expense of the left SHIFT and CTRL keys which is really really bad — the shift key is now as wide as a normal letter key.

    The quest for the Holy Grail continues…

    08
    Dec
    07

    Reflective Visitor

    A variant of the Visitor design pattern that I didn’t know exists, probably because I didn’t know Visitor is a family of design patterns. It is described very fluently here. Usually it is good for parsing, where the main intent of reflection is prevent changing the interface every time we add parsing functionality.

    Actually the Wikipedia entry describe it fully, and I think the best way to understand it is implementing a pretty-printer, since maintaining state in a Visitor class is a very cool bonus. (hopefully I’ll try that)

    An addendum to that, is setting up by going over all the reflective values, storing all of the methods inside a hash, and fetching them with a key (from a hash) to avoid reflecting each time and again.

    08
    Dec
    07

    A State of Flex

    I remember when first seeing Flex, that it was the ultimate, best thing out there. With its advanced binding abilities, MXML, and those cool sleek visuals – what more can a dev ask?. Then came AIR, adobe was determined to rule RIA. And MS had no answer.

    I myself researched alternatives, openlazlo, etc. There was only Winforms to compare to, but that was oranges and apples, really.

    Then came Silverlight. This was actually the quiet before the storm, Silverlight had no builtin effects, no controls, and exposed raw interface and unknown idioms. People started comparing Silverlight vs Flex, and the general opinion was the Flex was much superior. I spent a day googling for such comparisons, and saw some conversations between an Adobe dev and Silverlight fans over the Silverlight forums.

    But then the storm came. Microsoft rose up all guns machine guns, rockets, and turrets blazing, with the release of VS2008, .NET 3.0, 3.5 the VAST documentation, blogs saturated with information, and now even upcoming MVC.NET and framework source code(!).

    Only with these all bits and pieces out there, everything starts falling into place. suddenly using Expression Blend feels “right” and making my own Silverlight controls is a second nature. Visual Studio is so great that it makes me want to leave it open 24/7, and WPF is so much fun I don’t want to do anything else!
    Currently I guess Adobe is deep in developing the Flex 3 IDE, and from the Beta2 state of things, its hella buggy. So, I think it is inevitable to declare Flex as dead.

    03
    Dec
    07

    Attached Properties/Events

    This is a new concept in WPF. However I find that the best selling book in WPF (WPF Unleashed) fails to explain the meaning properly. I will attempt to explain this, trying to rely on familiar concepts.

    Firstly, you can take at this short but to the point post to get the motivation for using Attached Properties/Events.

    If you’ve read the motivational part in the link above, you now know, that a Parent object needs to store information about his Children.

    So the Parent attaches a property, a tag if you will, on each Child. Imagine it as you putting post-it notes on items before shipping them off. Coding rational: the information serves you and thats why you need to provide the facilities to store and manipulate it:

    (From Rob’s example)

    RobPanel.SetRotatationsPerMinute(b1, 30);

    Rob’s Panel tracks information, or property, of the button b1. From the button’s b1 point it has an attached property.

    This is a lot simpler than the XAML syntax, because it would rely on knowledge you already have. Attached Properties are probably a concept for something you coded before.

    So Attached things conceptually are nothing but a Hash at the parent, where the key is the child object and the value is the information. Practically, it might be that the Child “inherits” the property from the Parent, what ever it may be, the concept remains the same.

    The confusing part is that in XAML it only seems like it works the other way around. That is, metaphorically, every item puts the post-it note on himself:

    (Directly from Rob’s example – see link above)

    <my:RobPanel>

    <Button Name=”b1″ my:RobPanel.RotationsPerMinute=”60″ />

    <Button Name=”b2″ my:RobPanel.RotationsPerMinute=”3″ />

    </my:RobPanel>

    Hope I’ve cleared things up.

    29
    Nov
    07

    Books: PEAA, Refactoring

    I’m trying to keep up with the ‘a book per 2 weeks’ aim.

    Refactoring

    Let me just say that this book holds the wicked wisdom only achieved by experience. Once per several years you stumble into a truly good book, and to cut things short, I give it my score of perfection (relative to the current computer-related state of book publishing :-) 10/10.

    PEAA

    A great book by Fowler. He manages to cram so much into a relatively small volume (~550pgs). Everything I ever wondered about in enterprise software, and was afraid (enterprise concurrency, session management, anyone?) to know, is there. It does what it promises, every pattern has simple abstract-ish example, and every idea is explained thoroughly. This, also, is a very rare 10/10.

    29
    Nov
    07

    Coderev: Genghis WindowSerializer

    Genghis is a set of extensions built on top of .NET and integrated with WinForms to provide application-level services in the same flavor as the Microsoft as the Microsoft Foundation Classes. This project seems a bit dead, and a bit buggy. However its a great repository of wisdom, since some cool people work or have worked on it.

    Starting off with WindowSerializer, this is a cool way of doing a .NET component. When you drop it on your form, it will plug into its OnClose, OnLoad, OnResize and OnMove events, as well as nick itself the form instance variable.

    When the form fires any of these events, the WindowSerializer will record the change, and when OnClose is fired, it will flush its state to disk. When OnLoad is fired, it would load that state and update the form’s properties as needed.

    They tried to provide some sort of Strategy/Provider pattern, so you can choose what kind of storage you use for the form settings, defaulting to Isolated Storage
    . I found some of the code they used there confusing. Some variables were not used at all, I think they were some ‘just in case’ code. Specifically I’m referring to the path idiom they used.

    private string ValidatePath(string path, string argumentName)

    Here, argumentName was never used in the function body. Also, path, which is seen here and previously being passed to the ctor, moved around in 4 places in the code, isn’t actually used for anything, which render this method and perhaps other path-handling methods useless.

    What I would do, is provide an abstract class like they did, but leave all those path or logical setting separation out:

    • Instantiate with the FQN for the form name
    • The abstract class will contain the get/set property convenient methods, abstract “‘main” get/set methods and abstract Serialize/Deserialize methods
    • The implementing object is a data object.
    • Which could use .Net serialization, to Isolated Storage, if we decide to use XML. Or our own if we implement a registry based serialization