Mutable structs in C#

Frances Buontempo from BuontempoConsulting

We know what this does, right?

    struct Pricer
    {
        public double Price;
        public long Size;

        public void AddExecution(long lastSize, double lastPrice)
        {
            Price = (Price * Size + lastSize * lastPrice) / (Size + lastSize);
            Size += lastSize;
        }
    }

    class PriceData
    {
        public Pricer pricer;
    }

    class Program
    {
        static void Main(string[] args)
        {
            Pricer price = new Pricer{Price = 0.0, Size = 0};
            for (int i = 0; i < 5; ++i)
            {
                Console.WriteLine("{0} {1}", price.Price, price.Size);
                price.AddExecution(1, 2.5 * (i + 1));
            }

            for (int i = 0; i < 5; ++i)
            {
                Console.WriteLine("{0} {1}", price.Price, price.Size);
                price.Price= 2.5 * (i + 1);
            }

            PriceData priceData = new PriceData();
            priceData.pricer = price;
            for (int i = 0; i < 5; ++i)
            {
                Console.WriteLine("{0} {1}", price.Price, price.Size);
                priceData.pricer.AddExecution(1, 2.5 * (i + 1));
            }
       }
    }

Eric Lippert tells us about mutating *readonly* structs: http://blogs.msdn.com/b/ericlippert/archive/2008/05/14/mutating-readonly-structs.aspx but even non-readonly structs can get us in a mess.

Pdb ftw

Frances Buontempo from BuontempoConsulting

pdb - python debugger

If a script throws an exception, try running it in the debugger
python -m pdb myscript.py
For example given the following (rubbish) python program
C:\Dev\src>cat bad.py
def naughty():
raise Exception()
naughty()

if we just run it the exception tries to escape ...
C:\Dev\src>python bad.py
Traceback (most recent call last):
File "bad.py", line 4, in <module>
naughty()
File "bad.py", line 2, in naughty
raise Exception()
Exception

So, we know what line the problem's on. We could change the script to see what's going on using
import pdb; pdb.set_trace()
or we could run it under a debugger.

Run script through debugger

Invoke the pdb module in python and send it your script, e.g.
python -m pdb bad.py
This gives a (Pdb) prompt to type instructions in to:
> c:\dev\src\bad.py(1)<module>()
-> def naughty():
(Pdb)
Type 'c' for continue - it will halt when it gets an exception, as follows
(Pdb) c
Traceback (most recent call last):
File "C:\Python27\lib\pdb.py", line 1314, in main
pdb._runscript(mainpyfile)
File "C:\Python27\lib\pdb.py", line 1233, in _runscript
self.run(statement)
File "C:\Python27\lib\bdb.py", line 387, in run
exec cmd in globals, locals
File "<string>", line 1, in <module>
File "bad.py", line 1, in <module>
def naughty():
File "bad.py", line 2, in naughty
raise Exception()
Exception
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
> c:\dev\src\bad.py(2)naughty()
-> raise Exception()
(Pdb)
At this point
 (Pdb) p <variable_name>
can be used to inspect variables, and
 (Pdb) a
shows any arguments to a function.

Main Pdb commands

