Category Archives: Programming

Tech Book: Swift for the Really Impatient, Matt Henderson & Dave Wood

SI love the title of this book, the authors kept the content as concise as possible and showed that it really is possible to give a decent introduction to a programming language in just 156 pages (and less than 1cm). The book is quite practical you can read it cover-to-cover to pick up the features of the language, then you can use the handy code snippets as a quick reference guide (and the index is pretty good for this too, not always the case).

I bought a 2015 edition, the only downside being that this seems to be aimed at Xcode 6 and is now slightly out of date. With Swift being an evolving language, that’s to be expected – some readers might prefer to work with the electronic copy and remain up to date.

It’s also worth mentioning that, if your aim is to write a simple iOS app in Swift, you might be better off working through a tutorial and learning Swift that way, along with picking up tips and tricks for working with Xcode. See FoodTracker and To Do.
Five Stars

Leave a comment

Filed under Programming, Swift, Tech Book

Scott Meyers – Good to go

I just read that Scott Meyers has announced he is stepping back from active involvement with C++.   I’ve been a big fan of Scott’s work, I attended his C++ training sessions at DevWeek, London in the late 90’s, and I’ve read his Effective C++|More C++|STL books – except for the most recent one, his take on Effective Modern C++. My copy is now on order. 

Leave a comment

Filed under C++, Programming

How to upload iOS App onto iPhone

XcodeI’ve been working on a hobby project for a while, learning Swift and gaining some experience of iOS App development. I reached the stage where the app was worth testing on my iPhone, but found that my version of Xcode (an early v7 beta) required an Apple Developer Licence!

Fortunately, it turns out that upgrading to Xcode 7.2 meant that I could upload to my own phone simply by providing my Apple ID. The upgrade was much easier than I had expected, compared to the number of bad reports on the internet. I used the App Store to upgrade, maybe it’s harder if you download and install the application directly.

Next, I had to find out how to install an application on my device from Xcode. First, connect the device to the Macbook and it will appear in the device list in Xcode above the simulated devices (i.e. all the iPhone and iPad models). Selecting the device by name and clicking run kicks off a full install and runs the app on the phone.

The final question was how to configure my phone to allow apps written by me to run – this was answered on the Apple Developer Forum, and is simply a matter of becoming familiar with Settings -> General -> Profile / Developer App.

I’m impressed by how well Xcode has automated this process, I’m sure a lot of work has gone into making installation onto a device a positive developer experience.

Leave a comment

Filed under Programming, Swift

How to write generic, duck-typing code in F#

When writing generic code in C++, it’s easy to imply constraints in the generic type when developing a template. For example:

template<class T> 
class Announcer{
public:
	static void announce( const T& t )
	{
		std::cout << "And now from " <<  t.country << ", we have: ";
		bool first = true;
		for ( auto person : t.people )
		{
			std::cout << person;
			if (!first) std::cout << "\n";
			first = false;
		}
	}
};

Here, we’re assuming that T has two properties, ‘country’ and ‘people’, with the latter being enumerable (i.e. supports begin/end methods and iterators). This is one of the attractions of C++ for generic code – although, in the future, concepts will enable you to document the constraints in order to make it easier for developers to use your library, and for the compiler to give clearer errors.

What about something similar in F#? I found Tomas Petricek’s post from StackOverflow very useful.

type IHasCountryProperty =
    abstract Country : string

