The affair of the C# bang bang - !! - operator

A programming language is like any other language. It must evolve over time to reflect the ways that it is used. One of the things I love about C# is how it has grown over the years. One of the latest changes is the addition of a !! operator (otherwise known as the “bang bang” operator). This is causing a bit of debate, which is great because changes to a programming language should always be made on the basis of a proper discussion. But you might be wondering what all the debate is about. So here’s a quick explanation of what is going on.

C# has always had methods. A method is a thing you can ask an object to do. For example, you might have an object which you can ask to serve a drink:

barkeeper.serveBeer();
barkeeper.serveCoffee();

Then you might decide that rather than have a lot of different methods for different kinds of drink it would be easier to make a method that accepts an argument that tells it the kind of drink that is required:

barkeeper.serveDrink("Beer");
barkeeper.serveDrink("Coffee");

The serveDrink method can look at the value of the argument and decide what to do:

void serveDrink(string drinkName)
{
    // test the name and make an appropriate drink
}

So far so sensible, although we have made things slightly easier in one respect (we can use serveDrink method to serve any drink rather than having to make lots of methods) by making things slightly more difficult in another (the serveDrink method has to decide what drink is to be made and what to do if a matching name is not found). For example, what should happen when the following code runs?:

barkeeper.serveDrink("BEER");

The above code is asking for a beer, but the name is all capital letters. Does the method deliver a "Beer", or does it fail with an error. If it fails with an error, how does the user of the program know that an error has occurred? At this point we have to invent a convention for our application. We might say that the serveDrink method will throw an exception if it is given a drink type it doesn't recognise. That's fine as long as the behaviour is documented so that users of the method now how to use it.

But what about bang bang? I hear you ask. The operator is intended to make life easier for programmers by automating the handing of null references. Consider what would happen if someone did this:

barkeeper.serveDrink(null);

This code will ask for a drink but provide a null reference as the drink description. A null reference is not the same as an empty string, it is a reference that points to nothing. This is like asking the barkeeper for a drink and then falling over on the floor before you tell them what you want. An attempt by the serveDrink method to use this null reference will result in the method failing in some way.

Naughty hackers love this kind of situation. They might discover that asking for a null drink causes the serveDrink function to crash just after it has opened a bar tab, so that they can then continue to order drinks for free. They might find it serves out the most expensive drink in the bar.

As the person who is writing the serveDrink method you don't want anything like this to happen. So in the method you add a test to make sure that the argument is not a null value:

void serveDrink(string drinkName)
{
    if (drinkName is null) {
        throw new ArgumentNullException(nameof(drinkName));
    }
    // test the name and make an appropriate drink
}

The first thing this serveDrink method does is check to see if the drinkName is null. If it is null an exception is thrown which exits the method instantly. This exception may or may not be handled by the caller, that is up to them. However, we have made sure that the serveDrink method won't do anything stupid if given a null reference. (of course we now have to worry about the issues that might be caused by this method throwing an exception thougth - welcome to the world of error handling).

What the bang bang operator does is make the above test for us automatically.

void serveDrink(string drinkName!!)
{
    // test the name and make an appropriate drink
}

In this verson of the code an exception is thrown if drinkName is null. I don't have to remember to add the call. This might make my programs slightly safer. But it also means that readers of the code need to understand what !! means in this context. They might look at it and think that the drink is very important, or hot, or something else. They might not know what it does and add their own tests for null which don't do what they expect. Hence the debate.

My opinion? I split language features into two categories. Cake and icing. This is definitely icing. I'd never use it personally, as I like my error handling code to be very visible to someone reading my programs. Plus I don't like situations where readers need to know "special stuff" to make sense of what they see. However, it's not a thing I'd stress about too much either way. I just love the way that C# is still striving to move forwards.

You can find out more about this proposal and the debate here.

Say hello to the Three Headed Programmer

I’m playing with some ideas for the introduction to an update of the C# Yellow Book. I don’t want people to end up thinking that a developer writes programs. I think a good one does a lot more than that:

The Three Headed Programmer

I like to think of a developer as having three heads. I think that to be a good developer you should be capable of wearing any of these heads, although you will probably be better with one head or another. If you are working in a team, you might find that team members gravitate towards one particular head, but everybody should know what the heads do. The heads are:

