The Books I Read in 2016: My 2 Books a Month Challenge

Tags

, ,

I have always been interested in improving my knowledge in a wide variety of subjects and reading books is a great way to accomplish this task. In 2016 I set myself a goal to read two books a month, the same goal that Mark Zuckerberg set himself in 2015. The difference is he set up a Facebook page (https://www.facebook.com/ayearofbooks/) to document his journey whilst I will be using many different forms of social media to do this, as well as Facebook I will also post my books to Twitter, LinkedIn and Yammer (if business focussed) and also on my blog.

I’m pleased to say that I managed to read 24 books within the year. This was only possible because I have an Audible subscription and I listen to at least one book a month whilst cycling to work. I also listen on double speed, which when  you first hear it sounds strange but if you slowly build up the speed it becomes pretty easy to listen to. If you are looking at ways to increase the number of books you read in a year then I would definitely recommend this approach. Find some time in your day where you do something simple, e.g. ironing, walking, etc., and get yourself an Audible account to listen to from your phone. See how easy it is to listen at slightly faster speeds until you reach the maximum of 3 times – I’m only on 2 at the moment but find I’m able to concentrate whilst cycling at this speed.

So, anyway, here is my list of books I’ve read last year, in the order that I read them. I hope you enjoy them and if you have any suggestions for other books you think I should read then add them to the comments section as I’m going to be continuing my reading this year too.

1. Memories of Ice

by Steven Erikson

This is the third installment from the Malazan: Book of the Fallen series and was immensely pleasurable to read. The genre is high-fantasy, which is something I hadn’t realised I would like so much until I started reading it, and is based in a world where mortals can ascend to become Gods and Gods and can be dragged kicking and screaming into the mortal realm. There are games being played on so many levels, by mortals, ascendants and Gods and they all intertwined in wonderful and magical ways, it reminds me of Greek mythology, which I love. A very good series to start if you like anything similar to Game of Thrones or The Lord of The Rings.

2. 59 Seconds: Think a Little, Change a Lot

by Richard Wiseman

This book is all about how changing the way you think about something or changing the way you present yourself can have a major impact on your happiness as well as: how successful you are at dating and dieting; how persuasive you are to other people; and how motivated you are with your tasks. The author has researched lots of studies that have been conducted in all of these topics and delivers them with some subtle humour that keeps you entertained. At the end of each chapter there is a section called ’59 Seconds or Less’ that gives the reader a task to do to help them improve quickly based on the studies they have just read, it’s also a great way to review the chapter in a concise manner at a later date. I highly recommend this book to anyone wishing to understand how to improve their day to day mood and those of people around them.

3. How to Create a Mind: The Secret of Human Thought Reveiled

by Ray Kurzweil

The first part of this book is a fascinating insight into how memory works in the brain. It’s very easy to liken the way the brain stores information to the way that a computer stores information on its harddrive but Ray explains that we don’t hold items of information but instead patterns of information and to retrieve that information we follow a hierarchical system of patterns to rebuild the memory based on these patterns. The second part to this book starts getting very deep and discusses consciousness and whether a computer could ever be conscious. A very enlightening read for anyone interested in artificial intelligence.

4. The Docker Book: Containerisation is the new Virtualisation

by James Turnbull

This book gives a very good introduction to containerisation and the reasons it should be used. It also goes into a good amount of depth with examples so that you can understand how it works practically as well as in theory. The only shortcoming I found with this book is how dry it could be. The introduction to Docker was fascinating and gave me lots of information on its creation and use but the examples ended feeling a bit monotonous by the end. Still, I recommend this to anyone wishing to get to grips with the technology quickly.

5. Ramen Noodle Cookbook

by Nell Benton

This book starts off with information about each of the constituent parts that make up a ramen and the Japanese love affair with the famous dish. The second part of the book is all about recipes, and they range from the simple chicken stock down to building a full tonkotsu ramen including chashu pork. I found the first part of particular interest because it explains the history of the dish and gives insight into the regional varieties that have changed over the years. The second part was great for learning that you really can put anything into a ramen, e.g. they have a Pad Thai Curry Ramen, but for the advanced cook you’ll find yourself skipping a lot of parts that are just too simple, but that just makes it a great read for the novice.

6. Feel the Fear and Do It Anyway

by Susan Jeffers

I was recommended this book by a colleague of mine whilst I was working on a talent and development programme. I’d mentioned that I wasn’t that comfortable standing in front of people and presenting to them, and the culmination of the programme was a presentation to the board of directors! This book was a great way to understand why we are fearful and also how to overcome fear. The first quarter of the book really gives you all you need to know about the topic but the rest of the book drives home the point with lots of case studies, some of which I found useful but mostly they weren’t relevant to me and only laboured the points I already knew. Still, it was a great book to read and has given me the confidence to be more proactive and put myself in more situations to overcome my fears.

7. Postwar

by Tony Judt

Wow! This was a very long book. I have to admit it was not really my cup of tea as it was unbelievably dry. If you like history and can deal with the dryness then you’ll probably love this book. It is a very thorough account of the events that have happened since the Second World War ended and in parts I found the depth and breadth of this book to be outstanding. However, it’s made me realise I don’t ever want to read a history book again! I prefer dreaming of the future and not dwelling on the past.

8. Pitch Anything 

by Oren Klaff

I started  reading this book because I was going to pitch to the board of directors of my company as part of a talent and development programme that I was part of. Initially I thought the book wasn’t great as it was suggesting some things that sounded like a surefire way to get fired very quickly. However, after reading more I realised that the content in this book would really help with a pitch, in fact I even used some of the techniques in my presentation and they worked well. I highly recommend this book if you want to know a few tricks of how the brain works and what you can do to get your idea through when presenting.

9. The Jungle Book

by Rudyard Kipling 

This was a brief respite from the hectic first six months of the year. Even so it was a fantastic story that I haven’t read since I was a child and I’d forgotten most of the story.  It was a relaxing dive into another world, a world full of animals, adventure and education. A good light read.

10. How to be F****** Awesome

by Dan Meredith

This book caught my eye because of the brilliant title. What more could someone want than to be fucking awesome. Everyone has a different interpretation of what awesome is but I’m sure no one wants to be mediocre, they want to be awesome in their own right. So, I gave this book a shot and was happily surprised by how enlightening and damn right hilarious this book was. It took a lot of the principles that I’ve read from other books and turned them slightly on their head and looked at them from another perspective. A highly enjoyable book with some great tips.

11. Night School

by Richard Wiseman

Another great book by Richard Wiseman, he’s fast becoming a favourite of mine! This book was a fascinating insight into the way the brain works during the wee hours of the night. It explains all the really interesting and down right bonkers experiments people have attempted to crack what dreams are made of and how to get the most out of your sleep. I’ve always been someone who likes to get as much out of the day as possible and sometimes this has been to the detriment of my sleep but this book has shown me that that kind of lifestyle can only last so long – sleep will catch up and is required. Now I have a better understanding of what I need to do to maximise my sleep and be fully alert throughout the daytime.

12. The 7 Habits of Highly Effective People: Powerful Lessons in Personal Change

by Stephen R. Covey

This book is full of really great ways to improve yourself. Whether you want to do this for your family life, for your work life or whether you just want to understand the pschology of people, you will find a lot of answers to your questions in this book and should easily have some take aways from it. It reiterated some of the principles I’ve read in other self-help books but also explained some new ones. The first three habits are great and really worth getting stuck into, however I found some of the latter habits to be a little trickier to process. I am going to spend some time mastering the first three habits and then re-read the book to see if I can push to the next level. Great book and worth a read if you want to improve your life in anyway.

13. Emotional Intelligence

by Daniel Goleman

I really enjoyed reading this book as I have a 2 year old daughter and a lot of the case studies from this book were on young children and how easily they can be affected by emotional situations around them and what can be done to help them set themselves up for a happy and healthy life. I’ve read before about the different areas of the brain and how they function and how there is a “croc brain”, an “emotional brain” and a “logical brain” and how when receiving information from someone the information is fed through each through acception but each one can reject the information before reaching the next. However, this book described how children’s brains start off with just the “croc brain” and as they grow they develop the next two “brains” meaning for the first few years they don’t have the logical part of their brain that we sometimes expect them to have. So during this time it’s better to be emotionally involved with them and just nurture them – this opened my eyes to how I could better deal with potty training.

14. Grit: Passion, Perseverance and the Science of Success 

by Angela Duckworth 

This book was pretty decent and explained why sticking to a passion is so important to becoming successful but it did seem to go on a bit long. To be honest the title explains everything you need to know – find a passion and persevere with it until you are successful.

Book 15: Mindfulness: A Practical guide to Finding Peace in a Frantic World

by Mark Williams & Danny Penman

I’ve been meditating for a while now, on and off, but it’s been based on a few reads here and there on blog posts. So I figured it was about time to get serious and this book seemed well reviewed. I thought it was a good read but it didn’t give me anything major to think about apart from the weekly structure of meditation. The best part for me was the end where Mark talks about 8 different meditation techniques, it was spoken in a similar vain to the Headspace app and this was nice to hear. A good book for anyone who hasn’t looked into mindfulness before but if you are already a little used to it (and already open to it) then it may not be that good, except for the exercises.

Book 16: You Said What?! The Biggest Communication Mistakes Professionals Make

by Kim Zoller and Kerry Preston

Not that impressed with this book. When a book tells me that I have to be careful of what I post on social media then I soon realise this book is not going to be of that much use to me. The majority of the book was in list format, e.g. do this and don’t do that, with the odd ‘side note’ that included a snippet of a real life example of what you should say and do. However, these just felt tacked on and didn’t make me feel a eureka moment, it was all common sense. So, I wouldn’t recommend reading this book.

Book 17: Black Box Thinking

by Matthew Syed

This has to be up there with one of the best books I’ve read his year. it’s all about how failure should be embraced and how successful people, companies and industries rely on failure to improve themselves. It explains why scientists have been failing fast but continuously improving since the dawn of science and how creating an MVP and iterating is better than perfection from the beginning. It gives good examples of how companies failed and made a success from it, such as Dyson and how they iterated over the vacuum 5000 times before it was the product we know and love. It also gives some great examples of how to make failure work for you so this book is a must read from this list.

Book 18: Full Catastrophe Living 

by Jon Kabat-Zinn

I enjoyed reading this book because it explained mindfulness in more detail than my previous book on mindfulness. The last book was more about how to deal with stressful situations whereas this book explained how mindfulness is great in any circumstance. My only criticism is it doesn’t have any practical examples but they are easy enough of find elsewhere. This book combined with the Mindfulness book have lots of great information though.

Book 19: The Obstacle Is The Way

by Ryan Holiday

The idea that hitting an obstacle and not giving up is a great one. Learning to persevere during the hard times is a great skill to have and this book champions this trait. I thought the book was a good read but I don’t feel it had that much depth. The title summed up the book and the stories within didn’t call out to me. I suppose it’s very similar to the Grit book, which I also didn’t rate very well. It is a good read but didn’t give me much knowledge that I didn’t already have.

Book 20: House of Chains

by Steven Erikson

What a fantastic book this was. It’s nice to have a good long fictional book to get into. I like to keep one ticking over in the background whilst reading non-fiction and self-help books and for this 2 books a month challenge it is necessary as this book has taken me almost a year to read! I was blown away by the majority of this book, there were parts that got a bit complex with the storylines not melding well together but it was a thrilling ride none the less.

Book 21: Vaporised: solid Strategies for success in a Dematerialized World

by Robert Tzercech

This book is a great book for anyone who wants to understand the history behind the digital revolution and what it has done, and has the potential still to do, to well established businesses across the globe. it was a fascinating read that explained how traditional businesses such as record stores, taxi firms, the hotel industry and even banks are being vaporised into digital bits. I’m a keen reader of technology news so already had a pretty good understanding of this but as the book wore on a started to realise just how much scope there really is for improvement and disruption. The next 10 years are going to be very spectacular indeed.

Book 22: Pregnancy For Men: The whole Nine Months

by Mark Woods

I’ve read this book once before, back in 2013 when my wife was pregnant with my first child. I decided that I’d give it another go now that she is pregnant again, yay! It wasn’t the same the second time round though. Still very amusing but I suppose the unknown of the first made this book what it was. Now I know what it’s like the second read is not that useful, but still funny. A definite read for new dad’s to be but no need to read twice.

Book 23: Negotiating the Impossible

by Deepak Malhotra

I don’t like things to be static, I much prefer to change something and see if it is better or worse. This kind of attitude can sometimes get me into some difficult arguments though. Sometimes this change can be perceived as too drastic and disruptive for limited gain but that is where negotiation comes in. So, I decided to read this book and found that it had some really great insights into how to better frame your idea so that others are less negative towards your requests. It tells you about how to see it from the others point of view and try to solve their issues so that you can then present yours. It has some great case studies and is well worth a read for anyone who deals with conflict in their daily life.

Book 24: The Coaching Habit

by Michael Bungay Stanier

This book was pretty good. It explains how to be a better coach to people around you by giving examples of what you should and shouldn’t do. I thought it was going to be more around how to coach other people but it seems to be more about how you can be a better coach, i.e. how you can change your own habits so that you react to situations in a better way. In some parts it was very pertinent to me but in others it was preaching about habits that are generally common sense. It was a good book for me to read this year as next year I will be managing people for the first time but I think this only really covers a few topics around being a successful coach and there is so much more to learn.

So, that’s all folks. I’ve been on a wonderful journey this year and read some fantastic books. Next year I won’t stop, in fact, I’m hoping I can get more than 24 in next year as this year was probably one of the busiest years of my life. However, I do have another child on the way so maybe I’m being a little ambitious. Till next time.

SC.

Advertisements

Shop Direct’s Outstanding Talent and Development Programme

Tags

, , ,

Up & Coming: Stand Out

What is it all about?

Back in October the Shop Direct Talent and Development team sent out an application for anyone that was not in the leadership team, to apply for their new Stand Out programme. A programme where the main focus was on driving Shop Direct into the future of innovation in the digital mobile space, whilst also nurturing, and bringing to the fore, the existing talent within Shop Direct. The brief was vague but intriguing. We knew that the programme would last six months and we would be expected to produce something tangible at the end of the term. We also were told that this would be on top of our day jobs and to be prepared for a lot of extra work! To apply we would have to answer the following three questions and would be able to present them in any format we so desired, this could be a simple PDF, a creative video, or even (in one person’s case) a mobile game:

  1. Tell us about a company that has super impressed you with their mobile experience or an app you use. Why are you impressed?
  2. What more can we do to make digital the DNA of our culture?
  3. Why is Up & Coming: Stand Out good for you and how can it help you be the very best you can be?

The applications would be reviewed by a panel of 4 people that included the Talent Partner, who had set up the programme; the Talent Director, the Ecommerce Director and the CEO of Shop Direct. As you can imagine, this was not an opportunity to be missed and I jumped right on it!

The applications

Now the seed had been sown, it was time for the panel to wait for the applications to come rolling in. However, none came. The panel waited longer, but still, none came. Then about two weeks before the deadline, there came some hope. One application. Then two applications. Then… no more. Could it be that the programme was never going to take off? Surely not! Do not fret dear reader, as with all good stories, there is a happy ending. In the final week, just before the deadline, a deluge of more than 90 applications flooded in and the panel dutifully took to processing each and every one of them.

In your wildest dreams you can not imagine the marvelous SURPRISES that await YOU – Willy Wonka

The applications came in all shapes and sizes. There was one in which the application mimicked Buzz Feed’s site by answering the questions in lists of ten; there was another in which the applicant went above and beyond the call of duty, when researching the current and best mobile apps, by digitally applying make-up to himself through the L’Oreal app; and finally, one of the applicants created a mobile game app where the panel would have to get to a certain amount of points to unlock the answers to the questions. The panel had their work cut out to whittle these applications down to just 20 that would be accepted. This proved too difficult in the end and the panel decided that they would take 24 due to the quality and effort put in by everyone. I am pleased to say that I was one of the lucky applicants, and just like Charlie Bucket from Charlie and the Chocolate factory, I was very excited about having a ‘golden ticket’ to a new adventure.

Golden ticket

Kicking off the programme

The programme officially started on the 14th Jan and we all met each other in one of the converted warehouses in the up & coming Baltic Triangle area of Liverpool. The full day event involved meeting the successful applicants, being told what exciting things awaited us and being given an overview on how we can succeed. This was a gathering of likeminded individuals who want to make a difference at Shop Direct, and the excitement in the room was palpable.

As the programme was sent out to every employee across Shop Direct, we had a broad range of people in the room; from marketing to sales & trading, IT engineering to customer services, and from warehouse operations to financial services. In amongst this eclectic mix was the talent and development director, the ecommerce director, the credit risk & operations director, the group merchandising director,  the CIO, the head of user experience and the talent partner, who set up the programme. The applicants didn’t know what to expect when they woke up that morning, but it was like waking up on Christmas day and seeing that Santa had been, and had left a stocking full of gifts.

After the sociable meet and great over coffee in the morning, we were taken through the programme, what we should expect and what the end goal will be. We were told that there would be four work streams and that the delegates would be split into teams of 6 and given a team lead (one of the directors in the room or the CIO) and also a team coach. The four workstreams are as follows:

  1. Bring ’em on board: how do we look to the future of acquiring new credit customers?
  2. APPovation: what is the future of transactional app development and how do we get there?
  3. The category challenge: how can we improve our home & furniture offering and experience on mobile and tablet?
  4. Help yourself: how does mobile become the way which we help more customers self-serve more easily?

As you may have guessed from the URL, I am part of the Appovation team. The five other colleagues in the team are shown below and our team lead is Andy Wolfe, the CIO of Shop Direct.

APPovation Team

The APPovation team: (top row) Euan Macdonald, Vicky Bolam, Tom Lilliston; (bottom row) Matt Arnold, Melissa Theobald, Seb Carss

The next piece of information we received was that we would all be going on a trip to Mobile World Congress in Barcelona! This would help us to compound our research and open our eyes to the future of technology in the mobile space. As you can imagine I was pretty giddy by this point. A trip to Barcelona to get a look at future tech, this was a geeky dream come true!

Mobile is Everything – Theme of Mobile World Congress 2016

We were also told there would be a Mobile First Week during the course of the programme where we would be given one day to engage with everyone across Shop Direct and to communicate what digital is and what it means for them. This could be a demonstration in ‘The Street’ of Skyways House of the new technology that is coming out; a video explaining digital and the digital revolution that we are currently in; or a Q&A Yammer session (i.e. a Yam Jam). You may be thinking this sounds like a lot of work, but wait, there’s more.

The next thing we were told was that we would be a digital mentor for a director during Stand Out. We were all assigned a mentee and we would have to setup a meeting with them and bring them up to speed on all things digital. The idea behind this is that us, so called, Millenials, who have never known life without the internet or adult life without a mobile phone, use technology differently to the older generation and therefore, for Shop Direct to accomplish its task of becoming a world class digital retailer, the directors would need to understand how Generation Y tick.

We were then told that the culmination of all of this hard work would result in a 2 hour long presentation to the board and the CEO, Alex Baldock. These would be spread out throughout June and the APPovation team have the luck of being first up to present on the 1st June. Ok, so we’ve got less than 6 months to research, design and present a game changer for Shop Direct!

Innovation distinguishes between a leader and a follower – Steve Jobs

Finally, we were told all of the work above has to be done on top of our normal day jobs. That’s a lot of work! This was no easy task and it would stress and strain us throughout the 6 months. How are we going to achieve all of this? No one really knows, but, no one will disagree when I say, we are going to do it and we are going to do it well. Watch this space.

5a41132e-b3b2-4ad4-b0b6-d9f0864380d4-original

Shop Direct’s Up & Coming: Stand Out programme

Reasons to Use Interfaces over Extension when Testing

Tags

,

Should We Use Interfaces?

There is lots of information on the internet, in forums, books and at conferences that suggest we should be using interfaces when designing our code. One of the most popular programming books – Design Patterns by the Group of Four – shows you how the use of interfaces in your code will help to improve the design. One of the main reasons interfaces are lauded so much, by experts in the field, is the ability to change the code in the future. Adding interfaces upfront means that at a later date, when the requirements have inevitably changed, it is much easier to swap out the implementation with another, and therefore save you some headache inducing refactoring. As the author François de La Rochefoucauld stated:

The only constant thing in life is change

So if interfaces are so great why don’t we have an interface for every class that we create? Well, some may argue that you should. Some developers write an interface for each class and then pass the interface around instead of passing the concrete class. This leaves the code very loosely coupled and easy to manipulate. Doesn’t that sound wonderful?

Well, maybe not so much. You see, there is also contradicting information on the internet, in forums, books and at conferences that states that you should only add interfaces when required. YAGNI (i.e. you ain’t gonna need it) states that there is no point writing an interface for every class because it is easy enough, with today’s IDE’s, to automatically generate an interface when required. This principle is based on the idea that good development involves heavy use of refactoring to keep the code clean. Bob Martin (AKA Uncle Bob) has this saying about coding (taken from the boy scouts):

Always leave the campground cleaner than you found it.

So, if we are constantly making small changes to clean the code as we go along, then adding a new interface when required isn’t that big of a deal, right? Another point that gets raised when there are lots of interfaces being used is how much more difficult it is to navigate through the code to understand what is going on. However, this for me, is where understanding how your IDE works pays dividends. In Eclipse you can click F3 to drill into a class. When you hit an interface you can hit F4 and see the implementations in the Type Hierarchy and double-click to drill into it. Once you have become adept at using these keys, understanding the code becomes quick and easy again.

Unit Testing Using Fake Objects and Interfaces

Writing unit tests is a skill, like all programming, that needs to be learned and mastered. Good code design helps with writing unit tests, which is why TDD has become so popular. If you write the test first and then write the code to make the test work, then the design you end up with, in theory, is well designed and easy to maintain in the future. One of the tools I generally use when writing unit tests is the notion of fake objects. These are objects that pretend to be an object we care about but allow us to call our own faked methods instead of calling the real methods. This means we can setup the fake object to return the values we expect within our class. Take the following example:

We are testing a CashMachine class, which gets the required bank from a BankDirectory class. It then uses this to withdraw the money. Here’s what this may look like:

public class CashMachine {
    private BankDirectory bankDirectory;
    public String withdraw(Card card, int amount) {
        Bank bank = bankDirectory.getBank(card.getBankId());
        UserCredentials credentials = card.getCredentials();
        boolean withdrawSuccess = bank.withdraw(credentials, amount);
        if (withdrawSuccess) {
            payOut(amount);
            return "SUCCESS";
        }
        return "ERROR";
    }
    // getters and setters hidden
}

Before I continue it’s probably a good idea to highlight that the getBank(String) method of BankDirectory access a database to retrieve that required bank. As this is an external system and not one that is suitable for a unit test we need a way to override the method so that it returns the Bank that we want to use.

There are a few different schools of thought on how to test code that involves collaborators that access external systems. Martin Fowler can explain this much better than I can, so if you want more information then check out: Mocks Aren’t Stubs. However, I will concentrate on the use of fake objects for this post as it has helped me to understand not only a reason to use interfaces but how not using them can cause headaches.

So, the test that I am going to show in this example is this:

GIVEN bank approves withdrawal
THEN return "SUCCESS"

For this test I need to create 2 fake objects: A FakeBankDirectory and a FakeBank.

public class FakeBankDirectory extends BankDirectory {
    private Map<String, Bank> banks;
    public FakeBankDirectory() {
        banks = new HashMap<String, bank>();
    }
    @Override
    public Bank getBank(String id) {
        return banks.get(id);
    }
    public void putBank(String id, Bank bank) {
        banks.put(id, bank);
    }
}

public class FakeBank extends Bank {
    private boolean acceptWithdrawal = false;
    @Override
    public boolean withdraw(UserCredentials creds, int amount) {
        return acceptWithdrawal;
    }
    public void setWithdrawalAccepted() {
        acceptWithdrawal = true;
    }
}

As you can see FakeBankDirectory extends BankDirectory and FakeBank extends Bank. This means that in my test I can swap my collaborators for the fakes and not worry about actually calling the real objects. The two methods that I need to control have been overridden which means I should be able to create my test like so:

public class CashMachineWithdrawTest {
    @Test
    public void givenWithdrawSucceeds_thenReturnSuccess() {
        // instantiate test objects
        FakeBankDirectory bankDir = new FakeBankDirectory();
        Card card = new Card(BANK_ID);
        FakeBank bank = new FakeBank();

        // setup test data
        bankDir.putBank(BANK_ID, bank);
        bank.setWithdrawalAccepted();

        // setup test component
        CashMachine cashMachine = new CashMachine();
        cashMachine.setBankDirectory(bankDir);

        // run test
        String result = cashMachine.withdraw(card, 50);

        // verify test
        Assert.assertEquals("SUCCESS", result);
    }
}

At this point I run the test and expect it to pass but instead of seeing a lovely green bar I see the red bar! The error I get shows my test is trying to connect to an external system that the FakeBankDirectory depends on. Some of you may already be screaming at the screen at my mistake. So it’s time to confess. I haven’t told you the whole story. I have hidden one rather significant detail. The reason why I didn’t mention it at the beginning was because sometimes developers don’t see the whole picture themselves, or don’t understand some of the little, implicit, intricacies of Java.  So here is the part I missed out.

BankDirectory has a constructor. This constructor sets up the connection to a database that it can then use when someone invokes getBank(String). The stacktrace shows us that this is the external system that is trying to be called and is failing. You may be wondering how this is possible when we don’t instantiate a BankDirectory? We have our own FakeBankDirectory constructor and we don’t call super() on it so how is it being called?

Some of you may already know what is happening here but I will elaborate for those that don’t. When a class extends a second class and the sub-class is instantiated, the parent class’ constructor always gets invoked first. If the parent class also extends a class then its parent gets invoked before both the sub-classes. Here is another example:

class Animal {
    public Animal() {
        System.out.println("Animal");
    }
}

class Dog extends Animal {
    public Dog() {
        System.out.println("Dog");
    }
}

class application {
    public static void main(String[] args) {
        Dog dog = new Dog();
    }
}

In this situation, when the application is ran the output is:

Animal
Dog

As explained above, the parent class’ constructor is always invoked first, even if you don’t explicitly call the super() method like below.

class Dog extends Animal {
    public Dog() {
        super();
        System.out.println("Dog");
    }
}

This is because the Java compiler automatically adds the super() constructor call in for you, if you leave it out. The other thing the compiler does for you is it automatically creates a default constructor if you don’t. So if Animal didn’t have a constructor then the compiler would create one for you and then call it when you instantiate Dog.

If you decide to create a constructor with a parameter, then the default constructor is not created. Instead your constructor must be used when instantiating the object.

class Animal {
    public Animal(String type) {
        System.out.println("This animal is type: " + type);
    }
}

class Dog extends Animal {
    public Dog() {
        super("Dog");
        System.out.println("Dog");
    }
}

class application {
    public static void main(String[] args) {
        Dog dog = new Dog();
    }
}

In the above example the output would be:

This animal is type: Dog
Dog

If you didn’t add the super(“Dog”) constructor call, then the compiler would throw an exception because a super constructor always has to be called and because you have created a constructor, no default constructor is created automatically by the compiler.

Back to the CashMachine Example

So we take a step back from the Animal example and go back to our CashMachine example, and the point of this post, which is to highlight that if you are using fakes in your tests you should be aware that extending real “build” classes can cause dependencies to throw errors. It would be much better if there was an interface that both the BankDirectory and the FakeBankDirectory implemented. This would allow the FakeBankDirectory to stand alone but would allow us to use it in place of the BankDirectory. So, here is the better version:

interface FinancialInstituteDirectory {
    public abstract Bank getBank(String bankId);
}

class BankDirectory implements FinancialInstituteDirectory {
    public Bank getBank(String bankId) {
        // ... do real "build" version of getBank
    }
}

class FakeBankDirectory implements FinancialInstituteDirectory {
    public Bank getBank(String bankId) {
        // ... do test version of getBank
    }
}

Our test class will look exactly the same but in this instance, because FakeBankDirectory is implementing FinancialInstituteDirectory and not extending BankDirectory directly, the test will not call the BankDirectory class’ constructor and fail with an external system dependency.

Breaking dependencies: When a constructor instantiates objects

I was speaking to a colleague recently during one of our fortnightly tech forums and he mentioned a specific class that he found difficult to get under test. The problem was that the constructor of the class was attempting to instantiate and configure new objects that were difficult to setup in a test harness. When you are faced with a constructor that instantiates classes internally there are a few different ways to break these dependencies safely. This article describes some of them and the reasons for using each one. Continue reading

Breaking Dependencies to Test Code in Java: Irritating Parameter

Tags

, , , ,

Whenever I need to add a new feature to some legacy code I attempt to add some tests around the code before I start making changes. This ensures that I don’t break the original purpose of the code. This is not always easy though as some classes and methods can be difficult to get into a test harness. One example I will talk about now is that of the Irritating Parameter, which was pointed out to me in the book http://www.amazon.co.uk/Working-Effectively-Legacy-Robert-Martin/dp/0131177052. If you haven’t read this book I thoroughly recommend it as it explains ways of breaking dependencies to get classes under test, which I have found can be difficult when working with legacy code and large systems.
Continue reading