Contact and Coil | Nearly In Control

CAT | Software

Aug/10

21

Getting a Property Name as a String in F#

I’ve been playing around with F# recently, the functional language that shipped with Visual Studio 2010. I’m looking at using it to write an application using WPF and the Model-View-ViewModel architecture. One big requirement is for DataBinding.

When you bind the View to the ViewModel, you typically have to use the explicit name of the property on the ViewModel that you’re binding to (like “Text”). You also need the literal name of the property when you fire off (or receive) the PropertyChanged event. That’s always been a little ugly, because using the literal string means it isn’t compile-time checked. I got around it in C# using a helper class which uses reflection and lambda expressions to look at a piece of code (e.g. o => o.MyProperty) and get the name of the property as a string.

That utility class didn’t work in F#, mostly because F# lambda expressions aren’t the same base object as C# lambda expressions. I was faced with rewriting it. This is where F# seems to shine. Here’s the same “get property name” logic written in F#:

    open Microsoft.FSharp.Quotations.Patterns

    let propertyName quotation =
        match quotation with
        | PropertyGet (_,propertyInfo,_) -> propertyInfo.Name
        | _ -> ""


Here’s how you can use it:

    type myClass(p) =
        member x.MyProperty
            with get() = p

    let myObject = new myClass(1)

    let myPropertyName = propertyName <@ myObject.MyProperty @>


At the end, myPropertyName has been assigned the string value “MyProperty”. It’s a heck of a lot less code. In this case it only works if you have an existing object to run it against. However, you can modify the propertyName function to make it recursively dig through the Lambda and find the PropertyGet:

    let rec propertyName quotation =
        match quotation with
        | PropertyGet (_,propertyInfo,_) -> propertyInfo.Name
        | Lambda (_,expr) -> propertyName expr
        | _ -> ""

    let myPropertyName = propertyName <@ fun (x : myClass) -> x.MyProperty @>


Now you don’t need to have an instance of the class lying around to get the property name.

No tags

Jun/10

7

Let’s do it again for the last time

This week I did something I’ve probably done a hundred times before, but this time it felt absolutely absurd. It’ll probably be the last time I ever do it.

What was this crazy event? I purchased shrink-wrapped software. It was an upgrade copy of Visual Studio 2010 (upgrade from 2008 Standard Edition).
Visual Studio 2010 Upgrade

I had to add a cute little piggybank because otherwise it just looked pathetic.

This little box of bits says it was “made in Puerto Rico”. I guess that means the RTM build was FTP’d to some server in Puerto Rico where it was burned onto a dual layer DVD. In fact it’s likely the DVD’s were burned somewhere else and shipped to Puerto Rico, but anyway, this DVD was then stuffed into plastic case along with a 5×7 piece of heavy stock paper with a beat up yellow sticker on it: the license key.

This plastic case was then stuffed into a cardboard sleeve and shrink-wrapped. It probably made its way to a distribution center before being sold to an online distributor CDW, where it sat on a shelf for a few weeks.

It was at this time that I started hunting around for a Visual Studio 2010 license. I had a copy of VS 2008 and I knew there was a discount for upgrades. You can actually download fully licensed copies from the Microsoft store for $399 (CDN), but I found this boxed copy for about $30 cheaper. Of course I still had to pay S&H, but that was about $13 (UPS Ground).

That was on Friday. Today it’s Monday and I received a call from the local UPS distributor. They’d put it on the wrong delivery truck today, so they wouldn’t be able to deliver it until tomorrow. I wasn’t going to be home anyway, so I told them I’d pick it up tonight after work.

I drove a good 25 km out of my way to go pick it up. The truck wasn’t back from its run yet when I got there, so I stood in line another 20 minutes waiting. I’m not knocking UPS here: their whole system boggles my mind. They knew exactly where this package was 100% of the time, even when it ended up being loaded on the wrong truck, and it was in my hand about 20 seconds after the truck pulled up to the building.

Never underestimate the bandwidth of a UPS truck full of dual layer DVDs.

After installing the software, the first thing it asks you to do is check for updates online. That’s because the version that came on the disk was probably out-of-date before it made it out of Puerto Rico. The only thing I really bought was a yellow sticker with my 16 digit license key on it. I could have downloaded a fully working copy last Friday night, and had it in about 2 hours. It would have worked for 60 days, and you could extend it for another 60 for no cost at all. The only thing of value was the legal right to use this software past the evaluation date. The 16 digit license key is only a proof of purchase.

The absurdity of shipping useless plastic and paper all of the continent, driving out of my way and even standing in line to pick it up, just to “prove” that I paid for a legal license to use the software — it’s really striking isn’t it? What’s crazier is how normal this seemed ten or even five years ago!