Type 'q' for quit, 's' to step (maybe into another function) or 'n' to move on to the next line.
'w' shows where you are in the stack, 'u' moves up and 'd' moves down.
b(reak) [[filename:]lineno  sets a breakpoint.
There are more details in the manual: http://docs.python.org/2/library/pdb.html

Virtual functions in constructors and destructors

Frances Buontempo from BuontempoConsulting

Interview question.

What does this do?

class Base
{
public:
Base()
{
log();
}
virtual ~Base()
{
log();
}

//virtual void log() = 0;//note this compiles but doesn't link
virtual void log()
{
std::cout << "Base\n";
}
};

class Derived : public Base
{
public:
Derived()
{
log();
}
~Derived()
{
log();
}
virtual void log()
{
std::cout << "Derived\n";
}
};

int main()
{
Derived d;
}

I half remembered this http://www.artima.com/cppsource/nevercall.html so wasn't sure.

Review of Overload "editorials"

Frances Buontempo from BuontempoConsulting

I have run Charles Stross' code over my Overload "editorials" in the hope of generating some kind of end of year review. Any favourite phrases anyone?
 
---

the incoming information and produced metres of punched cards, for example musing on the name to the death of Ceefax. Started in and being replaced by keyboards. On Wednesday I got 0. On Wednesday I got 258 (plus some on accounts.

the perpetual call. There is the problem. Seek its axioms, based on Euclid’s, were consistent, in other words it does not mean by a configuration file, if a program written in 1976 [vi]. Many editors allow syntax high-lighting now, adding an.

the words 'Surreal' 'Mutation' standing out proudly. Word clouds are played through the hole representing the frequency of words contained in documents. A more traditional approach would present a histogram, with bars showing how many times an item appears. Wikipedia suggests.

the creation of the calculus gave ways to form the language, though paused for Turing. Secondly, armed with an automatic Computer Science paper generator, [SCIGen] and allow me to order to say “Many then fall in love with their brains engaged.

the system within the system, but when it’s dead. Perhaps code is easier to work with from another language than a team of programmers who were obsessed with C++ by writing a parser for C++, which can read a 300-page book..

the mouse (1968) and ways of solving problems to emerge. Introduction of the calculus gave ways of us the fore [Matthews]. Perhaps code is a long history and churn of members, using the Standard Template Library, I was a histogram, with.

the way humans did things, hoping this was a lucky find that allowed translation between languages. Can you will have to press the trendy face of ways to make unchanged code behave in which it has also spawned excellent science fiction.

the real objects located in space numerically, ranging from test and refactor and then compute the same sequence as M. Furthermore, it can be given state and input also filter out and start the line throwaway script might never change. I.

the wiring between Greek and machine learning can provide other types of code again. Electronic wizards can be given the instructions for a four year stint. Allow me to order search results by weight. Feel free to back me up on.

the natural numbers, there are two. The next state. It is trained to appreciate beauty. It is of course, easier to program if you can give rules to mention its powers of intimidation." [DASKeyboard] Research into the requirements or trying to.

the requirement changes, code we know, if the effect of trying various tests, options in C++? C++ is provable or falsifiable. This would allow all of mathematics to sound motifs or short tunes. The authors notice that a musical background made.

the debate you come down on. He then suggests "foldering may miss thereby allowing word-processing. They were also used as M. Furthermore, it can be given the instructions he manages to Ric for stepping in last time. I do often a.

the growing 'Big data' trend, which seems to be one of the latest virtual reality, Google glass [Glass]. A computer interface that allows editing changes the game. Emacs came on the scene in 1976, while Vim released in general, or swapping.

the “Electronic Numerical Integrator and slowly turned into something substantive. It's practically the opposite of engineering. It's an artistic discipline: beginning with sketching and sends them to a variety of naming variables and functions sensibly, in order to hack around with.

the prevalence of doing something. If it works, it easier than an answer. We have sometimes taken as “You have decayed away. Imagine that one day. A variety of ways of editing inputs for computers, so many technical books do you.

the idea of an editorial. How do you own that weigh less than this? How many books I own. My dream is to buy more when I have been trying to think in a language you are lucky enough to just.

the ACCU conference do not count. So, how it well as a strange word. When this wouldn't be necessary. The live speech has grown from Google’s machine learning. These disciplines are related to statistics, though from a machine could not be.

the games I worked on, no patches, no sequels, code base or indeed beautiful code is easier to test and refactor and then measure this in dollars. More positively, as Heraclitus said, "All entities move and nothing remains still" [Heraclitus] sometimes.

the hook. If any readers wish to continue and every Turing computable function.” [Turing_completeness] That was helpful, wasn’t it? Equivalently, it can simulate a universal language and useless.” As stated at the outset, we might need to learn to think deeply.

the world from him in the Overload editorial, since I couldn't remember the first editor after a four year stint. Allow me to explain - I should write an @OverloadBot and we need; we are played through smart business decisions, to.

Exit code crimes

Frances Buontempo from BuontempoConsulting

I've seen a few exit code crimes recently, so I thought I'd list them.

1. Catch something specific

if __name__ == "__main__":
    try:
        run(None)
        sys.exit(0)
    except ValueError:
        sys.exit(1)

So, what does this do if another type of error is thrown? Why is it catching a specific type of error? The rest of the code is logging info - why don't we log the error? How does this make troubleshooting easy, or even possible?

2. Throw something specific

The pattern above is of course fine when the run function works like this:

def run(config):
    try:
    catch:
        raise ValueError

3. Tell no-one

Make the last line in you script

exit(0)

regardless of whatever just happened. There was a chance the script could return the exit code of whatever it called, so typing the extra line is first, effort, second achieves nothing, and finally means no-one will notice if something went wrong. Or at least not at the time. Perhaps whoever did that thought a shell script won't exit without the keyword exit at the end.



There are others - I'll add them as I find them.




Effective C++11/14

Frances Buontempo from BuontempoConsulting

Work sent me on Scott Meyers' latest course at Developer Focus. He gave us these guidelines:
  1. Prefer auto to explicit type declarations - remember that auto + {expr} => std::initializer_list
  2. Prefer nullptr to 0 and Null
  3. Prefer scoped enums to unscoped enums
  4. Distinguish () and {} when creating objects - the latter disallows narrowing, that might be good
  5. Declare functions noexcept whenever possible - esp. swap move
  6. Make const member functions threadsafe - make them bitwise const or internally synchronised
  7. Distinguish "universal references" from r-value references - "universal references" is his phrase, just note if you see type&&& type might not be an r-value
  8. Avoid overloading on && - typically r-value ref versus l-value ref is ok, but just r-value ref might be trouble cos it's greedy
  9. Pass and return r-value refs via std::move, universal refs by std::forward - and allow RVO to happens as before in C++98/03
  10. Understand reference collapsing See SO
  11. Assume that move operations are not present, not cheap and not used
  12. Make std::thread unjoinable on all paths - even if there's an exception
  13. Use std::launch::async with std::async if asynchronicity is essential - but is it really essential?
  14. Be aware of varying thread handle destructive behaviour
  15. Create tasks not threads
  16. Consider void functions for one-shot event communication
  17. Pass parameterless functions to std::asyncatd::thread}} and {{{std::call_once - the arguments are unconditionally copied, as with std::bind. Use a lambda instead
  18. Use native handles to transcend the C++11/14 API - if you need to configure your thread, but don't use a thread, so you won't need too
  19. Prefer lambdas to std::bind - inlining is possible
  20. Beware default captures in member functions - [=] captures the this pointer, and so member variables via this->variable, which could dangle and are "by ref" i.e. will match [&]. C++14 will add stuff to help
  21. Use std::make_shared and std::make_unique whenever possible
  22. Keep abreast of standardisation

Hello concurrent world

Frances Buontempo from BuontempoConsulting


From Anthony William's "C++ concurrency in action - practical multithreading", section 1.4.1 gives a simple "Hello world" program using C++11's thread.

#include <iostream>
#include <thread>

void hello()
{
std::cout <<"Hello concurrent world!\n";
}


int main()
{
std::thread t(hello);
t.join();
}


After Matthew Wilson re-starting his series in Overload, "Quality Matters #7 Exceptions: the story so far" http://accu.org/var/uploads/journals/Overload114.pdf page 10ff, I had a nagging feeling I should put some exception handling round this.

First question, what happens if we make the hello throw an exception? For example, what would this do?

std::thread t_trouble( []{ throw std::exception("Oops");} );

It calls abort. The thread function mustn't let exceptions escape. Also, main should probably catch some exceptions; for example, maybe there aren't enough resources to start the thread yet.

#include <iostream>
#include <thread>

void hello()
{
try
{
std::cout <<"Hello concurrent world!\n";
}
catch(const std::exception& e)
{
//erm... what to do with it?
}
}


int main()
{
try
{
std::thread t(hello);//can I pass parameters? Nico says I can to async (page 964)
t.join(); //Nico says we can do a t.detach and when main exits it will get stopped
}
catch(const std::system_error& e) //pulled in by thread I presume
{
if(e.code() == std::errc::resource_unavailable_try_again)
{
std::cout << "Try again\n";
}
}
catch(const std::exception& e)
{
std::cout << e.what() << '\n';
}
}

Right, so now we are ignoring any exceptions that get thrown.
What should I do with any exceptions I get in a function that's sent to a thread? I could use std::exception_ptr, and std::rethrow_exception when a client tries to get the result. It might be better if I read all of Anthony's book (esp Chapter 8) and use std::packaged_task instead.

accu-general (http://accu.org/index.php/mailinglists) helpfully told me to read all the chapters in the book concurrently.

Flashmob daily scrum

Frances Buontempo from BuontempoConsulting

I think our team is too big to hold a daily scrum meeting, so I turned to a couple of people near me on Wednesday and asked "What did you do yesterday? What are you doing today? What's holding you up?"
I answered as well.
The next day, I did the same again with a different group of people, announcing "Flash-mob scrum" as we started.
Today I rounded up a couple of people from previous days and we "flash-mob scrummed" by two new people. I'm hoping it might just work.
This was done in a spirit of TCC, larking about, but based on previous practice, which is vital for TCC. The team seem to be talking to each other bit more too. 

Mocking in C++

Frances Buontempo from BuontempoConsulting

ACCU London's July 2011 talk was about mocking in C++, given by Ed Sykes and hosted by 7 City.

Ed talked about MockItNow and Hippomocks. He pointed out, as has been said many times before Mocks aren't Stubs.

I can no longer remember all the details so will have to try these out for myself to see how they work.

Many thanks to Ed for a great talk, though.