The "Find out what is wanted" head

This head is friendly, approachable, and constructive, but not above asking hard questions about what should really happen or why something is being done the way it is. This head is good at writing things down and then showing them to people to make sure that everyone agrees what is being made. It has a twin - the "This is what I'm going to build" head which is used when you are making something for yourself.

When you first start programming you don’t use this head very much because the things that you do are set out as exercises for you to have a go it. However, if you can get good with this head it will vastly improve your usefulness as a developer.

The "Make something that works" head

This head is good with technology. It can take the problem definition from the first head and build a solution using software and hardware. Making it work might involve creating an overall design, breaking things into components and then making each component in turn. For a large development this head might have to assemble and manage a team of people. Testing will form a big part of the process; this head is very keen to be able to prove that it has made something that works. This is the head that most people think developers wear all the time. I think it is the hardest head to learn to use because when you are learning program it is very difficult to know where to start when confronted with a problem and asked to make something that provides a solution.

The "Make it good" head

This head is a bit of a worrier. You might think it comes into play once the "Make something that works" head has finished but this is not quite how it works. This is a head that you pop on every now and then to look at how things are going. It's the one that asks the hard questions when finding out what is wanted. It's also the head that looks at a solution and worries about things like reliability (are there things that can go wrong), security (can the system be successfully attacked), scalability (what happens if we get lots of users) and business (can we be sure we are going to get paid for all this). This head really wants to make something good, but it also has a sense of perspective and is happy to negotiate what "good enough" means, as long is that is written down and everyone agrees about it.

In a team the heads can turn into different roles for team members. Whatever happens I think it is really useful if a developer stops every now and then and thinks “I wonder what my other heads would think of this?”.

Thermal Camera Meetup next week

We’re holding our first in-person meetup event of 2022 next week at the Makerspace in Hull. At this event we are going to take a look at what a thermal camera can do for you. Brian has got one running into a Raspberry Pi and has been doing some tests.

Of course we’ll be bringing along other bits of hardware to talk about and you are welcome to bring yours too.

Red Nose Day 2022 Lecture in Rhyme is go!

If you’d told me thirty years ago that I would still be doing Red Nose Day lectures in Rhyme in 2022 I’d have said “Who are you?” and “Why can’t you tell me anything useful like ‘Buy Google Shares’?”

But that’s by the by. I’m doing it again, sooner than I expected. For now, just make a place holder in your diary and get ready to flex your wallet a bit. This time I’m going to tell you some Genuinely Useful stuff about how the web works. You don’t need to know how to program, or anything much about computers. But by the end you’ll know a bit about how the web works, have played a silly game and heard more cheese puns that you really want to.

Keep coming back to here and I’ll update you with progress, including the all-important link where you can donate your socks off.

Print over Bluetooth using an ESP-32

Not bad for around twenty pounds

The thermal printer I ordered a while back has arrived. I’ve been playing around with it. What I want to do is control the printer over Bluetooth from an ESP-32 device. Then I can see about getting an ESP-32 with a camera and getting pictures off that and into the printer. First thing I did was fire up BLE Scanner for the iphone and take a look at the services provided by the device. I used this to send some ASCII codes to services I thought might work (you can do this with the program - it’s great fun) and managed to get the printer to print out “hello”. Which was nice.

Then I went to the source code for my Furby Bluetooth connection program and modified it to use the services that the printer supports and managed to make that print “hello” too.

Then, as I was rolling up my sleeves to start building the printer control software it dawned on me that someone else might have done this before. And someone has. He’s called Larry Bank and you can find his splendid library here. I had to make one tiny change to his code. My printer has the name “MPT-II”, which was not on the list of the printers supported by the driver. I fixed this (in a way that I’m not particularly proud of) by editing the file Thermal_Printer.cpp in the src folder for the library installation and changing the first printer name in the list to MP-II. It was on line 59 of the file in the version I was using.