It’s not like I wouldn’t have purchased the $399 copy from Microsoft if that’s the only one I could find. I went through this because, well, given the chance to save about $15, I’m just cheap. I guess they figure some people won’t bother to pay money for something they can’t hold in their hand, but aren’t we past that now? Apple figured it out. Look at the iPhone App Store, and iTunes.

If I relate this story to my daughter ten years from now, she’ll think I’m nuts. You bought software how? Why?!?

Well, good riddance, shrink-wrapped software. Rest in peace.

The “low intellectual property” Fashion Industry as a model for innovation?

I have to agree. Since I’ve started getting involved in open source software, I can tell you that intellectual property laws are the biggest obstacle to innovation that I face. I can say that because I took the time to consult with intellectual property lawyers on everything from trademark to copyright to open source license to software patent. Here’s what I found out: you can’t write a single line of code without violating someone’s patent, somewhere. However, the only time that person will enforce their patent claim is if you’re really successful. The only defense is to pay tens or hundreds of thousands of dollars to build up a patent portfolio of your own so you can partake in a ludicrous arms-race deterrent. On top of that, your patent portfolio offers no defense against so-called “patent trolls”: companies that only own patents and don’t write software of their own. They’re the equivalent of a terrorist cell with nuclear weapons… your nukes are ineffective because you don’t have a city to target.

Copyright is under control, mostly because it’s so much weaker than patents, and it’s free. It stops whole-sale copying of your software, but allows someone to look at your source code, learn from it, and then write it themselves without violating copyright (if they’re careful). Plus, the wide adoption of open source licenses give us lots of material that we can freely copy or integrate.

The irony is that patents were supposed to speed up innovation, but they’ve done exactly the opposite in the software industry.

Do you want to know why none of this matters though? I’m going to make a bold prognostication here:

If the last decade (have we agreed on what to call it yet? The Oh’s?) was about more crap, then the next decade will be about customized crap. Seriously, we gorged ourselves on the mountain of crappage that is sold at Wal-mart and people are starting to wake up with a hangover. We’ve already seen the desires start to change from more to better but I think we’re going to see it change to mine. People are going to want unique stuff. Things that they had a hand in customizing. Something they can use to express themselves.

This has major implications for manufacturing, so it affects the automation industry, and I think it also affects software. Just like the fashion industry, where people use clothes to express themselves, we’re about to enter an age when all the crap you sell to consumers has to have a story, a personality, and be unique. Mass production will remain for your basic staples, and China is going to continue to provide us with that, but North America and Europe are going to have to start producing bespoke crap.

What does this mean for automation? We’re going to see a rise in the build-a-bear style build-your-own-product-on-a-website and have it manufactured and sent to your door the next day. Imagine the logistical changes that need to take place to make that happen. Internet merchandising companies like cafepress already have a leg up in this department. Their merchandise is manufactured after you order it. Now imagine a product with 10,000 or a million different variations, and the automation that has to support it. Imagine the automation required to manufacture products whose specifications change as fast as fashion trends.

On the software side, we’re going to see every major application support custom 3rd party add-ins so everyone can customize their software so it works for them. I think we’re also going to see a rise in “pseudo-programming languages” that let people who aren’t programmers actually customize their applications in ways that we’ve never let them do before. Platforms that give people the power to build solutions to their own needs are going to flourish, and one-size-fits-all solutions like word processors will fade into obscurity.

So I think we’ll have two options: the vast majority of us are going to spend our time building custom things for individuals or businesses. The successful ones will produce products that people can customize themselves.

· ·

I spend a significant amount of my time these days doing PC programming (as opposed to PLC programming) and I’d say the most time consuming part of my job is following the DRY Principle, aka “Don’t Repeat Yourself”.

The naive interpretation of the DRY principle is that it’s about minimizing the amount of code you write. While this may sometimes be a side effect, this isn’t the point of DRY at all. What we’re trying to do is structure the program so that there’s just one place for everything, and everything is in it’s one place. This is a lot harder than it sounds because no matter how you segment your program into modules, classes, or layers there’s always something that cuts across those boundaries.

Take logging for instance. Every part of the application needs to log things to the same log file. The naive implementation of opening a file, writing a line, and closing it is short but doesn’t follow the DRY principle because we’re repeating this simple sequence of steps all over the place. The danger is that if we change our logging strategy, we now have to change multiple places in every file.

There are probably two ways that the “logging strategy” could change:

  1. We change where (or if) we want to log the data, like to a database instead of a file
  2. We change the kinds of stuff we want to log

We can handle the first case easily by moving the logging logic into a global subroutine, or if you’re more advanced you would use something like a logging service with the service locator pattern. That would let us change where we log the data, and if we include a severity level with the logging interface, we could filter our logging by severity.

