C++17: if initialiser

I attended a C++17 presentation by Nicolai Josuttis last year, but at the time, my laptop’s compiler didn’t support any of the features to try them out. After a recent update, it turns out that many are now supported, so I’ve written a few unit tests using GTest.

The first feature I tried was the if initialiser. This feature looks a bit odd at first, because C++ programmers are so conditioned to seeing if statements containing a single condition. Allowing an initialiser statement as well

if ( initialiser; condition )

means that you can initialise a variable and test it on the same line. It also prevents the variable being used outside the scope of the if statement – this prevents accidental re-use if you subsequently mis-type a variable name.

auto return_int()
{
   return 101;
}

TEST( Cpp17, if_initialiser )
{
    // NB we can use i in the body of the if or the else
    // Also, must have a variable name for the object to live in the whole statement
    // (so must name locks taken, even if not used in the body, otherwise it's a temporary).
    if ( auto i = return_int(); i < 100 )
    {
        EXPECT_TRUE( i < 100 );
    }
    else
    {
        EXPECT_TRUE( i >= 100 );
    }
}

TEST( Cpp17, if_initialiser_with_map_insert)
{
    std::map<int, std::string> my_map{ {42, "Hi" } };
    
    if ( auto[it, inserted] = my_map.insert( std::make_pair(42, "Bye" ) ); !inserted )
    {
        // See also StructuredBindings for iterating over a map
        auto& [key,value] = *it; // iterator is pair of key and value
        EXPECT_EQ( 42, key );
        EXPECT_EQ( "Hi", value );
        
        value = "Bye"; // update the value
        EXPECT_EQ( "Bye", my_map[42] );
        
        // key = 43; // compile error! - cannot assign to const key-type
    }
}

See also next post on C++17 Structured Bindings.

1 Comment

Filed under C++, C++ Code, Programming

Book Review: The Lost Fleet – Valiant, Jack Campbell

This book follows the same template as the other Lost Fleet books that I’ve read. We travel with Captain “Black Jack” Geary on Dauntless, the flag ship of his fleet, as he attempts to steer his people home after a damaging series of battles. This episode is more optimistic, the fleet is performing well in battle and Geary’s efforts to bring a humane change in culture to the personnel is succeeding (they rescue stranded enemy civilians who had been abandoned on an outpost planet). However, he still faces the growing threat of hidden enemies within the leadership who are still trying to overthrow him. Geary confronts the fact that he cannot continue to court Co-President Victoria Rione now that his growing feelings for Captain Tanya Desjani are obvious to everyone in his crew.
Three stars

Leave a comment

Filed under Book Review

Book Review: The Fix, David Baldacci

TheFixI really enjoyed the first in David Baldacci’s Amos Decker series, so was looking forward to this one. Unfortunately, it wasn’t at the same level – a completely implausible plot, combining industrial espionage with an international spy ring, terrorism and family betrayal.
TwoStars

Leave a comment

Filed under Book Review

IET Turing Lecture: Innovation and Technology – Art or Science

This evening at the IET was split into two lectures, the first by Larissa Suzuki entitled “Brave New Smart World”. Larissa covered a lot of ground, scaring the audience with figures on our over-population of the planet, over-consumption and lack of recycling. Then she showed how we may have potential to engineer our way out of these global problems – with smart cities, self-driving cars and smart-recycling.
Quote of the Day:

You cannot jujitsu your way out of bad data


The main Turing Lecture was by Andy Harter, who among other things invented VNC (used for connecting to remote computing devices). The stated intention of the lecture was to make the audience think about whether innovation and technology owe more to Art or Science. The lecturer admitted that his hope was that we’d agree that both are necessary. He covered a number of facets that he believes are the ingredients behind the best inventions: Creativity, Necessity, Storytelling, Timing, Retrospection, Observation, Laziness, Simplicity, Responsiveness and Generosity.

If necessity is the mother of all inventions, laziness is the father!

This quote was quite pertinent to the speaker, who invented VNC so that he didn’t have to leave his office to help a colleague down the corridor with issues on his machine!

Leave a comment

Filed under Meetup

Book Review: The Closers, Michael Connelly

I bought this book from a charity book shop, so it could have come anywhere in the timeline of the Harry Bosch series. I was quite amused that this one heralds Bosch coming out of retirement to work in the Open-Unsolved Unit of the LAPD – the last book that I read in this series was when he came out of retirement after he’d left the Open-Unsolved Unit!

Bosch and partner Kiz Rider are assigned to investigate the murder of a schoolgirl many years before. The case is being reviewed in the light of DNA evidence – they hope that blood on the murder weapon will lead them to the killer. As might be expected, they witness the devastating effect the crime had on the girl’s mother and father. The mother’s life is on hold years later, waiting for resolution. The father has lost his career and is homeless – but Bosch tracks him down. He finds that the man blames himself for letting his daughter down, having been scared off from asking questions about the investigation by senior members in the LAPD.