const char *szBLENames[] = {(char *)"MPT-II",

It works a treat. The library is very comprehensive. It can do different sized text, barcodes and even print images. The next thing to for me do is to get an ESP-32 device with a camera and discover how to get images off it. However, if you have Arduino app which you just want to use with a printer this is a very self-contained, cheap and portable way to do it.

How to write a technical book

So, I’m loitering on this forum and Tamás was asking if anyone had any tips for first time technical writers. I sent an email response and then I decided that the whole world should have the chance to read my words of wisdom…..

I’ve written a few books over the years. I can confirm that it is not a way to get rich, but at least it is a hobby that doesn’t run at a loss. I’ve self published and used a publisher. 

  • It is surprising how many typos get through when you self-publish. You have to work really hard (and show your text to loads of people) to get the same level of mistake detection as you get from a good copy editor.

  • A good technical editor adds a huge amount to a text. If you are self publishing see if you can persuade someone to take this role. Perhaps offer to pay them with a signed copy of the book. Or a nice piece of cheese.

  • Lots of pictures can make your book file large and unwieldly, but to the reader opening a book and seeing a pair of pages of dense text can be a bit demoralising. Settle for diagrams and cropped screenshots that might be less version sensitive.

  • Don’t be afraid to talk directly to the reader. When I started out I tried really hard to put things into the third person for no good reason. It’s painful and people don’t like to read it. Address the reader as “you”. Have a conversation with them. And for projects you can say “We are now.....”

  • Never say something is easy. It trivialises the point and makes the reader feel stupid if they don’t understand it. Instead tell folks how powerful the technique is and how useful it will be once they get it.

  • Context is key. Don’t tell the reader how a for loop works, tell them the situations in which a for loop would be useful, with a side order of when not to use them and how they can go wrong.

  • Readers love narrative. If you can make the text into a story or journey that will be a huge win.

  • Round things off at the end and provide a trajectory for the reader to take what you’ve told them and go further.

  • Use verbs in chapter titles – “Make a whatnot” is a quick way of setting a context. Just giving the name of a tool or technique as a heading won’t help the reader as they don’t know what it is. If you want to name the technique say “Make a whatnot with a whatsit”

  • Treat your first pass of the material as the “ore” that you you’ve mined. You then have to refine it into the finished content. Don’t be afraid of making huge changes at this point. You might have to rearrange or dump large sections until it feels right. I find that I have to “go and live” in a chapter for a week or so until I’m happy with the sequencing and content.

  • I went to a session about writing a long time ago and they talked about “Killing your favourite children”. By that they mean that you might have a chunk of text that you really like the look of, but it doesn’t really fit the context of the piece that you are writing. In that situation you need to dump the text that you love.

  • Never really throw anything away. I keep a folder called trash where I put stuff that didn’t fit (see above). Maybe it will come back as a blog post or in a different section.

  • Look at writing tools. I’m playing with something called Scrivener (https://www.literatureandlatte.com/scrivener/overview) which I quite like. It makes it very easy to organise and sequence elements (which can be given separate synopsis sections). It also has very advanced output options where the same text can be compiled to generate different output formats. I’m hoping that it will make it easy to make epubs, word documents and html pages. It’s looking promising so far...

  • Treat what you have written as collateral that you can always find an outlet for. This email is going to turn into a blog post 😊 - and it did

Happy Flying with Microsoft Flight Sim

we think this plane is definitely happy

Going flying is now a big social thing in our house. Three of us go flying together once a week and on weekend afternoons we get together over coffee and then go for a flight using the TV in the living room. Today we took a flight round Australia, what with the new landscape pack just having been released. They keep on about this “metaverse” thing. I think bits of it are already here.

Stop your glasses fogging up when you wear a mask

I don’t see wearing a face mask as anything to do with personal freedom. To me it is more like a way of not killing myself or others around me. But if you wear glasses a mask can be a bit of a pain because a mask makes them steam up.

Chris told us that these work really well. So we got some and yes, they are awesome. You have to make sure your glasses are clean and then use the cloth to apply whatever chemical magic repels water vapour. The coating lasts a day or so and the instructions say that the cloths are good for lots of applications. We’ll see about that, but for now they are working a treat. Recommended.

How not to migrate Animal Crossing island data

Home sweet home

I’ve just got a new Nintendo Switch. I’m in the process of selling a bunch of stuff from the loft that I don’t need any more and I reckoned I could raise the price of a new OLED one. I got it today and it is lovely. The screen is really impressive.

Moving your settings from one Switch to another turned out to be one part smooth process and one part white-knuckle terror ride. It started well enough. Once the new switch was online I was able to authenticate using the phone and I was asked if I wanted to copy all the saved games and settings from one device to another. “Yes please” I replied and progress bars grew and shank. At the end of it I was asked if I wanted to delete my Nintendo identity from the old device. I said yes, because it is going on sale to pay for the new one. Feeling rather smug at how well that had all gone I then loaded Animal Crossing into the new device and opened up my little island.

It wasn’t there.

And I’d just disconnected myself from the old device. I really thought I’d lost everything I’d built up over hundreds of hours of gameplay. I didn’t know (although I should really have worked out) that Animal Crossing saved games are managed outside of normal game saves. So my island was still on my original old Switch. But could I get back to it? It turns out that I could. I re-registered myself on the old Switch, opened up Animal Crossing and was then given a chance to claim my island data which had been left lying around on the device - presumably to deal with situations like these. I was then able to use the Island Transfer tool to move the island from my old Switch to my new one, and that worked a treat. I can now wander around picking up weeds in splendidly sharp colour.

The takeaway from this is to use the Animal Crossing transfer tool if you are moving your island from one device to another, don’t expect the device transfer process to do it for you. I’m impressed that you can recover from the situation; but I’m rather annoyed that I had to do it in the first place. If at any point I’d accepted the offer to make a new island I dread to think what would have happened. I’d have lost the lot. A prospect that felt a lot more scary than it probably should be, what with nothing particularly real being involved. I really hated the idea of losing all the digital chums that I’ve made over the years, to say nothing of all the digital loot that I’d accumulated.

Making videos with OBS and Camtasia

After many years of trying, I think I’ve finally found a decent workflow for making videos. I’ve always loved Camtasia for making screencasts but I really like the flexibility of OBS for getting video onto my computer. So now I use both. The only thing I needed to do for it all to work was to go into File>Settings in OBS and change the video recording format to mp4:

Once I made that change I could import my recording files into Camtasia. It asks me if I want to use 60Hz video for the project (oh yes I do) and then lets me get on with formatting the video, adding captions, sorting out the audio and finally uploading it straight to YouTube. OBS is free and Camtasia has a really generous free trial period. If you are thinking about making some videos these two tools are a great way to get started.

Full disclosure: Tecksmith were kind enough to give me a copy of Camtasia to play with as part of my Microsoft MVP award. But I’d been using Camtasia and liking it in my day job for a good while before I got the freebie.

Whatever happened to MouseTrap?

You know how old people are supposed to get cross about change? Wellllllllll.

They’ve changed the MouseTrap board game. The new one doesn’t let you eliminate other players by catching them. Instead you collect portions of cheese or something. Most unimpressed. I see this further evidence of the continuing decline of civilisation etc etc.

My advice: seek out the original and best. Proper sudden death action.

Upgrade your Circuit Python version in the Raspberry PI PICO

My first version of the PICO MIDI Cheesebox used Circuit Python 6. And it worked fine. But I thought I’d upgrade to version 7. This turned out to be harder than I anticipated because of my less than stellar hardware design. The Raspberry PI PICO that I use to control the CheeseBox is locked inside the case with no access to the all-important BOOTSEL button that you hold down during power on to force the device into firmware upload mode.

However, the good news is that you can use a couple of Python statements to get your PICO to reboot into firmware mode so that you can drop in a new version of Circuit Python (or anything else). You can issue the commands down the terminal connection. I used the Thonny program which provides a REPL connection to my Circuit Python powered CheeseBox (or Crackers Controller).

microcontroller.on_next_reset(microcontroller.RunMode.UF2)

This is the first command you type in. It tells your device to reset into UF2 mode next time it is reset.

microcontroller.reset()

This is the second command. It resets the device and makes it appear as as storage device into which you can load the firmware. Note that if you do this you will wipe the contents of your PICO so make sure that you copy anything important off it first.

I’ve upgraded the firmware for the CheeseBox on GitHub to Version 7. You can find it here:

https://github.com/CrazyRobMiles/PICO-MIDI-Cheesebox

Tax Paid

I’ve done my tax for the year. Just six days before the deadline. Go me. Now, if you’ll excuse me I’ve got some crying in the corner to catch up on…

It didn’t used to be this way. I was happy to pay may tax and watch things around me get better and better. But to think of the possibility that some of my cash is being used to fund the incompetence and maliciousness that passes for government these days is rather upsetting.