type Announcer<'T when 'T :> IHasCountryProperty>( item : 'T) =
    member this.Announce() =
        printfn "And now the party from %s" item.Country

let inline countrifiedItem<'T when 'T : (member Country : string)> (item : 'T) =
    {
        new IHasCountryProperty with
            member this.Country = (^T : (member Country : string) item)
    }

type London() =
    member this.Country = "England"

// Use it
let city = London()
Announcer( countrifiedItem city ).Announce()

The Announcer class uses a member constraint with statically resolved type parameters which bind to the Country property. Then, the inline static function ‘countrifiedItem’ uses static member constraints to capture the existing Country property on any other type, even if like ‘London’ it doesn’t support the IHasCountryProperty. The consensus seems to be that this approach is encouraged because it documents the requirements on ‘T in an interface.

Leave a comment

Filed under C++, C++ Code, F#, Programming

Regex – concrete use cases

This post by Eric Miller gives 5 use cases for regex.  As per his introduction, I’m only an occasional user of regex, but it’s one of those skills worth learning.

I’ve found knowing some basic regex to be extremely useful in my day-to-day work. So few things pay off such good returns for so little time invested, and I wish I’d learned it years ago

Leave a comment

Filed under Programming

ACCU Meetup: Quicker Sorting, Dietmar Kühl

Meetup - Quicker SortingI was lucky to get an invite to this month’s ACCU London meet-up on the topic of sorting. Dietmar Kuhl hosted the presentation at the plush Bloomberg offices on Finsbury Circus. The talk brought together a sample of approaches to speeding up QuickSort:

  • insertion sort
  • sentinel partitioning
  • hand-rolled sorting for small collections

Overall, these changes (and others) made an impressive improvements, such that the combined algorithm rivalled std::sort for sorting std::vectors of integer. However, the algorithm wasn’t as competitive for other important element types such as std::string.

Dietmar intended the talk to be accessible to all, rather than an in-depth presentation using advanced C++ techniques. I think it was a good example of how you can iterate and bring in multiple techniques to optimise an algorithm for a specific use case.

Leave a comment

Filed under C++, Meetup, Programming

How to define an interface with overloaded methods in F#

In F#, it’s possible to write both object-oriented and/or functional programs.  This means that a task that would be straight-forward in C++, defining an abstract interface containing overloaded methods, is also possible in F#.  However, you have to get the syntax exactly right, otherwise you get obscure compiler errors which could mis-lead you into thinking it isn’t possible after all.  For example, to use overloads, you must define multi-parameter methods using tuples.

type IBlog =
  abstract Write : DateTime * string * string -> IBlog
  abstract Write : string -> IBlog

type MusingStudio =
  interface IBlog with
    member this.Write (entryDate : DateTime, subject : string, body : string) =
      // publish blog entry
      (this :> IBlog)

    member this.Write (subject : string) =
      // automatically generate body and publish (!)
      (this :> IBlog)

Note the syntax of the abstract method declarations carefully.  As per this helpful post on StackOverflow, putting brackets around the tuple changes the signature and leads to confusing compiler errors:

type IBlog =
  abstract Write : (DateTime * string * string) -> IBlog // don't do this!
  abstract Write : string -> IBlog

Whilst it’s possible to implement the interface above and call into it, the syntax to do so involves additional brackets and is unnecessarily clunky.  The syntax at the top of this article is preferable:

let blog = WordPress( "MusingStudio") :> IBlog// create blog
blog
.Write( "How to overload in F#" )
.Write( DateTime.Now, "Book Review: Make Me, Lee Child", "Is this the best Jack Reacher so far?")

Leave a comment

Filed under F#, Programming

ACCU: Overload 127 (June 2015)

Overload127CoverCatching up on back issues of ACCU’s Overload magazine from June 2015, a couple of articles are worth mentioning for future reference:

  • Terse Exception Messages by Chris Oldwood.  Here,  Chris relates his experience of unnecessarily long debugging sessions due to limited error information in exception messages.  Often, this is due to laziness on the part of the programmer, sometimes because they expect to refactor a block of code soon and will come back to “do the error handling later” – then the refactoring never happens.  I see this as a false economy – even during unit testing, having proper error messages in exceptions can speed up your own debugging.
  • Get Debugging Better by Jonathan Wakely.  Here, Jonathan lists a few tips for using GDB effectively, aimed at programmers like me who typically use an IDE.

Leave a comment

Filed under Programming

Software bug causes prisoners’ early release

BBC News reports that 3200 US prisoners were released early over a 13 year period due to a software bug.  It’s hard to fathom how this could have been released in the first place, how it remained undetected for so long, and finally why it’s taken so long to fix.

The bug miscalculated the sentence reductions prisoners in Washington state had received for good behaviour.  It was introduced in 2002 as part of an update that followed a court ruling about applying good behaviour credits.

Ok, we know that there’s always room for mis-interpretation of requirements when developing software, and every program needs some period of user acceptance testing.

The Washington Department of Corrections (DoC) added that it was made aware of the problem in 2012 when the family of one victim found out that the offender was getting out too early.

Huh? It took ten years for someone to notice? The average mis-calculation was 49 days and a maximum of 600 days – and it wasn’t noticed? What sort of testing did they do – surely some worked examples were provided?

Despite this, the faulty software was not corrected until a new IT boss for the DoC was appointed, who realised how serious the problem had become.

This is the crux of the matter – if you’re writing mission-critical software, you have to test accordingly. Here, prisoners released early may have committed further crimes – that’s a hefty penalty that could have been avoided by professional software practices: code reviews, test coverage analysis, user acceptance testing.  Surely some regression data tests existed when they were releasing the upgrade – someone must have signed off that all these differences were fine “because the rules have changed”.  Yes, but not by that much!

Mr Inslee said he had ordered the DoC to fix the software as quickly as possible.   An update that applies the correct formula for calculating sentence cuts is due to be in place by 7 January.

Let’s hope they’ve thoroughly reviewed their test coverage now and that the release goes smoothly.  Also, they should review any other software developed by the same team in that 2002 period, it’s unlikely to be an isolated mistake.

 

Leave a comment

Filed under Musing, Programming

ACCU: CVU magazine 266

Catching up on back copies of ACCU’s CVU magazine, there was plenty of good material in January 2015’s edition.
CVU Jan 2015

  • Simplicity Through Immutability – Chris Oldwood provides a worked example of the benefits of introducing an immutable type. The example is pretty simple, but experience with F# shows that this approach frequently simplifies logic (most of the time without noticeable performance penalties)
  • Delayed Copy Pattern – Vassili Kaplan compares ways to push huge objects into an STL container, with timings showing that a delayed-copy wrapper is comparable in performance to emplace-back (and the wrapper can be used for older compilers)
  • Standards Report – I was particularly taken by Mark Radford’s note on Operator Dot. At first sight, it could be dismissed as a typical C++ programmer’s wish to overload any operator available, which is currently prohibited for operator dot. However, Bjarne Stroustrup himself is named on the paper, and the motivating case is for ‘smart reference’ classes.
  • Scott Meyers Interview – more than just a subtle book plug, gives an insight into Scott’s introduction to programming and C++.

[The links to CVU articles are accessible to ACCU members only]

Leave a comment

Filed under C++, Programming