Before going on a too short vacation I attended the Developer Open Space conference in my home town Leipzig. As the conference name suggests this was an Open Space conference where the participants them self create the agenda for the day.
I held a session on modern C development which was a high level summary of my past posts here. The slides are now online:
Sonntag, 25. Oktober 2015
Mittwoch, 30. September 2015
Software Craftsmanship in Leipzig
I started hosting the meeting of the Leipzig branch of the German software craftsmanship community Softwerkskammer. This is also a reason why I am short on blog posts here. Anyway, it's good fun. We try to team with the hardware nerd at Makerspace Leipzig by meeting us at there premises. We think this is a better fit than meeting in some companies (clean) office environment.
Dienstag, 29. September 2015
Markdown Presentations
I plan to do offer a session on modern C development called Not Your Fathers C at the Developer Open Space conference in Leipzig/ Germany. For that purpose I was looking for a way to prepare slides not in some proprietary format like Powerpoint but in pure text which is rendered to something nice.
After one evenings search engine investigation for me the way to go forward is remark which lets you create Markdown based presentations which can also be run offline. Very neat.
After one evenings search engine investigation for me the way to go forward is remark which lets you create Markdown based presentations which can also be run offline. Very neat.
Samstag, 26. September 2015
Socrates 2015 - What the f**k
I'm a IT professional for over a decade now - but I've never attended something like this before:
A colleague and me took part at the Socrates 2015 conference. It's an Open Space conference which mean there is no agenda at the beginning. Just an empty flipchart which if filled with self-proposed topics of the participants at the beginning of each conference day.
No pop star like speakers but people like you and me how admit "I am not the expert but I've done something in that field and I want to share this knowledge with you." For me this is all you need - for everything more involved there are books.
While thinking about the conference I was astonished how much I've either learned or was pushed towards something. Here is my top 5:
A colleague and me took part at the Socrates 2015 conference. It's an Open Space conference which mean there is no agenda at the beginning. Just an empty flipchart which if filled with self-proposed topics of the participants at the beginning of each conference day.
No pop star like speakers but people like you and me how admit "I am not the expert but I've done something in that field and I want to share this knowledge with you." For me this is all you need - for everything more involved there are books.
While thinking about the conference I was astonished how much I've either learned or was pushed towards something. Here is my top 5:
- Sketchnotes. This is for me "Doing something more with the whiteboard than the usual stuff without needing to be an artist." I believe in the area of Powerpoint spoilt organisations it makes a huge difference to develop a topic just with a flipchart and a pen. It's amazing how much you can do. I love it.
- Walking Skeleton. I never heard of this topic before. It's basically an approach to build up a system not from inside out but from outside to the inside, guided by so called end-to-end tests as well as unit tests. The book to read on that topic is Growing Object Oriented Software Guided By Tests. People refer to the approach as "London School Of TDD" (the authors of that book are based in London) in contrast to the "Chicago School Of TDD" which is TDD as we know it (Kent Beck, Uncle Bob). Really interesting.
- Personal Kanban. I was once again pushed to think about my time management method. I attended a session about Knowledge Management but we soon found out the the key is actually Time Management. So one of the attendees offered a session about time management the next day. It all was about the guys Getting Things Done interpretation. Anyway, during the discussion I was reminded on the existence of Personal Kanban, and this is what I am trying out at the moment, all analog!. There will be a post with a nice picture somewhen later.
- Legacy Code Retreat. I spent quite some time wadding into muddy legacy C code. I thought I am quite good at this topic but this guy who hosted a 2 hour session an how to attack lagacy code was somewhere else. Really impressive. I've done some handson training for a Golden Master Test. Also, training people to deal with legacy code can be simplified by using Adrians work.
- I had a chat with somebody at dinner how was working for a software consultancy run as a cooperative. Basically, they have no boss and decide all together how they want the company to proceed. This was really thrilling, I was just about to hand in my CV but they are based in the wrong city ;-).
Overall the conference was much more than I expected. In my hometown Leipzig/ Germany there will be the Developer Open Space conference in some weeks, run also as an Open Space event - this time I plan to prepare something my self. Working title "Not Your Father's C".
![]() |
| Yes - there were also some hippies ;-) |
Dienstag, 4. August 2015
Uncle Bob On Videos
For those of you who are even later than me: Uncle Bob, famous for his Clean Code book has produced a series of one hour videos which cover the topics of the book - but in a very funny and at the same time educational way: Clean Code Videos
Sonntag, 2. August 2015
Bash syntax check
When automating your administrative tasks also shell scripts are checked in to a version control system. The built-in command line argument -n allows a syntax check of the shell script without executing it:
$ bash -n myScript.sh $ echo $? 0If the syntax check is successful nothing is displayed and the exit code is 0. However, if there is an error (like in the following case a missing parenthesis) an error message is printed and the exit code is 2:
$ bash -n myScript.sh ./myScript.sh: line 23: syntax error: unexpected end of file $ echo $? 2When checking your scripts in that way inside your continuous delivery pipeline it is easy to spot simple type errors.
Freitag, 31. Juli 2015
Dependency Breaking in bash
In times of Devops you might want to also (unit) test your shell scripts. A collegue of mine introduced me to a nice trick how to do dependency breaking with bash.
The following script sketches how to utilize this feature to replace an original function with a stub at run time:
The replacement function is just an empty stub. When executing the stubbed version of doComplicatedThings than as expected nothing happens. Calling eval restores the original function so that the second call of doComplicatedThings prints out the original message.
The technique is based on the declare -f command which allows you to print the definition of previously defined function:
$ sayHello() { echo "hello world";}
$ declare -f sayHello
sayHello ()
{
echo "hello world"
}
The following script sketches how to utilize this feature to replace an original function with a stub at run time:
#!/bin/bash
doComplicatedThings() {
echo "i am doing many complicated things"
# ...
}
codeOfOriginalFunction=$(declare -f doComplicatedThings)
# stub out "doComplicatedThings"
function doComplicatedThings { :; }
# executes stub (does nothing)
doComplicatedThings
# re-establish orignal function
eval "${codeOfOriginalFunction}"
# executes the original function
doComplicatedThings
The function doComplicatedThings is the production function which might have been loaded from an external script file via the source command. The definition of doComplicatedThings is then saved as a string into codeOfOriginalFunction.The replacement function is just an empty stub. When executing the stubbed version of doComplicatedThings than as expected nothing happens. Calling eval restores the original function so that the second call of doComplicatedThings prints out the original message.
Dienstag, 12. Mai 2015
My Favorite Things - A One Time Downloader
For this blog it's a quiet year so far. I'm busy with work related stuff. Also, I'm collecting material for a book a colleague of mine and me are planning to write, more on that later.
Since Google Code is closing down I had to move an other old project of mine to github.com. It's a plain old CGI applications which allows small Do It Yourself (DIY) vinyl record labels to create small download vouchers for their releases. Being a vinyl collector myself five years back most of the vinyl records I bought came without any legal possibility to obtain the music in digital format as well.
I wanted to make the world a little better here. Over the years the software has been used around the world. I was occasionally in touch with users. Some of them where so happy about the tool that they've send my a bunch of records they recently released.
This project was my first time getting out to the world with some software I developed. Back then I decided to use Perl as implementation language. For the reasons see here.
Nowadays I still would choose a dynamically typed language but I guess it would be Python then.
Since Google Code is closing down I had to move an other old project of mine to github.com. It's a plain old CGI applications which allows small Do It Yourself (DIY) vinyl record labels to create small download vouchers for their releases. Being a vinyl collector myself five years back most of the vinyl records I bought came without any legal possibility to obtain the music in digital format as well.
| Downloading the MP3 files for "A very good Record" |
This project was my first time getting out to the world with some software I developed. Back then I decided to use Perl as implementation language. For the reasons see here.
Nowadays I still would choose a dynamically typed language but I guess it would be Python then.
Mittwoch, 25. Februar 2015
A Node.js based PLC Emulator
I just uploaded an old project of mine to Github: https://github.com/samba2/ripley/
Many thanks to my girlfriend Franziska for drawing Mr. Ripley above.
Background
Some years back a tried to get my head around Javascript and Node.js in particular. The latter one was quite new and you would read about it everywhere.
Based on some ideas from work I started implementing an idea I had for a long time: In a production environment their are many Programmable Logic Controller (PLCs) which communicate with a background system. To test the background systems logic it is common to replace the PLC with an emulation software. This software is than acting like the PLC (sending messages, receiving messages...).
At the time I was in charge of the background system including the required programming. Since the emulation software is complex we always required a separate emulation programmer for testing. My idea was create an alternative emulator which was configurable by a config file and which could cover 80% of the usual emulation cases.
I had good fun implementing my idea, working with Node.js went reasonable well. However, by the time when I finished I had a much better idea which is in use now: instead of impersonating a PLC I found out is much easier to write integration scripts on the background system itself which would trigger the same actions as the PLC emulator would have triggered.
Those scripts follow the xUnit style of programing tests and are way more broader and flexible.
The github repository is where Ripley is now laid to rest.
Sonntag, 22. Februar 2015
Quick C Tricks - Assertions With Error Message
This quick post is the last little trick I got out of the book Patterns in C written by Adam Tornhill. The technique presents comments for assertions which also appear as an error message if failing.
Here is an example:
Running the code gives the following result:
This trick works since the string This is an error message itself evaluates to True. The actual checking is taking place in the first part of the assertion, a second appended True does not influence this behavior.
You can argue that this is a hack (that's true) but giving the user some guidance in the event of failure is also not a bad idea.;
Here is an example:
#include <assert.h>
int main() {
assert(1 == 2 && "This is an error message");
}
Running the code gives the following result:
main: Assertion `1 == 2 && "This is an error message"' failed.
This trick works since the string This is an error message itself evaluates to True. The actual checking is taking place in the first part of the assertion, a second appended True does not influence this behavior.
You can argue that this is a hack (that's true) but giving the user some guidance in the event of failure is also not a bad idea.;
Mittwoch, 18. Februar 2015
Review of "Patterns in C" by Adam Tornhill
Twenty one years ago the book Design patterns : elements of reusable object-oriented software changed the way object oriented software was written. Some month back I asked myself if somebody has tried to apply those ideas to plain C. Although C has no object orientation build in, using Abstract Datatypes (ADT) it is possible and also preferable to structure C code in an object oriented manner.
My research lead me to the online book "Patterns in C" by Adam Tornhill, available as PDF or epub from leanpub.com. This book combines a couple of blog posts the author did over the course of years. Not unexpected, the book is introducing ADT in C as prerequisite for the rest of the book.
All the design patterns presented in the book share a second similarity: They all gain their flexibility through the consequent usage of C function pointers. I admit, I did barely touch them in the past. After having read this book I still believe you should not overuse them but they give you flexibility in your programming you would not expect to find in good old C.
But let's look at the first chapter. It deals with the implementation of a state machine. The author quickly illustrates the classic approaches being simple case statements and a table based approach. He then argues that those classic approaches are not scaling to the big which lets him introduce a C take on the STATE pattern. I personally found that example rather confusing but I would consult it a second time if a state machine is on my C development agenda.
The next chapter deals with the STRATEGY pattern. This is also my favorite chapter of the book. The example given shows how a customer record can be designed leaving certain calculations interchangeable. This is a good example of how modern C can look like and something which is already in my personal tool box.
The following chapter introduces an example implementation of the OBSERVER pattern. The idea is that an object can have one or more subscribers which get informed if the internal state (e.g. measuring data) of the object changes. The subscribers can then decide what to do with this information. It turns the object communication, excuse me, I mean the ADT communication upside down from polling ("Did something change at your side?") to pushing: "Attention, something changed at my side!"
As with the STRATEGY pattern before the main ingredients for the OBSERVER chapter are ADTs and function pointers. The implementation is pleasant to work through and surprisingly straight forward.
The last pattern discussed is the REACTOR pattern. Here, an event is received and dispatched to the appropriate event handler. Although the patterns logic is simple, I had my difficulties to see that logic happening in the code. Maybe reading not only snippets but the whole example would have helped.
The book closes with a couple of C tricks of which I already posted Simulate Keyword Arguments here. This last chapter also shows my general problem with the book: it is too verbose and also trying to be too intellectual. At the end we talk about established programming conventions in the OO world and their adaption in C. This is straight forward software engineering where a Kafka quote feels a bit out of turn.
Concluding, I learned that function pointers are an important tool towards a flexible design. Together with ADTs they make the implementation of established OO design patterns possible also in C. The book itself is not an easy read, though.
My research lead me to the online book "Patterns in C" by Adam Tornhill, available as PDF or epub from leanpub.com. This book combines a couple of blog posts the author did over the course of years. Not unexpected, the book is introducing ADT in C as prerequisite for the rest of the book.
All the design patterns presented in the book share a second similarity: They all gain their flexibility through the consequent usage of C function pointers. I admit, I did barely touch them in the past. After having read this book I still believe you should not overuse them but they give you flexibility in your programming you would not expect to find in good old C.
But let's look at the first chapter. It deals with the implementation of a state machine. The author quickly illustrates the classic approaches being simple case statements and a table based approach. He then argues that those classic approaches are not scaling to the big which lets him introduce a C take on the STATE pattern. I personally found that example rather confusing but I would consult it a second time if a state machine is on my C development agenda.
The next chapter deals with the STRATEGY pattern. This is also my favorite chapter of the book. The example given shows how a customer record can be designed leaving certain calculations interchangeable. This is a good example of how modern C can look like and something which is already in my personal tool box.
The following chapter introduces an example implementation of the OBSERVER pattern. The idea is that an object can have one or more subscribers which get informed if the internal state (e.g. measuring data) of the object changes. The subscribers can then decide what to do with this information. It turns the object communication, excuse me, I mean the ADT communication upside down from polling ("Did something change at your side?") to pushing: "Attention, something changed at my side!"
As with the STRATEGY pattern before the main ingredients for the OBSERVER chapter are ADTs and function pointers. The implementation is pleasant to work through and surprisingly straight forward.
The last pattern discussed is the REACTOR pattern. Here, an event is received and dispatched to the appropriate event handler. Although the patterns logic is simple, I had my difficulties to see that logic happening in the code. Maybe reading not only snippets but the whole example would have helped.
The book closes with a couple of C tricks of which I already posted Simulate Keyword Arguments here. This last chapter also shows my general problem with the book: it is too verbose and also trying to be too intellectual. At the end we talk about established programming conventions in the OO world and their adaption in C. This is straight forward software engineering where a Kafka quote feels a bit out of turn.
Concluding, I learned that function pointers are an important tool towards a flexible design. Together with ADTs they make the implementation of established OO design patterns possible also in C. The book itself is not an easy read, though.
Sonntag, 11. Januar 2015
A software engineer does for a dime what any fool can do for a dollar - SICP Finished
Done! Done! Really, no kidding. It took longer than expected but eventually I'm done with my self study of the online material of Computer Science 61A, Spring 2014 edition. The course is a modernized version of the material in "Structure And Interpretation Of Computer Programs" (SICP).
For more informations on why I initially started the course see my post from March 2014.
This post is about my lessons learned, findings and experiences.
General Software Engineering Findings
A great quote from the lecture (for a geek T-shirt maybe?): A software engineer does for a dime what any fool can do for a dollar. The key to such an efficiency is abstraction and separation of concerns.
This wasn't knew to me but it was good to see that those concepts were not invented by the "object-oriented people". They've made the idea popular but you also can achieve nice abstraction layers in your code by only using functional programing, see this section of the original SICP book for a good example.
Recursive Thinking
Before I started the course I probably never wrote a recursion - at least not by intention. In SICP recursion is an important concept and I had solve many different exercises on that topic. Over time I believe I can say I've adopted the recursive thinking.
The most important idea here is the leap of faith. This is a way of thinking which help dealing with recursion: Since it is hard to play a whole recursion through in your head (particularly for complicated tasks) develop your code with a simpler variant of the original problem in mind and believe that the recursion will also work for the more complex variants.
Read Eval Print Loop (REPL)
These days I wouldn't start a bigger programing project without having a REPL available. A REPL gives you an interactive way to try out some pieces of code before adding it to your actual program.
Ideally you can interact with your programming language line by line - like in Python: Type in python and you're inside the REPL where your can program interactively. For Javascript on the server side node.js offers something very similar. For client side Javascript just use the console of the browsers development mode (F12).
For Java I utilize the Eclipse Scrapbook, for C I sometimes use codepad.org. Those last two examples are no REPLs since they are not interactive but at least they provide some convenient way to try out code. For C I might use straight gdb next time - we'll see how well that goes.
Functional Programming
SICP is heavily relying on the power of higher order functions. That is due to the Scheme heritage of the course material. In the original SICP book (the wizard book) the possibility to assign values to a variable is mentioned somewhen in the middle of the book. This modern version of the course is not as puristic.
The further you work your way through the course material you see functional programming being used side by side with classic procedural and object oriented programming. In my opinion this is what makes Python such an interesting language: you pick the programing paradigm (the tool) which fits best for the job to be done.
I did some Javascript coding recently and used this occasion to re-read Eloquent Javascript. After having taking SICP this whole fuzz about Javascript functions is now much less confusing. The syntax could be more elegant though ;-)
Object Oriented Programing
Due to my efforts in structuring my work C code I was aware of Abstract Data Types (ADT) before. In the course we've pushed this idea further: We've been using Python to implement an own object model including inheritance. This object model stood beside the build-in OO-features of Python.
This was an impressive and eye opening experience. Now I eventually know how to give the bash OO-capabilities ;-)
To quote the teacher, Professor Hillfinger: Object oriented programing is just a disciplined way to structure your programs.
Declarative Programing
The last quarter of the course had a huge emphasis on declarative programing. We've learned the concept, discussed a simple interpreter of a small invented declarative language written in Python. This language was a mix of Prolog (the structure) and Scheme (the brackets).
I saw that this is a very different way to approach solving a problem and that you should be aware of it. However, for my taste we've spend too much time on coding exercises with this little academic teaching.
Python as The Courses Main Language Language
Many years back my first programing language was Perl which impressed me with the power of a couple of code lines. Python is for me Perl done right - a multi purpose high-level scripting language with an easy to read syntax. At least Python doesn't share Perl (bad) reputation for cryptic one-liners.
Writing some Java after having done Python makes me feel like "Is the handbrake still pulled?" - not to mention my emotions going from Python back to application programing in C.
Scheme - Your Fathers Brackets
The original material of the course was entirely held in Scheme. In the new version the main programming language was Python but Scheme was still very present.
After doing some Scheme syntax and coding exercises the last project was about writing an own Scheme interpreter in Python. I wouldn't say that I'm now an expert in designing programming language but if I would ever get the task to implement an own language I definitely have a clear idea of the basic concept - a constant (meaning recursive) evaluation and application of a stream of input tokens.
This concept is so fundamental that it made it on the originals book title:
I have to say that I haven't become a big Lisp/ Scheme enthusiast. I still found the syntax rather confusing. However, I can image that it could be fun coding a bigger project and thus spending more time with the language..
Time Management
I started the course when I was off on parental leave for two months. At the beginning of that time I appointed one full day per week for the course work, in the second month I increased to two days per week. Additionally, I was watching the lecture screencasts in the evenings at home.
To stay focused I tried to study at my local universities library as often as I could.
When I started working again things slowed down. I tried to shift my study time to the evenings but my performance is not the best after 8:30 pm, particularly when you're not "just coding" but trying to solve tricky lab tasks. Additionally, work (a lot of mighty C programming) was quite involving.
The trick was to believe in small steps and to celebrate every complete homework, discussion or lab assignment.
At the beginning I tried to do all homework tasks, also the extra credits. When I saw my pace going down I decided to be just an average student and to focus only the compulsory work. My pace increased again and I realized that to be average in my situation was a good decision. It was my trade off being a full time worker, committed family father and a remote student at the same time.
Self Paced Learning
The course wasn't designed as a self study course. However, the lecture screencasts where great, I watched them all, some of them more than once. I found out that my brain digests new ideas better if new material is first presented/ explained to me and then I start practicing on my own.
The study guide Composing Programs also helped a lot to approach a topic from a second side (first listen to the screencast, second read in the book).
When we've learned about environment diagrams, the Online Python Tutor was very helpful. It's basically a graphical debugger for smaller code snippets which nicely illustrates the environment frames involved and their content.
Most of the hands-on assignments (labs, homework, projects) came with unit tests which described the intended behaviour of the functionality to be implemented. This way I could always check my implementation. Solutions were also available (with the exception of the projects).
Maybe the biggest problem for me was the lack of support from somebody else. As an enrolled student there are assigned teaching assistants (TAs) to help you. If I had questions I only had the Google search on my side which wasn't always as effective.
Particularly when I got into writing recursive functions I was sometimes fighting for hours to finish a task. Of course I only could have looked up the solution but this wasn't my intent - the whole purpose of my studies was to deeply understand the material.
Bigger projects where intended to be work on by small teams. As a one man team I did all the tasks on my own. This was also one reason why I took my longer then planned to finish the course.
Next Steps And Follow Up Courses
Online courses are great. They have their limitation once you get into project or group work. But e.g for learning a new programming language or library sites like codeschool.com are nowdays first choice for me. Infact, I would rather take a week off and work my self through a quality online course than attending a real life training. Check out this AngularJS course as an example for what I mean.
I was a bit disappointed that CS169.1x had already started when I finished: CS169.1x teaches the fundamentals of software engineering using Agile techniques to develop Software as a Service using Ruby on Rails. They have now the archived material available so I might work my self through that course again - we'll see.
Conclusion
It was fun and I definitely would do it again. Also for me the modern Python version of the course was more appealing than the pure text book based study of the old Scheme book.
For more informations on why I initially started the course see my post from March 2014.
This post is about my lessons learned, findings and experiences.
General Software Engineering Findings
A great quote from the lecture (for a geek T-shirt maybe?): A software engineer does for a dime what any fool can do for a dollar. The key to such an efficiency is abstraction and separation of concerns.
This wasn't knew to me but it was good to see that those concepts were not invented by the "object-oriented people". They've made the idea popular but you also can achieve nice abstraction layers in your code by only using functional programing, see this section of the original SICP book for a good example.
Before I started the course I probably never wrote a recursion - at least not by intention. In SICP recursion is an important concept and I had solve many different exercises on that topic. Over time I believe I can say I've adopted the recursive thinking.
The most important idea here is the leap of faith. This is a way of thinking which help dealing with recursion: Since it is hard to play a whole recursion through in your head (particularly for complicated tasks) develop your code with a simpler variant of the original problem in mind and believe that the recursion will also work for the more complex variants.
Read Eval Print Loop (REPL)
These days I wouldn't start a bigger programing project without having a REPL available. A REPL gives you an interactive way to try out some pieces of code before adding it to your actual program.
Ideally you can interact with your programming language line by line - like in Python: Type in python and you're inside the REPL where your can program interactively. For Javascript on the server side node.js offers something very similar. For client side Javascript just use the console of the browsers development mode (F12).
For Java I utilize the Eclipse Scrapbook, for C I sometimes use codepad.org. Those last two examples are no REPLs since they are not interactive but at least they provide some convenient way to try out code. For C I might use straight gdb next time - we'll see how well that goes.
Functional Programming
SICP is heavily relying on the power of higher order functions. That is due to the Scheme heritage of the course material. In the original SICP book (the wizard book) the possibility to assign values to a variable is mentioned somewhen in the middle of the book. This modern version of the course is not as puristic.
The further you work your way through the course material you see functional programming being used side by side with classic procedural and object oriented programming. In my opinion this is what makes Python such an interesting language: you pick the programing paradigm (the tool) which fits best for the job to be done.
I did some Javascript coding recently and used this occasion to re-read Eloquent Javascript. After having taking SICP this whole fuzz about Javascript functions is now much less confusing. The syntax could be more elegant though ;-)
Object Oriented Programing
Due to my efforts in structuring my work C code I was aware of Abstract Data Types (ADT) before. In the course we've pushed this idea further: We've been using Python to implement an own object model including inheritance. This object model stood beside the build-in OO-features of Python.
This was an impressive and eye opening experience. Now I eventually know how to give the bash OO-capabilities ;-)
To quote the teacher, Professor Hillfinger: Object oriented programing is just a disciplined way to structure your programs.
Declarative Programing
The last quarter of the course had a huge emphasis on declarative programing. We've learned the concept, discussed a simple interpreter of a small invented declarative language written in Python. This language was a mix of Prolog (the structure) and Scheme (the brackets).
I saw that this is a very different way to approach solving a problem and that you should be aware of it. However, for my taste we've spend too much time on coding exercises with this little academic teaching.
Python as The Courses Main Language Language
Many years back my first programing language was Perl which impressed me with the power of a couple of code lines. Python is for me Perl done right - a multi purpose high-level scripting language with an easy to read syntax. At least Python doesn't share Perl (bad) reputation for cryptic one-liners.
Writing some Java after having done Python makes me feel like "Is the handbrake still pulled?" - not to mention my emotions going from Python back to application programing in C.
Scheme - Your Fathers Brackets
The original material of the course was entirely held in Scheme. In the new version the main programming language was Python but Scheme was still very present.
After doing some Scheme syntax and coding exercises the last project was about writing an own Scheme interpreter in Python. I wouldn't say that I'm now an expert in designing programming language but if I would ever get the task to implement an own language I definitely have a clear idea of the basic concept - a constant (meaning recursive) evaluation and application of a stream of input tokens.
This concept is so fundamental that it made it on the originals book title:
![]() |
| Quelle: http://icampus.mit.edu/files/2011/12/xTutor1.jpg |
I started the course when I was off on parental leave for two months. At the beginning of that time I appointed one full day per week for the course work, in the second month I increased to two days per week. Additionally, I was watching the lecture screencasts in the evenings at home.
To stay focused I tried to study at my local universities library as often as I could.
When I started working again things slowed down. I tried to shift my study time to the evenings but my performance is not the best after 8:30 pm, particularly when you're not "just coding" but trying to solve tricky lab tasks. Additionally, work (a lot of mighty C programming) was quite involving.
The trick was to believe in small steps and to celebrate every complete homework, discussion or lab assignment.
At the beginning I tried to do all homework tasks, also the extra credits. When I saw my pace going down I decided to be just an average student and to focus only the compulsory work. My pace increased again and I realized that to be average in my situation was a good decision. It was my trade off being a full time worker, committed family father and a remote student at the same time.
Self Paced Learning
The course wasn't designed as a self study course. However, the lecture screencasts where great, I watched them all, some of them more than once. I found out that my brain digests new ideas better if new material is first presented/ explained to me and then I start practicing on my own.
The study guide Composing Programs also helped a lot to approach a topic from a second side (first listen to the screencast, second read in the book).
When we've learned about environment diagrams, the Online Python Tutor was very helpful. It's basically a graphical debugger for smaller code snippets which nicely illustrates the environment frames involved and their content.
Most of the hands-on assignments (labs, homework, projects) came with unit tests which described the intended behaviour of the functionality to be implemented. This way I could always check my implementation. Solutions were also available (with the exception of the projects).
Maybe the biggest problem for me was the lack of support from somebody else. As an enrolled student there are assigned teaching assistants (TAs) to help you. If I had questions I only had the Google search on my side which wasn't always as effective.
Particularly when I got into writing recursive functions I was sometimes fighting for hours to finish a task. Of course I only could have looked up the solution but this wasn't my intent - the whole purpose of my studies was to deeply understand the material.
Bigger projects where intended to be work on by small teams. As a one man team I did all the tasks on my own. This was also one reason why I took my longer then planned to finish the course.
Next Steps And Follow Up Courses
Online courses are great. They have their limitation once you get into project or group work. But e.g for learning a new programming language or library sites like codeschool.com are nowdays first choice for me. Infact, I would rather take a week off and work my self through a quality online course than attending a real life training. Check out this AngularJS course as an example for what I mean.
I was a bit disappointed that CS169.1x had already started when I finished: CS169.1x teaches the fundamentals of software engineering using Agile techniques to develop Software as a Service using Ruby on Rails. They have now the archived material available so I might work my self through that course again - we'll see.
Conclusion
It was fun and I definitely would do it again. Also for me the modern Python version of the course was more appealing than the pure text book based study of the old Scheme book.
Labels:
courses,
Own Projects,
Python,
Scheme,
SICP
Sonntag, 7. Dezember 2014
Quick C Tricks - Simulate Keyword Arguments
Here is a little trick I found in the book Patterns in C written by Adam Tornhill. It will give you a syntax which looks like there are keyword arguments in C - but in fact there aren't:
Beside my unit tests I believe I won't use this syntactic sugar that often. If there is the need to pass in a couple of arguments to a function I would use this technique which relies on compound literals and designated initializers.
... int a, b, result; result = sum(a = 2, b = 3); ...This trick just moves the assignment of a and b insight the functions parameter section. However, this code is identical to:
... int a = 2, b = 3, result; result = sum(a,b); ...So it is just some eye candy but are there any useful applications for that? Well, yes. This technique helped me to write some easy to read unit test code where I wanted to be explicit what the arguments of the function under test stand for.
Beside my unit tests I believe I won't use this syntactic sugar that often. If there is the need to pass in a couple of arguments to a function I would use this technique which relies on compound literals and designated initializers.
Sonntag, 30. November 2014
Quick C Tricks - Structured Include Path
In a larger C project you might want to have your API (=the collection of your header files) more structured instead of throwing all the header files into one flat directory.
The cpputest project is using a nice and simple approach. Their software (a C and C++ unit test library we are using at work) consists out of core functions and extended functionality.
Here is a sketch of the include path layout:
This structuring approach gives you simple namespacing of your headers - which also your Java co-works will appriciate ;-)
The cpputest project is using a nice and simple approach. Their software (a C and C++ unit test library we are using at work) consists out of core functions and extended functionality.
Here is a sketch of the include path layout:
/.../cpputest/include/
CppUTest/
MemoryLeakDetector.h
TestHarness.h
...
CppUTestExt/
GMock.h
MockFailure.h
...
The compiler gets the main include directory -I/.../cpputest/include/. In your code (for example to start writing a unit test) you include the remaining path:#include <CppUTest/TestHarness.h> ...Looking at this include line you instandly know that TestHarness.h belongs to CppUTest and (if you are familiar with the library) it is part of the core functionality (=not inside CppUTestExt).
This structuring approach gives you simple namespacing of your headers - which also your Java co-works will appriciate ;-)
Freitag, 28. November 2014
Quick C Tricks - Explicit Declaration Of String Terminator Byte
In C a string is an array of single characters terminated by the NUL-value ('\0'). I came across the following notation to clearly communicate this fact:
// declaring a 10 byte long string buffer which // will be later terminated by '\0' char myString[10+1];Of couse I could have written the above line like this:
// same thins as above but not that obvious char myString[11];It's a cosmetical thing - but they help to improve the readability of your code.
Dienstag, 25. November 2014
Learning Tests - Something you Shouldn't Smile About
I admit - at university I was one of the guys who would rarely attent a non-technical course. Just because I thought that this is the easy stuff - I don't need to waste my time with that.
Well, this aditute has changed. Over the years I've learned the benefits of reflecting your work style, your personal progress and so on. Attempting to follow the principles of the agile manifesto is one of these findings.
The topic of this post are Learning tests, something a collegue of mine introduced to me and which I problably would have smiled about in university since it is not technical in itself - but it is a nice and easy way to invest your (usually limited) coding time carefully.
So what is it all about?Learning tests is about using your existing unit test framework to have a play with some new library function or class you haven't used before (or a long time ago). You are writing tests not against your own implementation but against the currently not so well understood new library function/ class you are planing to use in your own implementation later.
Learning tests are a kind of a step in between - the unit tests for a new feature you are planning to implement are there but you feel that you should examine the internal mechanics you will utilize for the implementation a little bit further (e.g. some complicated external library).
At this stage you slide in one ore more Learning tests which are writting using your every day unit testing frame work and hence live on with all the other unit tests. In your Learning tests you have a play with the unknown library until you understand how to employ it in your own work. You then move on to your actual implementation.
That's all about it. Nice, simple and definitly helpful.
Well, this aditute has changed. Over the years I've learned the benefits of reflecting your work style, your personal progress and so on. Attempting to follow the principles of the agile manifesto is one of these findings.
The topic of this post are Learning tests, something a collegue of mine introduced to me and which I problably would have smiled about in university since it is not technical in itself - but it is a nice and easy way to invest your (usually limited) coding time carefully.
So what is it all about?Learning tests is about using your existing unit test framework to have a play with some new library function or class you haven't used before (or a long time ago). You are writing tests not against your own implementation but against the currently not so well understood new library function/ class you are planing to use in your own implementation later.
Learning tests are a kind of a step in between - the unit tests for a new feature you are planning to implement are there but you feel that you should examine the internal mechanics you will utilize for the implementation a little bit further (e.g. some complicated external library).
At this stage you slide in one ore more Learning tests which are writting using your every day unit testing frame work and hence live on with all the other unit tests. In your Learning tests you have a play with the unknown library until you understand how to employ it in your own work. You then move on to your actual implementation.
That's all about it. Nice, simple and definitly helpful.
Freitag, 21. November 2014
Fibonacci numbers with Oracle WITH clause (SQL recursion)
While studying the Declaritive Programming section of Composing Programs, I stumbled accross a SQL example which calculated the fibonacci numbers using the SQL WITH clause. Since this is at work my major secret weapon to tackle complex queries I changed the example to run on Oracle SQL:
For those of you who wonder what this CYCLE expression stands for this is a good summary:
When a node is encountered for the second time, it will be included in the result set, its column value IS_CYCLE (a new column [...] with the statement above) is set to Y and the recursion stops then and there – so there will not be a second iteration starting at this node. Note however that any node where a cycle starts is included in the result set twice. [source]
This example is also introducing a nice aspect of the WITH clause I wasn't aware of so far - you can provide the column names of the subquery as arguments. See those two snippets for what I mean:
WITH compute_fib(previous, curr) AS ( SELECT 0, 1 FROM dual UNION ALL SELECT curr, previous+curr FROM compute_fib WHERE curr < 60 ) -- Oracles endless loop protection CYCLE previous, curr SET is_cycle TO '1' DEFAULT 'Y' SELECT previous FROM compute_fib;
For those of you who wonder what this CYCLE expression stands for this is a good summary:
When a node is encountered for the second time, it will be included in the result set, its column value IS_CYCLE (a new column [...] with the statement above) is set to Y and the recursion stops then and there – so there will not be a second iteration starting at this node. Note however that any node where a cycle starts is included in the result set twice. [source]
This example is also introducing a nice aspect of the WITH clause I wasn't aware of so far - you can provide the column names of the subquery as arguments. See those two snippets for what I mean:
-- this is how I used to name the columns of a subquery.
-- the first SELECT of a UNION also defines the column names
WITH old_way AS
(
SELECT 1 AS first_row,
2 AS second_row
FROM dual
UNION ALL
SELECT 3, 4 FROM dual
)
SELECT * FROM old_way;
-- this is much clearer way where the subquery
-- explicitly defines the column names
WITH new_way(first_row, second_row) AS
(
SELECT 1, 2 FROM dual UNION ALL
SELECT 3, 4 FROM dual
)
SELECT * FROM new_way;
Sonntag, 2. November 2014
Reflections on SICP (Part 1) - Function dispatching in C
Yesterday I've committed the last work for the Scheme project of SICP. Work, namely a lot of mighty C coding is mainly responsible for not having finished the course yet. However, since I am in the last quarter of the course material I decided to recap from time to time - what are the things I've learned, what was good, what was surprising and so on.
One of my favorite learnings is the idea of a dispatch table. Instead of having a long list of if/elseif branches which direct to a certain function the idea is to have this dispatching being done in a hash table. Since the table is dynamic the dispatching can be changed at run time (late binding).
Although I appreciate the "get my quickly from A to B" qualities of Python most of my daily business is based on good old C and Java. In this post I want to sketch out how function dispatching could be implemented in C - as usual as high level as possible.
Here is a naive Python example of using a dispatch table. See the last code example of this post of a more Pythonic version. This following code will be the template of our transformation to C later:
Dispatching takes place in accumulateList where the dictionary dispatchTable is being looked up for the entry method. The function returned is directly executed, hence the numberList argument.
So let'S look at C. As a friend of high-level expressions I'm using as usual GLib data structures. GList for the number list and GHashtable for the dispatch table.
The code structure is close to the Python example before. A remark for the strange GINT_TO_POINTER and GPOINTER_TO_INT macros: This is the GLib way of storing and retrieving integers in their data structures. For more details refer to the GLib manual.
createDispatchTable uses a GLib GHashtable to store string to function pointer pairs.
accumulateList is retrieving the right function pointer by looking up the dispatch table. As the next step the function is executed and it's result is directly returned.
Usually I would append a common prefix to the public functions createDispatchTable(),
accumulateLis() and destroyDispatchTable() to indicate that they belong to one module (see here for details) but for this example I tried to keep it simple.
So what do we think about that. Well, of course we could add some macro magic to shrink certain function calls (like the g_list_append) but I tend to use the C language straight, falling back on the preprocessor only if I can't achieve my goals directly.
The reason for that is more related to (good) code style. A macro always adds a new level of indirection which needs to be resolved by a human brain when trying to understand the code. Eclipse CDTs macro expansion feature is definitly helpful here but I rather live without personal syntactic sugar.
The matter is different little fellows like GINT_TO_POINTER and GPOINTER_TO_INT. They represent a feature which can't be accomplished by using the language straight - so their fine.
I personally would like to see the definition of the dispatch table somehow outside a function, more prominent and if I could choose defined by something like designated initializers.
The GHashtable approach does not support that so we would need to replace it by something like a struct (e.g. DispatchTableEntry) and an array of these DispatchTableEntry struct. The accumulateList function would then iterate over this array of structs looking for the right entry.
I tried that approach but it has a couple of downsides. One thing is that for simple usage of designated initializers the dispatch table array ideally has a fixed size. My personal favorite, a NULL terminated array of unknown length would lead to a rather odd syntax. So there is a trade-off here.
Also, implementing my own lookup functionality in accumulateList isn't what I was looking for - I wanted to use this out of the shelf.
An other obvious approach would be to define enums for the function names and use them as an index of an ordinary C array where the value would be the according function pointer. The lookup would be just a simple array index access using the enum as well.
Beside the missing runtime flexibility (you can't add enums at runtime) this approach has the problem that you maintain data at two sections: a new dispatch route would mean an entry in enums (new function name) and an extra entry in the array (the actual dispatch entry).
To my knowledge the best solution for this double data maintenance issue are X macros whose philosophy dates back to the 1960s. When you're in a pure C environment (poor you) this would be my way to go.
After weighting my options I stuck with the C implementation above. To add a new dispatch route function createDispatchTable has to be extended. Everything else is using battle proof implementations (GLib functions) in favour of (once again) rolling my own stuff.
To summarize the C example: this is as good as it gets in (high-level) C.
To conclude I promised to provide a Pythonic version of our example:
That is more then 80 line of code in C versus 21 in Python - the same functionality, expressed more clearer (in my opinion) in 1/4 of the code ;-)
One of my favorite learnings is the idea of a dispatch table. Instead of having a long list of if/elseif branches which direct to a certain function the idea is to have this dispatching being done in a hash table. Since the table is dynamic the dispatching can be changed at run time (late binding).
Although I appreciate the "get my quickly from A to B" qualities of Python most of my daily business is based on good old C and Java. In this post I want to sketch out how function dispatching could be implemented in C - as usual as high level as possible.
Here is a naive Python example of using a dispatch table. See the last code example of this post of a more Pythonic version. This following code will be the template of our transformation to C later:
#!/usr/bin/python3
def _sumAll(numberList):
sum = 0
for number in numberList:
sum = sum + number
return sum
def _sumEven(numberList):
sum = 0
for number in numberList:
if number % 2 == 0:
sum = sum + number
return sum
def _multiplyAll(numberList):
prod = 1
for number in numberList:
prod = prod * number
return prod
dispatchTable = {
'sumAll' : _sumAll,
'sumEven' : _sumEven,
'multiplyAll' : _multiplyAll
}
def accumulateList(method, numberList):
return dispatchTable[method](numberList)
numbers = (2,4,5,6)
print(accumulateList('sumAll', numbers))
print(accumulateList('sumEven', numbers))
print(accumulateList('multiplyAll', numbers))
Dispatching takes place in accumulateList where the dictionary dispatchTable is being looked up for the entry method. The function returned is directly executed, hence the numberList argument.
So let'S look at C. As a friend of high-level expressions I'm using as usual GLib data structures. GList for the number list and GHashtable for the dispatch table.
#include <stdio.h>
#include <glib-2.0/glib.h>
static GHashTable* dispatchTable;
int _sumAll(GList* numberList) {
int sum = 0;
GList *iter = numberList;
while(iter != NULL) {
sum = sum + GPOINTER_TO_INT(iter->data);
iter = g_list_next(iter);
}
return sum;
}
int _sumEven(GList* numberList) {
int sum = 0;
GList *iter = numberList;
while(iter != NULL) {
int number = GPOINTER_TO_INT(iter->data);
if (number % 2 == 0) {
sum = sum + number;
}
iter = g_list_next(iter);
}
return sum;
}
int _multiplyAll(GList* numberList) {
int prod = 1;
GList *iter = numberList;
while(iter != NULL) {
prod = prod * GPOINTER_TO_INT(iter->data);
iter = g_list_next(iter);
}
return prod;
}
void createDispatchTable() {
dispatchTable = g_hash_table_new(g_str_hash, g_str_equal);
g_hash_table_insert(dispatchTable, g_strdup("sumAll"),
_sumAll);
g_hash_table_insert(dispatchTable, g_strdup("sumEven"),
_sumEven);
g_hash_table_insert(dispatchTable, g_strdup("multiplyAll"),
_multiplyAll);
}
int accumulateList(const char* method, GList* numberList) {
int (*func)(GList*);
func = g_hash_table_lookup(dispatchTable, method);
return func(numberList);
}
void destroyDispatchTable() {
g_hash_table_destroy(dispatchTable);
}
int main() {
GList* numbers = NULL;
createDispatchTable();
numbers = g_list_append(numbers, GINT_TO_POINTER (2));
numbers = g_list_append(numbers, GINT_TO_POINTER (4));
numbers = g_list_append(numbers, GINT_TO_POINTER (5));
numbers = g_list_append(numbers, GINT_TO_POINTER (6));
printf("%i\n",accumulateList("sumAll", numbers));
printf("%i\n",accumulateList("sumEven", numbers));
printf("%i\n",accumulateList("multiplyAll", numbers));
destroyDispatchTable();
g_list_free(numbers);
return 0;
}
The code structure is close to the Python example before. A remark for the strange GINT_TO_POINTER and GPOINTER_TO_INT macros: This is the GLib way of storing and retrieving integers in their data structures. For more details refer to the GLib manual.
createDispatchTable uses a GLib GHashtable to store string to function pointer pairs.
accumulateList is retrieving the right function pointer by looking up the dispatch table. As the next step the function is executed and it's result is directly returned.
Usually I would append a common prefix to the public functions createDispatchTable(),
accumulateLis() and destroyDispatchTable() to indicate that they belong to one module (see here for details) but for this example I tried to keep it simple.
So what do we think about that. Well, of course we could add some macro magic to shrink certain function calls (like the g_list_append) but I tend to use the C language straight, falling back on the preprocessor only if I can't achieve my goals directly.
The reason for that is more related to (good) code style. A macro always adds a new level of indirection which needs to be resolved by a human brain when trying to understand the code. Eclipse CDTs macro expansion feature is definitly helpful here but I rather live without personal syntactic sugar.
The matter is different little fellows like GINT_TO_POINTER and GPOINTER_TO_INT. They represent a feature which can't be accomplished by using the language straight - so their fine.
I personally would like to see the definition of the dispatch table somehow outside a function, more prominent and if I could choose defined by something like designated initializers.
The GHashtable approach does not support that so we would need to replace it by something like a struct (e.g. DispatchTableEntry) and an array of these DispatchTableEntry struct. The accumulateList function would then iterate over this array of structs looking for the right entry.
I tried that approach but it has a couple of downsides. One thing is that for simple usage of designated initializers the dispatch table array ideally has a fixed size. My personal favorite, a NULL terminated array of unknown length would lead to a rather odd syntax. So there is a trade-off here.
Also, implementing my own lookup functionality in accumulateList isn't what I was looking for - I wanted to use this out of the shelf.
An other obvious approach would be to define enums for the function names and use them as an index of an ordinary C array where the value would be the according function pointer. The lookup would be just a simple array index access using the enum as well.
Beside the missing runtime flexibility (you can't add enums at runtime) this approach has the problem that you maintain data at two sections: a new dispatch route would mean an entry in enums (new function name) and an extra entry in the array (the actual dispatch entry).
To my knowledge the best solution for this double data maintenance issue are X macros whose philosophy dates back to the 1960s. When you're in a pure C environment (poor you) this would be my way to go.
After weighting my options I stuck with the C implementation above. To add a new dispatch route function createDispatchTable has to be extended. Everything else is using battle proof implementations (GLib functions) in favour of (once again) rolling my own stuff.
To summarize the C example: this is as good as it gets in (high-level) C.
To conclude I promised to provide a Pythonic version of our example:
#!/usr/bin/python3
from operator import add,mul
from functools import reduce
onlyEvenFilter = lambda x: x % 2 == 0
dispatchTable = {
'sumAll' : lambda list: reduce(add, list),
'sumEven' : lambda list: reduce(add, filter(onlyEvenFilter, list)),
'multiplyAll' : lambda list: reduce(mul, list)
}
def accumulateList(method, numberList):
return dispatchTable[method](numberList)
numbers = (2,4,5,6)
print(accumulateList('sumAll', numbers))
print(accumulateList('sumEven', numbers))
print(accumulateList('multiplyAll', numbers))
That is more then 80 line of code in C versus 21 in Python - the same functionality, expressed more clearer (in my opinion) in 1/4 of the code ;-)
Freitag, 15. August 2014
Second Status - Studying "Structure And Interpretation Of Computer Programs"
Some month ago I decided to self study the online material of the Spring 2014 course of "Structure And Interpretation Of Computer Programs" of the Berkley University. I was actually planning to regularly post my learning status - however, I forgot to post my half time status. This might be due to a minor football (soccer) event this summer ;-)
Anyway, here is where I am:
I'm slowly creeping forward, working full time doesn't help, too. How can people organize to work on a part time Ph.D. when they have a full time job and a family?!
As the pictures above shows, the next thing is to kick off the last project which is writing a Scheme interpreter in Python. I've done some Scheme recently, I don't hate it - I feel more like in this comic which was on one of the first lecture slides introducing the Scheme topic:
I've never had to deal with something complex like writing an own language interpreter so I'm really looking forward to spend some time with this (last) project.
Looking at my other obligations I suppose it will be October when I'm done with the whole course. We'll see.
Anyway, here is where I am:
I'm slowly creeping forward, working full time doesn't help, too. How can people organize to work on a part time Ph.D. when they have a full time job and a family?!
As the pictures above shows, the next thing is to kick off the last project which is writing a Scheme interpreter in Python. I've done some Scheme recently, I don't hate it - I feel more like in this comic which was on one of the first lecture slides introducing the Scheme topic:
| Source: http://inst.cs.berkeley.edu/~cs61a/sp14/slides/24_1pp.pdf |
Looking at my other obligations I suppose it will be October when I'm done with the whole course. We'll see.
Sonntag, 27. April 2014
Python doctest
Most of my exercises for SCIP come as a stub function where you have to implement the logic. To provide a way to self test your implementation, the stub functions contain also something called doctests.
doctests are a nice way to quickly add tests to your functions. This is what the Python manual says: The doctest module searches for pieces of text that look like interactive Python sessions, and then executes those sessions to verify that they work exactly as shown.
Here is an example of one of my exercises:
from operator import add, sub
def a_plus_abs_b(a, b):
"""Return a+abs(b), but without calling abs.
>>> a_plus_abs_b(2, 3)
5
>>> a_plus_abs_b(2, -3)
5
"""
if b < 0:
op = sub
else:
op = add
return op(a, b)
To run the two tests in the comment against the implementation I'm using the following command:
python3 -m doctest -v file.py
Abonnieren
Posts (Atom)



