Thursday 18 May 2017

Getting Started: Introduce Coding Using Swift Playgrounds on iPad

Swift Playgrounds is an application for the iPad built by Apple to help developers learn how to write Swift applications.
Swift Playgrounds is a revolutionary new app for iPad that makes learning Swift interactive and fun. Solve puzzles to master the basics using Swift — a powerful programming language created by Apple and used by the pros to build many of today’s most popular apps. [https://www.apple.com/uk/swift/playgrounds/]
Although the application is designed primarily for developers, it can also be used to help engage children in coding. For younger children, this does require adult supervision to help with explaining what the function does.

The session is designed for younger coders, for children aged 6 and upward it might be better to try the Hour of Code session created by Apple.

Getting Started

Session Time


Around 30 minutes

What you need


  • An iPad, probably Air 2 or newer. The graphics that render are quite cool, but require some power. I haven't tried it on an older device, but it seems fine on the Air 2
  • Download Swift Playgrounds from the Apple App Store
  • Download Learn to Code 1 as an in App download form the Swift Playgrounds app

Preparation 

  • It is worthwhile taking a look around the app and getting familiar with how it works. You don't really need any significant programming experience. The session will focus on moving an alien around the screen to pick up gems and activate switches
  • For younger children the trainer will need to help with reading skills and choosing the correct function. The functions are moveForward(), turnLeft(), collectGem(), toggleSwitch(). If you haven't come across the term function before, just think of it as an action the alien will perform
  • This session is really just a game, there's no programming loops just yet. These are for a different session
  • You will probably find you can run this same session many times, children really like the interaction and ease of controlling the alien

Controls & Leading Play

  • Controls are as simple as pressing the name of the functions (actions) that you need. To go forward twice pick the moveForward() function twice. Think of it like playing a step-by-step platform game
  • If the child says they're not sure what's next just run the program. The alien finishes up at the last instruction and then you can correct. Allow the child to make mistakes, this is really important and it's OK to not have the correct solution first time. They'll struggle later if this isn't done right from the beginning as the problems become more complex
  • Let them hold the iPad and control the pressing. You might want to have a small session where you show them first, but they will get more from being the one pressing the buttons


The screen has a description and extra instructions of what needs to be done. The code is the list of instructions at the bottom left. Run my code/stop is at the bottom of the screen. 

Lessons to Try

For a thirty minute session the following are probably enough to get started. I've also outlined some things to discuss and think about each lesson and a sample solution.

  • Issuing Commands
  • Adding a New Command
  • Toggling a Switch
  • Portal Practice
  • Finding and Fixing Bugs
  • Bug Squash Practice
  • The Shortest Route
Below are some sample solutions that we came up with:

In the next lesson we will look at how to make use of the Functions module and how to use that for teaching. 

Friday 12 May 2017

Kids Code Introduction

In recent years my blog has been fairly empty, life in general has taken over most of my free time. We have two small children aged 4 and 7 months, who are hard work but a lot of fun. The way in which children interact with technology fascinates me, Emily is quicker at using the iPad than her grandparents! Inspired by Devoxx UK, I have decided to try get back into community work. 

For the last three years I have taught over 500 developers fresh from University how to code better and prepare for a career that is more than just hacking they may have done at Uni. Most of the trainees have significant experience coding and the rest have at least started their journey. Often friends who don't program ask "How do I get into coding" or "How would I got about writing an app". It's very difficult to explain what coding is to an adult, so how do you get this across to a child that is just learning to read and write?



The are many educational games and activities targeting children, particularly for basic math and letters. Seeing how excited my daughter got by playing these games it inspired me to look at ways I could teach her the basics of programming. I wanted it to be something that we could do interactively together and that she also enjoyed spending time on. Making things fun is important, regardless of age group. An engaged trainee that is following a narrative or story along with hands on experience is usually the most successful in retaining information. 

In the blog posts to follow I'll be writing about the mini-training session plans I am working on with Emily (4 years old). Like any good training there should be some objectives and an understanding of the trainee:
  • Make coding and thinking in a structured way appealing to children. The goal here is not for Emily to join a start-up or to get to 10 and be a computer genius. It's adding an extra layer of thinking and approach to problems that schools are just getting to grips with. 
  • Sessions are no more than 30 minutes, anything longer and a young child may resent the task. I've found that it's also OK if they want to go and do something else, just start the session again from the beginning (if they remember they'll usually tell you). 
  • Being able to read is not necessary, but will help. We started this process before Emily could read, and now she can recognise some letters. We work together on choosing the right function calls and code as we go. Initially I drove that, but now she is much more confident in choosing the right functions.
  • Is not always on a computer. Some of the sessions that I am planning are not on the computer at all, but will have tasks that related to designing and executing instructions. 
Below is a video from one of my first training sessions with Emily. We are using software on the iPad called Swift Playgrounds, which is designed to teach developers how to learn Swift. However some of the early content can be used to also teach children basic concepts in a fun game environment. This will be the subject of the first lesson plan that I will publish next week. This video is special to me personally as it shows that coding can be fun and rewarding, even from a young age. 


If you are interested in following the lesson plans please keep an eye on my Kids Code page for links and on twitter. Also please do comment or make suggestions, I hope you have as much fun as we are having. 

Wednesday 4 February 2015

Pragmatic Functional Refactoring in Java 8

Java 8 is here! Now the honeymoon period is over larger companies and innovators are starting to use the new features. However, Java 8 isn't just another version of Java, it fundamentally changes how you are able to approach problems.

"Java 8 and functional programming is not just for beards" -- Raoul, and is now available to developers in general. Many business problems can be expressed in an easier way than in a declarative style of programming. It is a well known fact however, if there is someone with a beard next to you they probably are a functional programmer. 

The slide deck from JFokus can be found here, the session was also recorded by the VirtualJug in September last year.

The talk is aimed at making functional techniques relevant to programmers and takes the approach of introducing a problem and how it can be solved using functional techniques. The good thing about this style is that the emphasis on how to apply functional programming techniques is not bogged down in buzzwords or potentially confusing terminology. 

The talk starts out with a problem we often face as software developers. Initially we have simple requirements that over time change and if the code is not designed correctly or refactored when necessary can be unwieldily and difficult to maintain. The problem domain introduced is around invoices:
  • Filtering all customers of a specific name
  • Later we want to process different customers rather than a fixed customer
  • We also now want to separate out different functions with that company that may have a different suffix representing the type of activity carried out
  • We also now want to state whether we want the invoice included or not
The result is some fairly messy code:


From the messy code the talk goes on to look at how applying functional methods can reduce some of the problems. Introducing the Predicate interface from the Java 8 API allows a test for whether an invoice should be included. This simplifies the code dramatically as the test for inclusion of an invoice can be packaged up and passed into the method as a function. This is the core of how first-class functions work, allowing a function to be passed around as a first-class citizen in the language. The introduction of method reference is shown as an intermediate step, but we finally see our lambda solution that makes everything quite clear. As a Predicate is a functional interface the test can be passed in as a simple lambda expression. The intent of the code is now clear and considerably simplified:


Compositing functions together to create more advanced predicates is next on the agenda, introducing how more complex functions can be combined together using the and, or methods. Just as it's a bit weird to wonder how this is working, as a Predicate is simply an interface we learn a new concept Default Methods introduced in Java 8. The discussion finishes with a conversation about how pipelines can be used to chain functions together, where the sequence of application is important.  The example discussed is an E-Mail where first the content is created, followed by the spell check and the addition of the signature. 

The next topic for the pragmatic approach to refactoring is currying and partial application. Currying is a tricky topic to initially wrap your head around and involves taking an initial argument set and splitting them out, so parts of the overall logic can be reused as functions. The talk looks at how to refactor a conversation function to be used for converting common measurements such as temperature and mass. I like to think of the approach as at each step the initial argument set is locked down or partially applied. I definitely advise watching the section on currying, Richard and Raoul do a great job of explaining the concepts. Here is the example used in the presentation:


Mutability is problematic, specifically where developers make things mutable that would be far better modelled as immutable objects. Mutability can introduce subtle bugs where a developer takes a reference and updates an object - however it could be years before that actually manifests itself as a production problem and can be tricky to find. There are however some cases where you need to use mutable objects and this is fine. The key is to use the right design for the right requirements within your application. 

The talk goes on to cover Optional and how it can be used to help prevent NullPointerExceptions in chained code and provide the ability for a developer to provide default values or return a slightly different result. Another key benefit of Optional is the removal of lots of boilerplate null checks that can lead to issues around code readability. This part of the talk is extremely clever and introduces a practical case for the flatMap method on Stream to get at the contents of the Optional container. I actually heard several developers comment on how useful this was to them after the talk. 

The talk is a taster of the full course that is run by myself, Richard and Raoul  More information can be found on our training site, with public course running in Switzerland, United Kingdom and Sweden in the coming months. 


Tuesday 3 February 2015

JFokus 2015 First Impressions

In the centre of Stockholm, on a snowy first week of February, is the start of JFokus 2015. When I say cool it's currently -2°C with a "feels like" -11°C. The conference is a three day event, the first consisting of tutorials, the second and third are traditional  conference session styles. 

I came unprepared for Stockholm, and for future reference (mainly for myself) packing the extra items is recommended:
  • A hat. Only the speakers get the cool JFokus red hats!
  • Proper shoes, the snow is amazing here. It falls and everything just continues on as normal. The only effort I have seen of any snow being removed was a guy shovelling it off the roof of Stockholm Central Station. At least there was a barrier around the target area, on the pavement.
  • A decent coat for when you're outside, a fleece doesn't really do it.
When I got to the hotel on Monday I felt very unwell, got an early check-in and went straight to bed. I missed the majority of the first day except a few beers with RaoulRichard and Heather. The hotel bar was alive with conversations about the VM Tech Summit, which sounds to have proved popular with the attendees. 

Tuesday morning I got up and explored the hotel prior to the keynote starting. The hotel is next to Central Station, but navigating to it seems impossible. Almost everyone has a story about how they ended up in the wrong place or took about 6-7 different streets to get there. Waterside is a decent venue, with lots of space for the 1700 conference delegates.


The conference kicked off with a guy with a tape measure doing some robotic style dancing on the stage. My initial reaction was:
The "developer" was the joined by some other dancers to a pretty decent routine. The stage was then taken by Mattias Karlsson, sadly we did not get to see any of his dance moves. The main room is impressive here, with room for most of the delegates.


On day 2 I attended only a few talks.
I am planning to write up each of the sessions over the coming weeks, along with some sessions from tomorrow. 

Sunday 3 August 2014

Teaching ClassLoaders, Reflection and NIO2

As a leader of the London Java Community and as a developer in several firms I have noticed one trait across Java developers. We are spoilt! We have nice APIs, abstractions, IDEs and build systems which means that often we don't appreciate some of the lower levels of what is actually happening within the Java ecosystem. Most people can get by without this knowledge, however in the situation that there is an outage or a problem and we simply have no idea why something has started to fail, it's not the best time to start reading up on advanced Java topics. 

Sometimes we think we have enough information, because in a topic like class loading it might be enough to say "It's how Java loads classes". In my opinion this lack of knowledge is fairly dangerous, so in the Advanced Java course I recently taught with Mallon Associates I wanted to build an example that would capture the attention of the delegates. It covers four topics that we may be forgiven for forgetting Java is capable of.

The topics that I was aiming to teach amongst others were:

  • NIO2 file watch service API
  • Classloaders
  • Compilation of code at runtime
  • Reflection
The example I came up with was the WatchingClassLoader. The WatchingClassLoader is a toy example which watches a folder for the arrival of a new file. When a file lands in the inbox it checks to see whether it is a .class file or .java file. If it is a .class file the class loader will load it, if it is a .java file it first compiles it and then loads the compiled version. The main thread also holds a loop waiting for input into the terminal, this allows the user to specify a class and see via reflection the methods of the now loaded class within system. As the class loader is hierarchical if it is asked for a class it doesn't know about it defers to the parent. It works with simple classes that are in the default package (i.e. no package) - though it could be extended to be smarter. 

WatchService


The WatchService is a neat API that allows you to register a Path to monitor for a particular file based event to occur. You can specify the type of event that you are interested in using the StandardWatchEventKinds class. Using the .take() method on the watcher blocks until that event occurs. In the final example this runs on a separate thread.

Class Loader


It is possible to write your own class loader in Java. By default the class loader in Java looks on the classpath specified when running the java command - but more often this is provided from your build system specifying the path to all the library jars your running application will require. Class loading is lazy, so a class is only loaded into the system when it is first required - this is why your code can sometimes run for years and then when it goes down a spurious code path you suddenly find yourself with a ClassNotFoundException.

Writing a custom class loader gives you the opportunity to change this default behaviour. Examples of class loaders might be that when a class is requested it is loaded from a remote network location or your class files are stored in an encrypted format and the class loader is responsible for decrypting the file. In this case I just want to load the class in from where I am watching for new files to be added. To create your own class loader you need to extend the ClassLoader abstract class.

At minimum you need to be looking to override the loadClass method and basically get a byte array of the contents of class file to load. From here you need to call resolveClass and defineClass to correctly load the class into the virtual machine. My system works by checking if the class aiming to be loaded is visible in the directory I am watching - otherwise it defers to the parent class loader to load the class. Class loaders are hierarchical in nature so this is an acceptable way of delegating upwards the loading of the class. The situation that this occurs in my mini example is when the user types something like java.lang.String into the console. A cutdown example of how to do this is below.

Compiling on the Fly


One feature that surprised many of the people who took my course was that it is possible to invoke the Java Compiler from within an executing Java process. ToolProvider allows us to get hold of the JavaCompiler and from there we can pass in a CompilationTask which contains the .java file we are looking to compile. This is best shown by example: 

Reflection


The final stage is reflection, which allows the user to look at the .java file or .class file they have added to the running system. In a demo this is the closest we get to the wow moment :). Reflection is the Java mechanism that allows inspection of a class at runtime. Most people are using reflection, even if they don't know they are doing so, as it is heavily used in frameworks such as Spring. In the example I just print out the methods as this is enough to prove the point, though on the actual course we use reflection for many other purposes including to invoke methods and generally prove what is possible. The simple snippet for allowing reflection on our classes via a custom class loader looks like this:

The Full Project


You can find the full toy example that you can run and play around with on GitHub. As this is a teaching example, there are plenty of places that this could be taken further - so I welcome any pull requests or tidy up to the code. It was actually something originally produced via live coding in front of the class, which has been a fairly tricky learning curve to get used to. That said now I wouldn't run a course without live coding, as it's where you get the most questions and although it's massively stressful it makes for a great session.

Saturday 12 July 2014

Update and New Career

I thought it was about time I dropped an update onto the blog about why I've been quiet recently and what has been going on.

Early this year I decided to change career paths slightly and become a technical trainer. The highlights of my career as a developer have been to help others improve and learn from others in an informal supportive environment. I am now lucky enough to be able to do this full time designing new and fun ways of helping others learn Java, Python, C++ and .NET technologies. I work for my own company James Gough Ltd, with one primary client Mallon Associates. So far I've run ten training courses and had people booking onto my future courses, it's been challenging but one of the best things I've done. I have a fairly packed end to 2014 as I gear up for our 15 week training program.

As well as working on private training I have also teamed up with Richard Warburton and Raoul-Gabriel Urma. I am excited to announce will be offering public Java 8 courses with a focus on Lambdas and preparing Java developers for the changes that are right on our doorstep. Java as we know it is going to change, for years some developers have been dragging their feet with Java 1.4 style syntax and missing some key changes. An appreciation for the Object Oriented/Functional relationship is now required to both be able to design and build code that is succinct and solves the business problem in the best way.

This year is very busy with it being my first year in business and getting married so sadly I've had to put conferences on hold for a year, but I'm hoping that early next year I can attend jfokus.


Friday 24 January 2014

Live Coding on Java 8 Date Time API

Yesterday I recorded a live coding session on java.time. Below is all the information so you can code along if you like:

The Video


The Source Code

All the source code is freely available on github you can get this running the following command:

The (brief) details for setting up the IDE can be found in the readme.

The Slides