The second case is really hard to solve. We have to choose each spot in the code where we want to log information. Maybe every time I catch an error in a try/catch block, but that means every time I write a try/catch block I have to add a call to my logging service. This case violates the DRY principle because the idea is just “every time I catch an error in a try/catch block”. That idea needs to be codified in one place. Ideally I should be able to extend the try/catch block of the language and say, “any time you execute a catch I also want you to do this”. That’s not possible with .NET, that I know of anyway.

Likewise, maybe I want to know every time a user carries out any action that might affect the underlying data in the database, and I’ll have to add logging code at each of those places too. If you have all of your database access going through a single layer in your application, at least you can confine the logging to that layer, but it may consist of dozens of classes representing dozens of database tables. That’s where we need something like the ADO.NET entity framework, and have all of our database entities derive from a single base class, and then we might be able to tie our logging rules in there.

The problem is that these architectural solutions are hard. They take a lot of effort, and when you just need to add logging, it’s too easy to just go through your code and add logging wherever you need it, and you’ve created a maintenance nightmare. It’s the extremely low cost of copy and paste vs. architecture that creates this problem. If you had to pay $1 every time you copied and pasted code, I bet you’d write more maintainable software.

·

Mar/10

30

Phidgets!

I got ahold of some Phidgets on the weekend. These are basically USB I/O devices for amateur robotics, but I’m looking at their use in the home automation space.

Phidgets Interface Kit 8/8/8
They have drivers for lots of operating systems, and APIs for almost any programming platform under the sun.

Getting the I/O connected and controlled from a .NET application was a breeze, including the Interface Kit 8/8/8 and the little R/C Servo Controller. That little servo could certainly move a damper in a heating duct, and they have lots of environmental sensors. The wheels have started turning…

·

Mar/08

2

Software Standards Run Amok

A few years ago I wrote a program for a customer using a flowcharting language.  It wasn’t just a flowcharting language; the product allows you to use both relay ladder logic and flowcharts.  But the customer had a software standard that made the use of ladder logic forbidden!

Imagine a simplified example.  Do you think Bill Gates’ kitchen has a blender?  Probably.  But it’s probably not like the one you or I have.  Maybe it’s made out of solid gold and maybe it has a nuclear power source, but most of all I imagine it has a fully fledged industrial control system.  Now, imagine we’re programming the control system for this blender.

Of course it would have the standard start and stop buttons, but this blender is top of the line and absolutely safe.  It has a sensor to determine if the lid is closed.  Obviously, if we’re happily blending away and the lid flies off, we need to stop the blender, and it shouldn’t start again until the lid is back on and the start button is pressed.  After all, we wouldn’t want to endanger Bill’s fingers or anything (I happen to know he does a lot of blending).

Many of you have already written this complicated control system in your mind:

ladder-logic-for-blender

Good job!  No matter what happens, the lid will have to be closed or the motor simply won’t run.  Of course, the software specification says that you can’t use ladder logic.

Well, in flowcharting the start and stop logic is simple:

 flow-chart-for-blender

That’s pretty simple, but it doesn’t take the lid closed switch into account.  At first glance, we might have to put the check for the lid closed before every decision block, so we check for the state of the lid switch, then check for the start or stop buttons.  Do you see how this could get out of hand quickly?

Fortunately, the language offers a solution:

flow-chart-for-blender-with-exception

How’s that?  While it’s true that if the lid ever comes off, the motor will stop, we have no way to exit gracefully.  This “exception block”, as it’s called, stops whatever you were doing, turns off the motor and starts the whole process over again.  I’m sure it would work fine for our simplified example here, but what if we were doing something else later on in the flowchart?  What if we were tracking parts, or decelerating an unrelated axis?  In the ladder logic example, the lid switch only disables the motor.  In the flowchart it stops the logic and then disables the motor.

Of course, to deal with this problem in the complexities of a real machine, you end up writing two different flowcharts: one for the sequence and one for the outputs.

flow-chart-for-blender-sequence-outputs

Now take a close look at the right hand flowchart.  It scans through both decisions on every single scan of the controller.  It’s “ladder logic written sideways”.  It’s simple combinational logic that screams to be rewritten in ladder.

In fact, writing the state logic (like auto mode sequences) in flowchart and the combinational logic (like manual mode and faults) in ladder makes a lot of sense, especially for more complicated machines.  So why forbid ladder logic?  Perhaps it was just to force people to start using the flowcharts.

A software standard that bans ladder logic is a bad idea.  Some logic is more readable as flowcharts, and some is more readable in ladder.  For years we’ve had to write everything in ladder.  We were like the little boy who only had a hammer and thought every problem was a nail.  If that boy suddenly traded the hammer for a screwdriver, was he any better off?

Theme Design by devolux.nh2.me