Whilst the investigation necessarily follows the car mechanic whose blood was found on the gun, the investigators know that he may not be the killer. They need to link him to the girl somehow – probing attendance at the same school or overlapping social circles in the town. Yet, none of the girl’s friends recognise the man.

Four Stars

Leave a comment

Filed under Book Review

Book Review: The Midnight Line, Lee Child

This is the 22nd book in Lee Child’s Jack Reacher series and it continues where the 20th book, Make Me, finished. Any hope that Reacher’s collaborator in the previous book, Michelle Chang, would feature again were immediately dashed – but Reacher does work with an ad- hoc team in this one, and those tend to be the best of his adventures.

The premise of the book is that Reacher sees a small West Point ring in a pawn shop and decides to track down the (presumed female) owner and return it to her. Being an alumni himself, he feels a duty to help someone down on their luck. He allies himself with a detective, Terry Bramall, who also happens to be looking for the owner of the ring – employed by the beautiful sister of the owner. Finding the woman is only the beginning – the issues causing her to pawn the ring (battlefield injuries and drug addiction) are far harder to solve.

The next book in the series will be called Yesterday.

Four stars

Leave a comment

Filed under Book Review

ACCU Meetup: Code Craft

Jason Gorman of CodeManShip gave an interesting talk on code craft this week. The talk began with the business case for Code Craft, based on the cost of changing a line of code. If you compare the number of changes in source code repository to the expense of their development teams, the cost generally increases massively over time – 40X more expensive per line of code change after 8 years for one company. The same hockey-stick chart appears in Kent Beck’s book “Extreme Programming Explained”. Code Craft skills tend to flatten the cost-of-change curve, which is good for the business, and make the code easier to change, which is good for the developers.

Code Craft Skills

Write good unit tests, use version control, do continuous integration, apply design principles, refactor code safely.

Cost – if the cost of a change in design is 1, then the cost in implementation is 6.5, in testing is 15 and in maintenance is 100.  Bringing testing forward in the development process gives a massive return on investment.  Legacy code can be defined as any code that doesn’t have fast running, automated unit tests that can discover a bug quickly – enabling a cheap fix.  You must automate testing and enable the feedback loop to iterate quickly – ideally in minutes or seconds.

Readability – 50%-80% of time spent on a codebase is reading code, not writing it.  Making code easier to read and understand has a great pay-off.  Code that’s hard to understand is easy to break.

Complexity – attack complexity, try to replace it with the simplest thing, which is less likely to be wrong.

Duplication – never copy/paste code, especially off the internet!  You have no idea if it works or even compiles.  Making changes to common logic is multiplied if there’s duplicate code.  Duplication is the opposite of reuse – generate an abstraction to help improve the design.  Duplication can be hard to spot (e.g. customer playing several roles which could have been parameterised).

Ripple Effect – a change to one area of code breaks a much wider circle of code.  Cost of change greatly increased – need to have a local effect from a small change to code.

Principles of Clean Code

The speaker also coaches teams in the following principles:

1. Shorter feedback loops – automated unit testing.  Not possible with manual testing iterations or a manual testing phase.  Automated system testing can give good coverage, but is often too slow, can take hours to run.  Need to run in minutes or seconds.  Ideal chain is Unit Testing -> Integration testing -> System testing.  Want most of the testing in first layer, minimal number of smoke tests in the top System layer.

2. Simple Design – the code works, clearly reveals intent, free of duplication, made out of simple parts.  Need another pair of eyes to check the code is easy to read.  Code review your own code every few minutes.

3. Single responsibility – traditionally, this is taught as classes should only have one reason to change.  Or better, look at the number of combinations of the sections of code implemented in a function – it’s more powerful to break functions into smaller parts then use composition to implement the larger function.  Smaller components/functions => many more ways to re-use. So give each piece of software a single responsibility.

4. Tell, don’t ask – lots of low-level coupling between objects. Better to have objects sharing smallest possible interface to each other. Don’t pass the whole object – pass the data needed to do the operation.  Put the work where the knowledge lives – do the work in the right place so that data and behaviour belong together.

5. Dependency Inversion – you should be able to swap your dependencies.  Talk to dependencies as abstractions through interfaces.  Eg1 all commands inherit from ICommand and high-level components work on generic interface, not concrete classes.  Eg2 VideoRental example, rather than coupling to Imdb, replace with an interface.  Better for mocking/testing as well.

Leave a comment

Filed under Meetup, Programming