TDD – commit by commit String Calculator Kata (II)

Previous post in the series – TDD commit by commit String Calculator (I).

Last part ended with the basic functionality of string calculator. My “class” can parse numbers and sum them up. I have started with an empty project, slowly adding code with features. This post is the 2nd part of the series.

Step VI – Clean up

Before I can start adding new stuff, I need to make a little re-factorization. There are couple of issues in the code.

 

R#, var and other fun

One of the issue, thanks to Pawel Sawicz for pointing this out, is the type of “object” returned by the main function. There is an “object type” instead of “int”. This problem, probably, was caused by R# auto method extraction (that’s one of the reasons why I have disabled R# for a while just to check how it affects my work. Blog post about my observations coming soon). SAdly, This issue wasn’t caught by the unit tests, I am not asserting the expecting “type” just the “value”. This problem is related to the excessive “var” keyword usage. With explicit “int” instead of “var”, there would be an error on compilation. This error is also an assertion, that’s why I think it is beneficial to use explicit types on the expected “object / value”.

Class name + one file

I also noticed that the main class name is “Class1.cs”. Well, what can I say, not a good file-name, when I started implementing features this wasn’t a problem but now when I do know the name of my main class, I don’t see a reason to leave it like this. It’s time to rename the file to match the “class name”. With this change in mind it would be also great to split up the file into multiple files. One big file with code is a big “NO NO”. I don’t want to see the Custom exception or other not-relevant code, especially when I know that it won’t be modified in the foreseeable future. Little note. I am not introducing a new project for tests ‘Yet’.

Test first – first class citizen

Quality of the tests could also be slightly better. Right now each test contains code to create “new StringCalculator()”. It’s not that problematic but it creates an unwanted noise that distorts the readability of code. Unit test has to be clean, readable and easy to follow. I do believe in an idea of treating unit tests as “First Class Citizens”.

“The bottom line of all this is that we should consider our tests as being first. We already know we should write them first; but we should also clean them first, maintain them first, think of them first, and keep them first. We should give our tests the highest priority.
That is what “Test First” really means. The Tests Come First!”

Robert C Martin – http://blog.8thlight.com/uncle-bob/2013/09/23/Test-first.html

This is quite radical, I don’t agree with everything said here, but there is one thought that I do like. Take care of your tests, maintain them, clean and re-factor them. They are the description and the best documentation you have.

After this “brief” introduction time for some code changes.

Commit – test cleanup
I have changed the “expected” value declaration from var to int and automatically compilation error popped up. Now, I can change the “value type” and check if the error is gone and test are passing. Also, I have changed the name of the Test Class, but I am not splitting files yet. I don’t want to create noise and bloat up the commit diff. I introduced the “SetUp” function that is responsible for creating instance of “StringCalcualtor”.

Commit – split file
Finally the split is finished and I am happy ;)

Step VII – Newline character as deli-meter

New requirement, allow the new lines between number (instead of commas). Treat them as deli-meters. Simple example: for input “1\n2,3\n4″, calculator should return “10″.

Commit – Newline character test

Test is pretty straightforward, nothing to explain here. This now throws my custom exception, the input is not correct due to the “\n” characters.

Commit – Newline character test

Implementation is very simple. Do I need to create fancy code with “sparkles”? Not for this requirement. Split function accepts more separators and it’s just “Good Enough”.

Can I refactor the code and tests ? I don’t think so. Code is still quite straightforward.

In this part I just implemented one new feature.

Summary:
- on expected value use explicit “type” instead of “var”, compilation error is your friend
- refactor your code and tests, “Test First” and treat your “Tests as First class citizens”
- create “Good enough” software, don’t overcomplicate solutions.

TDD – commit by commit String Calculator (I)

In this series I want to share my approach to TDD. I will do a simple TDD kata, sharing with you all my decisions and thoughts. It’s called commit by commit beacuse you will find here links to github with each step. There will be a commentary to each one of these. I encourage you to comment and show me the flaws in my “style” of TDD coding. I also want to learn from you. I do know that my approach has its problems and there is allways a way to do something better.

String Calculator Kata

First Kata is quite simple. You can find all the details on the Roy Oshevore’s site. Just to be brief, I am going to implement string calculator that parses values from the string and sums all of them. For example for an input of “1,2,3″ the end result will be “6″. This simple kata is a good problem, to present you the way I do approach the coding with TDD.

If you don’t know the concept of “Coding Kata”, no worries, have fun reading this blog post by Dave Thomas the guy who coined the term.

Step I – Empty Project

Let’s start simple with an empty project containing one test class. Yes test class with a default name Class1. Why Class1 ? Right now, I don’t want to decide on the naming of the class under test. Also just to start, first lines of code are going to be inside the Test Method. I am not creating class or method, just a code inside the Test Method.

Thats one of the approaches, I’ve learned recently. Start as soon as possible with anything and check all the assumptions about the problem you are trying to solve. Don’t waste time over-thinking stuff not related to the problem at hand. I know that as engineers we do have a tendency to be mad about code quality from the start. But let’s forget about it for a while and this time do it differently ;)

Approach like this is ok for not so overcomplicated and self-contained problems. With more complex stuf, I tend to think about design for a while before I write the code. You can read more about classic and london school approach to TDD here.

Here is a link to the commit with my first step. I will post links like this at the end of the steps.

Step II – The most obvious string

First requirement : for input string with numbers separated by ‘,’ return sum of these numbers.

I approached TDD previously with tendency to start with tests for edge cases, null checks, exceptions. It is a very tempting approach. You can allways write something fast and make some easy “red/green/refactor happy” points. No, no, no. Start with a solution to The most basic requirement, that way you can check the requirements and the context of the problem before even touching edge cases.
Simple solution to the first requirement.

The code uses Split method on string to get all the values. Values are then parsed and summed up. Beacuse, at this moment I don’t care about the edge cases, the “Parse” method is used instead of “TryParse”. This is just a start, a first step that will influence next steps. Right now I want to start as simple as possible and prove that solution like this works and I do have a meaningfull result.

Step III – Introduce Class and Method

With a simple solution that fullfills the first simple case. I can now create a class with a method.
Commit

This is a start. With class in place I can think of some simple edge cases.

Step IV – Edge Cases

The time has come for some edge cases. I can define at least two of these now:
- What happens if input is empty or null ?
- What to do when input is not formatted correctly ? How to check it ?

Lets try to do the first one with empty, null, whitespace input scenario. What to do ? I can treat it as a wrong input throwing an exception ? or just return a zero value hiding the problem. Answer to this hard question is hidden inside the context around your problem. I have to ask a question, How is this code going to be used ? Who is going to call it ?. To keep things simple, I will stick with the return 0 option.

Commit

These is the test. Right now it is failing, to make it green I just added simple if clause. Due to simplicity no code in here just commit link.

Step V – Next edge case

What to do when input is not formatted correctly ? How to check it ?

I am using split, in this simple form, the code does expect string in a correct format. I am assuming that if I can’t parse the string with the split function, then the input string is not correctly formated.

Commit

As you can see the test is expecting custom exception. To be honest. I don’t know if the CustomException is needed here, maybe it would be better to just have a FormatException throwed here.
Commit

Things To note

- all of the code is in one file, there is no need to separate anything, at least right now
- my file still has a name of Class1.cs, I don’t want to rename it in this early stage. Of course, I have to make sure that this mess won’t leak into codebase later.

Summary

- don’t create class and methods on the start, write stuff inside the test method
- start simple with code fulfilling the most basic requirmenet, don’t focus on edge cases

Pragmatic Developer

I have changed the Blog name from “Passionate Programmer” to “Pragmatic Developer”. Why this change you could ask ? :)

From Programmer to Developer

Coder / Ninja / Hacker / Programmer / Developer / Engineer even Rock star. Quite a big list of names used to describe someone in our field. Why then it is really important for me feel as a “Developer” instead of a “Programmer” ?

My first job. I am sitting at the desk, bashing the keyboard, creating code someone else thought about. Simple code monkey duty, but I am happy as a Coder. One Year later different company, I can finally influence the code. I get more responsibilities. I finally feel that I am becoming a real programmer. Still a junior one but there is a progress. Another Year, another company. I am leaving technical domain from time to time, making workshops, advising my fellow team-mates. I am starting to feel the importance of soft skills. Negotiation, Communication, Team-Play even kindness. Instead of focusing on the code, I am becoming all around, problem solver. New feature can do this, influence organization can do this, change deployment procedure can do this, chat with client sure can do this, provide on site support yep this too :) . I have developed and my responsibilities changed a lot since I started. Programmer is just not enough to describe the things I do. Developer it is better. I develop products, teams, even myself. Wonder what’s next ;)

From Passionate to Pragmatic

I always thought that Passion is the single most important trait of a successful programmer. Now I think it is crucial but pragmatism took the leading role. I had to try a lot of different technologies and tools to really appreciate this attitude. I have stopped participating in technological ‘flame wars’. I do know that each technology has its pros / cons. My only drive is how much ‘value’ can this provide. I am just interested in how easily I do solve the problems. Also I could tell you a lot of stories about how crazy I was when it came to the code quality. Now I do strongly believe in the ‘Good Enough Software’. There is always a middle-ground to be found and We have to find. That’s why I recently discovered the value of code-review process. 2nd pair of eyes can greatly influence your code, design and can influence your way of thinking.

Pragmatism also changed the way I approach my career. I was ‘Chasing new Technologies’. I wanted to be the cool kid, that’s why I have changed jobs quite a lot. Now I know that when you are looking for place to work the single most important thing is the ‘Culture’. It’s the factor that can make your live happy or quite sad. And there is the thing about politics. I always thought that politics sucks, I am an engineer why do I need to engage in this messy managerial stuff. This perception changed a lot. If you want to influence your organisation, culture, company, you need to gain political power. You can’t be an insignificant peon in our IT world that is driven by the huge EGOs :)

My evolution was quite surprising to me. Wonder how I will think in the next 4 years. I would really like to read your programming path, don’t be shy add a comment ;)

My 100th post …. Welcome to London

It have been a while, but my blog is not dead … yet. Finally, I have found motivation to write my 100th post.

A lot has changed recently and I am spending most of the time stabilizing my life after “breaking” changes ^^. I have planned to move abroad for quite a while and due to various personal reasons I had to wait. But Finally, I have decided to move on. Time to get out of my “comfort zone” and face new challenges.

My new home – London. Never thought that this would happen, I was supposed to be in Germany or Sweden, that was the plan :) But I am glad that I am here, really glad.

Why Sweden ?

I have a very close family in there. I had a brief work experience in this great country, really liked it. Friendly people, good opportunities, IT is very strong. Weather could be problematic, but at least colder climate motivates you to work harder. If there is nothing to do you just go back to productive activities ;) .

I was thinking about sending my CV to tretton37 but it didn’t happen. They do look like a fantastic company with passionate developers. There is also DICE in Stockholm, I love BF series and was considering even to move into gaming industry, but nah web development and agile + business is the way to go for me :)

Why Germany ?

The IT is also strong. Berlin looks like a vibrant city with emerging startup ecosystem. I have noticed a lot of companies in games industry using Unity framework, Cool. Germany is quite cheap when you compare cost of living in the Europe. Houses and apartments prices are very similar to Polish cities like Krakow and Warsaw. It is close to my hometown which is always nice but with flights it is not a problem anymore.

UK / London

So why I am in London ;) Yeah …
Great community, great companies, great city, rent is quite expensive but its not that bad. I have analyzed the Dev community. Lots of meetups, conferences, there is allways something to do almost every day, 6 Amazing!. I think that this is the place to be for a passionate Dev, if he wants to develop your career. I will be working for JustGiving. Great company with work culture that is reflecting my approach and the way I think. Great staff with very bright people. We will see how it goes. So far so good ;) At the moment I am focusing on my productivity, to be ready as soon as possible to get stuff done.

“The Plan”

Thanks to these changes, I have found my motivation and passion. It got missing somewhere, but here I have it again :)

For the next 6 months in technical area I want to focuse on:

F#
The time has come and I am ‘mature’ enough to finally start using F# for some serious stuff. More to come soon.

TDD / DDD / BDD
I have been using TDD, love this approach but still there is a lot to learn. With TDD naturally I thought about BDD and to just go with the flow DDD thinking is something I need to get a serious grasp on.

Open Source
It’s time to get some pull requests accepted :)

English language + social activities in the London Dev community

My Book List for the next months

- Growing Object-Oriented Software Guided by Tests
- Test Driven Development
- Software Architecture for Developers
- The Best of Software Writing

Why Something > null is false – C# and Lifted Operators

In the project, I am working with, there is a simple feature that imports data from external source. Import is only interested in new records. This condition is fulfilled with ‘DateTime’ comparision.

Looks simple, Unfortunately I have encountered a nice ‘bug’ :) . On the first run, import got 0 records and I was sure that this number should be around couple of thousands. It seemed like the if clause returned false. In this scenario, on the first run, LastUpdateDate value is undefined.

The comparision looks like.

Weird, especially when you know that ‘DateTime’ is a struct and can’t be null. It’s default value is ’0001-01-01 00:00:00′. This comparision should evaluate to true right ? Sadly there is one catch. LastUpdateDate is a ‘DateTime?’ type. I assumed that both operands are of ‘DateTime’ type. Nullable DateTime is whole different story.

The comparision changes to

Default value of DateTime? is null, It is then.

Let’s see what the result of this comparision.

Simple class, with only one property a ‘DateTime’ struct. Result is ‘True’, because DateTime.Now > default(DateTime).

Now let’s check what happens if there is a DateTime? property.

Default Date value is null and the result is ‘False’.

What is happening when we want to compare Non-nullable type with Nullable type ?

There is a special kind of behaviour for this case. In C# specification 14.2.7 Lifted Operators

Lifted operators permit predefined and user-defined operators that operate on non-nullable value types to also be used with nullable forms of those types.

Check out this excellent description of lifted operators by Jon Skeet.

Why something > null is false

It seems like this is a design choice. In the specification you can find this:

The lifted operator produces the value false if one or both operands are null.

From Dwarf Fortress to Vim – evolution of .Net programmer

In this post, I want to write about my conversion to Vim, a complex but powerful text editor. It’s learning curve is quite step but once grasped, it can increase your productivity.

You can use it almost everywhere, Linux, Windows, Mac, you name it. It is an OSS software, easily moddable and open. You can write your own plugins and change almost every aspect of it. This process is very natural and easier than Visual Studio’s extensions and configuration hell.

You won’t replace Visual Studio with VIM, that’s not the case, you can however enhance your productivity with it. Instead of using new editor you can use Vim inside Visual Studio. Think of it as a new tool in your programming tool belt.

“My First Time”

My first “fun time” with Vim was in “git commit” command. This was an awful experience. Vim felt too weird for me. It was confusing and I had to spend a significant amount of time to commit something.

Steps are like:

  • enter insert mode
  • write some text
  • go to command mode
  • send command :w to save the file
  • send command :q to finish the process

A lot of stuff to remember for such a simple task. Back then “git gui” and “commit -m” saved my day. I wasn’t ready for such a shift. I was too attached to tools like Tortoise Svn, Visual Studio and Notepad++. I thought about Vim as another weird editor for all those uber geeks. It doesn’t felt powerful, my user experience was bad.

I wasn’t ready then, but now I am writing this blog post in VIM.

So What happened ?

Two things changed the game, “Git” and “Dwarf Fortress” (this hardcore game for weirdos). Learning Git and it’s command line interface was like a revelation. I felt more productive and done stuff faster without the mouse. I really think about this as a evolution of the programmer. Suddenly you just realize that there is this weird world that looks so different but also feels right. Git was just the begining of the end of my usual mouse and point/click approach.

Then, I discovered “Dwarf Fortress”, weird but awesome and complex strategy game. I hated it’s interface and UI. It is a perfect example of unfriendly design. Unfortunately, I am a maniac of all the complex strategy games (War In the Pacific is a perfect example of such a game). In order to play “Dwarf Fortress”, I had to force myself into learning it’s interface. This was a painful process, but with time I started to get it and was able to play the game normally. Poorly designed UI stopped being the problem.

This got me thinking. If I can learn to play “Dwarf Fortress” then maybe, I am able to grasp this weird editor “Vim”. Prior to this revelation, I approached Vim 4 times, all of them with moserable outcome. After “Dwarf Fortress” experience, I finnaly got it. I don’t know why but after the 5th launch and try, I finaly started to se the benefits of Vim and “hjkl” approach.

Vim Everywhere

Now, I am using Vim almost everywhere. Fortunately I didn’t have to ditch Visual Studio, there is a nice extension VsVim that runs on top of VS editor. It works well, it is somehow limited, but has the most important features like “imap” command. It is a great extension that gives you more possibilities.

There is even a nice extension to Chrome Vimium. I am still researching it’s possibilities, but it is nice to navigate website with “hjkl” keys. I like the keyboard only navigation that comes with this extension. You really should try it.

Sublime also supports “vintage mode” but it is very limited. The only thing that encouraged me to work with Sublime was “command + p” feature. Fortunately there are plugins that enabled simillar functionality in Vim. So I switched my Node.js development to it.

Summary

Don’t give up on Vim, even when you think it’s not for you. Someday, sometime there will come a moment that you will get “Vim addiction”.

Several Links to help me encourage you to Vim.

Everyone Who Tried to Convince Me to use Vim was Wrong

Why, oh WHY, do those #?@! nutheads use vi?

5 essential Vim plugins

Node.js – simple web server with ‘express’

I have been playing with Node.js recently. Mostly doing some small hobby projects. One of them needed server side badly, some of the cool features were not possible with the client side only web app.

I was thinking about using RoR, Asp.Net Mvc or NancyFX all of these frameworks suitable for the task. Then why Node ? Well, the answer is simple, FUN. There is a lot of hype around it. Community is very dynamic, lots of modules and extensions created on the daily basis. As a Passionate Developer, I also wanted to try something new. I can do .Net stuff at work and it is allways good to try something new and fresh.

Basic Node.js server

Let’s start with a very basic example, just to see the bare Node without the modules.

Node is basically a javascript, but this time on the server side ( weeee best language in the world on the server side, how can you not love it ? ). This code is a implementation of a very simple server responding to each get request, with some funky message and code 200. The require statement is the implementation of a internal module system.

Node.js with express module

This was a really simple example. Sure you can write whole app like this, but there are modules that provide a nice layer of abstraction with all the the nasty details hidden. I have been using the express module. It is a nice web application framework.

It provides

  • better wrappers to the request and response
  • support for view-engines
  • routing mechanism
  • cookies manipulation
  • basic authentication
  • more …

The express module is loaded into app object. It is then used to define the routings, accepting POST and GET verb. The syntax is quite simple. You provide the regexp which matches the route and a function that is executed when the request is matched. Function gives the access to the request and response wrappers.

Some Notes:

  • (/^(.+)$/ regexp is not the best one, it matches almost everything and has to be defined as the last route. Still it works ok and all the js, css files are being sent.
  • __dirname is a global value containing the name of the main directory with the node script.

CouchDB – First Steps

Long long time ago in one of the posts … I briefly described CouchDB installation process on the local machine.

IrisCouch

If you don’t want to configure local database you can use IrisCouch hosting.
You can get free database for basic tests. I am using this database hosting for one of the projects hosted in heroku. It is free for really basic usage.

Now we can play with our new toy. Let’s start with some general concepts.

Where are my tables ?

Quick answer there are no tables. Data is stored in a form of documents, which are JSON objects. Each document have properties. Properties are like columns. You can story values, array of objects, custom objects in them.

Here is a simple example. This document has properties : isActive, isApproved, type, url.

_id is a special value that has to be unique for each document. You can assign it by yourself, but it is also generated automaticly when you add document. Automatic value is a representation of UUID.

_rev is a special identification number which is used for the document versioning. Each time you save changes to the document _rev value is regenerated.

How to query this freaking thing ?

With this little introduction it is time create first query. I was using mostly relational databases that used SQL language to write queries. In CouchDB it is not simple like that. There is no SQL language and you don’t write queries. Instead you create map/reduce functions that are stored in CouchDB in form of custom views.

Map function is used to filter out the data. We can think of it as QUERY with WHERE clause and SELECT statement.

Reduce function is used to transform data to a new object. You can perform operations like SUM or COUNT here. I will write about this particular function in some later posts. Let’s focus now on querying the data.

Map function

In CouchDB map function === javascript function. It takes document as a parameter and returns nothing. Instead of return you have to use emit function. Map function iterates through all the documents and tries to match the document based on the if clause. If the document is matched we call the emit function.

emit() function takes two arguments ( key, value). This function can be called mutliple times in one map function and is used to create the view result with rows each containing key and value. View result then is converted to JSON object that contains rows and metadata.

Accesing data from the browser

The nice thing about CouchDb is that we can access data by using the HTTP protocol. Simple GET message is all we need to access data.

For example: GET to – http://localhost:5984/database.name/id

Returns the document with the id. You can make GET query to views, documents, database. It is quite usefull when you want to access data from javascript without the hassle of installing all the different frameworks.

In one of the apps on node.js, I am using nano module to access the database. This module is just a wrapper to the HTTP protocol.

Summary

That’s it for now. CouchDB is a nice database engine slightly different than Redis engine that I used recently. My experience with NoSql is still little low. But it is a fun thing to learn. I believe in a multiple databases used in the project with specialised database engines used for different things. You can read about this on Martin Fowler blog..

Stay tuned for more CoudhDB adventures.

CouchDb – getting started on Windows

This post will be a little note with steps needed to setup a working CouchDb instance on windows machine.

NoSql

RDBSM rules the world, it is still a “standard” in the industry. My first Database was used inside a simple rss client written in C. This was the weird world of C programming with weak documentation and Segmentation fault errors everywhere. Now, I am mostly using MSSQL with ORM support ( NHibernate ), but there is another world of databases on the horizon, NoSql movement.

There have been a lot of buzz about NoSql for quite some time, but I had no time to learn and use it for some real thing. Sure, There was a small project with Redis and RavenDb, but this was just fun and little playground. I created simple fun projects just to start somewhere, but now the time has come to make the move and start the journey to the NoSql world.

I am going to start with CouchDb. A nice database engine that stores data in JSON format and is accesible through REST based HTTP interface. If you want more info on NoSql check this site. You can find a lot more detailed explanation here with answers to some important questions like “Why I should consider NoSql ?” or “When is it a better choice ?”. Also Wikipedia is allways helpfull.

If you want to check how many different implementations of NoSql philosophy are out there, check this site : Big list of NoSql databases.

Installation

Where to download it ?

Ok so let’s start with the most simple step : The download.
You can find all the needed files ( actually there is only one file ) CouchDB here. Installation process is straigthforward ( just click Next ). There is one step that asks you if you want to run the database as a windows service, feel free to do this, I selected ‘No’, I want to control when and how it is running.

How to run it ?

Go to start menu and look for “Start CouchDB.bat” or go to “-InstallDir-\CouchDB\bin\couchdb.bat”. This is the main bat file that performs all the necessary steps to run database. CouchDB is written in the Erlang so the bat is starting the Erlang emulator. Don’t worry if you don’t have this ‘emulator’, it seems that it is installed automaticlly.

Watch the startup process. My first try, ended with “Abnormal termination” error, but if everything went fine you should be able to access the configuration site. http://127.0.0.1:5984/_utils/

Errors, Help !!

If there was an error in the Erlang Emulator Console. Check the error messages page.

I had an error “Failure to start Mochiweb: eaddrinuse”. This one is quite simple to fix and was caused by port being closed due to some application already using it.

To change the port :

  • Open “-Instal Dir-”\CouchDB\etc\couchdb\local.ini
  • Look for [httpd] bookmar
  • Uncomment the port section and change it to some free / open port. (8001)

Side Note: By default port is set to ’5984′. If you have installed CouchDB as a Windows Service you won’t be able to start a new instance beacuse the port is already taken. In this case you don’t have to run CouchDB manually.

IE 7,8 kendo ui binding problem – unknown runtime error

TL;DR; If you are getting unknown runtime error in the kendo javascript code. Check if you are using correct binding methods as per the demo on telerik site.

You’ve got to love IE with all the “special behaviors” in it. I have spent recently 10h trying to fix little problem found only in IE. My project have to support version 7, 8 ( you know – “enterprise IT” ). New version number 10 seems to be working really ok, no problems with it ( apart from that it looks almost like chrome ). Thanks to Microsoft and their abandoment effort, I don’t have to worry about revolutionary IE 6.

Problem:

Project uses kendo ui framework to create elements on the View. There is a support for MVVM pattern with multiple different bindings, just like knockout.js with similar syntax and behavior. One of the bindings is supposed to be changing text value. This binding is normally used with textboxes but we have used it with “label” and “anchor”. It worked fine on Chrome, Firefox, IE 10 but then the fun began. Tests on other IE’s version caused “runtime error”. Indeed very informative message, thanks IE just like “unknown error” on Sharepoint.

This “runtime error” was raied on this line of code.

After some research, I discovered that earlier versions of microsoft’s browser are very restrictive about certain changes performed on DOM elements. In this scenario you can’t change ‘innerText’.

I tried to create a workaround which removed and added new element, but this instead caused other problem. It seems that here IE is also very restrictive here.

Solution:

Fortunately solution is quite simple, instead of ‘text’ binding use ‘value’ binding. This one uses code that works fine in IE.

Hard truths about software developer career

I am a software developer. From my experience I can say, that this is one of the best jobs someone can do. It is creative, demanding and extremely rewarding plus it has an awesome community with friendly and intelligent people. When i was entering the work market in my first company i had various assumptins ans misconceptions that i learned in university. Boy i was soo wrong about a lot of things. In this post i want to dosciss some of them.

You are passionate, hard working and very engaded, sorry that’s not enough

First of all let me say this. Passion, hard working attitude and engagement this are awesome personality traits, thanks to them you can be really a great addition to a software team. Unfortunately you can’t make a difference based solely only on these traits. You need to link them with other important skills like teamwork and communication.

If you want to make a difference and be a crucial part of the team, then simple creation of endless lines of code won’t do it. First you need to sell your brilliant ideas to the team and decision makers. Even if you have some awesome ideas you need to convince others that they are awesome. You need to advertise your perception and passion.

In workplace its not like that that everyone wants to work as best as possible. People have their own attitudes and approaches, someone only cares about politics and his carrer advancement other wants to develop himself. You need to know how to convince different parties. If you want to survive you will have to learn complex political environment in your organization. Don’t become an idealistic person who thinks that hard working attitude will solve everything.

It’s not rocket science … a lot of the time

At university i was doing a lot of awesome stuff. Cool algorithms, fun games, low level programming. In most of the jobs you won’t find such a “cool” stuff. Sure, there are startups with nice ideas but a there is a big possibility that you will end up maintaining and developing CRUD applications. It might look like this applications are only sending and transforming data from one place to another, but you will get used to this. There are boring tasks but from time to time you will stumble upon a real gem. Job becomes more interesting as you mature up and take more senior responsibilities.

Remember that if you are ambitious and you want to learn you have to fight for this, you have to convince your boss that giving you something new to do, will not only benefit you, but also your company in the long run. Look for companies that understand this and wants to develop their workforce. Avoid places that only want to exploit you. It is best to work under a passionate team leader who thinks about hist team and people. Who understands that people won’t leave a company when they are happy.

But I am a engineer I don’t want to communicate…

I think that the hardest part of the job is the client and teamwork. Human interactions are not soo simple like 0, 1 deterministic logic. I know that it sucks, we are considered to be mostly introverts that like to sit alone. There is even this old stereotype with programmer sitting in the basement. This perception has changed, we are considered now almost like rock-stars. Today apart from the technical skills you need to be an awesome communicator, negotiator and team player. In a normal workplace you will work in a team, solo ? no way.

Unfortunately working together generates a lot of friction and problems. People have different needs, characters and approaches to the work. It can be really hard. Good team player know how to use those differences for the good of the team, he knows how to approach other people, how to talk to them, how to criticize, how to praise. You can consider these skills as purely managerial stuff. You can even say that you dont need them, but please trust me. You won’t go far without them. These skills are needed to advance your carrer and to create a successful track of projects, which is the best measurement of your abilities.

Whenever you feel like you know a lot … you are wrong

Technology is changing too fast. Software developer needs to sacrifice a lot of time to refresh and gain new knowledge. This can be quite difficult. I am always surprised when I learn something only to discover that there is a new world of possibilities waiting for me to explore. Every time I think I know a lot there is always something new waiting for me just as reminder of how little I know. If you like to learn, you won’t be disappointed in this line of job.

One of the realisation a young developer have to make is to accept the idea that you cant know everything. We have to prioritize a lot and make a strategies about our time investment. It is just like diversify investment of your money. You can learn easy stuff that can get you a little but certain return, but we also have to take a risk and learn something new and trendy. This thing can be dead next year but if you want to stay on top and hopefully become an expert in the future, then you have to do this.

Visual Studio – Extensions and Configuration

In this post, I want to share some details about my Visual Studio 2012 configuration. You can find here a list of plugins, some options and various customization that I am using.

Some thoughts

I am not using any GIT integration tool. I don’t need it. Console and bash is all, I need.
I am mostly using 2 split window setup. All the tool windows are pinned out if i need them i can use CTRL+TAB.
I am trying to not use mouse at all.

Extensions

R#

Tool that you can’t live without. Finally i got my personal license thanks to the promotion at the end of the world :) . I am mostly using R# to navigation. Ctrl+Shit+T and Alt+Shift+T are the most used shortcut combinations, Unit Test runner is also pretty cool. I am using it with XUnit plugin.

There is one problem with R#. It is very addictive. We have to be carefull to not become too attached to one IDE and one set of tools. I am trying to “fight” some small RoR projects. It is really cool when you are learning new tools ecosystem.

StyleCop

A set of rules, conventions that that are good practices when creating code. Nicely integrated with Resharper. You really get a lot of feedback and there is even nice explanation of every rule.

ForTea – a T4 templating plugin for ReSharper

If you are using T4 extensively, then you need this plugin. It provides a lot of features available in R# within T4 files.

AttachTo

Simplifies the process of attaching debugging to the process. Very Usefull.

Hide Main Menu

I hate all the menus, windows and unnecesary stuff, thats why I have the main menu hidden. When i want to use it, I just press alt and navigate with keyboard.

Highlight all occurences of selected word

Visual Studio Options

As you can see on the screen it is a preety usefull extension.

Indent Guides

Previous picture also contains presentation of the Indent Guides. This extension creates really subtle visual “help” that simplifies tracking of the start and end of braces and “scopes” in the code.

Productivity Power Tools

This is a big bundle of different extensions. It is too big, I am only using Enchanced ScrollBar option and Power Commands.
Power Commands are adding nice action – “Open containg folder” It lets you easily navigate to the file on your system.
Scroll Bar shows some useful markers that also help with navigation through bigger files.

Color Style:

For the colors I am using
Step Son Of Obsidian

I like the black theme.

Options

1. Lines turned on Text Editor -> All Languages
2. On startup show empty enviroment (performance boost) Enviroment -> Startup
3. Source Control Set to None ( I dont need TFS ) Source Control -> Plug-in Selection
4. Package Manager my custom nuget package feed -> http://www.nuget.mfranc.com/nuget/
5. Text Templating -> Show Security set to False i dont need this

Key Bindings and Remap

For key Remapping in the system, I am a big fan of KeyTweak

1. CTRL+ALT+J move window to previous split windows
2. CTRL+ALT+K move window to next split windows
3. CAPSLock -> Backspace
Quite powerfull rebind, but you need to get used to it.
4. Right Ctrl -> Right Mouse Click
I need this mapping to use VS without the mouse.

OAPT – “One Assert Per Test”

In previous posts we discussed the problem with multiple asserts in the unit test. One of the reasons to create test with only single assert was “Unit Test Misinformation”.

One of the readers of my blog remainded me in the comments that there are frameworks that can help in a situation like this. One example of such a framework is One Assert Per Test – OAPT

What does it do.

Oapt saves you this trouble by running your unit tests several times, each time using one assert and ignoring the rest.

Quite cool idea, that can save a lot of trouble.

Still I think that unit test should only contain one assert whenever possible. When it’s not, frameworks like this are quite helpfull :)

Extending git with custom command

I am really happy that I can use git for my every day job. Earlier I was only using it in hobby projects. Now I can learn and experience git in real projects, with real people and problems. So far, I love it :)

There is one nice ‘feature’ of git that i found recently : creating git custom commands. It is useful, when I want to automate some repetetive tasks.

Repetitive Task

Whenever I want to commit changes to the branch, I have to execute add command and then perform a commit. ‘Projectname’ is one of the conventions in my company. Each commit needs this variable beacuse we are using it in internal mail service.

One of my practices with source control systems, is to commit a lot, so doing this ‘repetition’ all the time is a waste of time.

Git Custom Command – git c

Custom command specification :

  • execute git add
  • execute git commit
  • commit message with project name

All this is simple except the project name variable. Fortunately our projects folders are named after the project. In the Script, I just have to get its name.

Script

Installation process

  1. go to libexec/git-core folder (@Windows ‘C:\Program Files (x86)\Git\libexec\git-core’)
  2. create new file in this folder called ‘git-c’ (no extension)
  3. copy paste the script code

Usage

Good unit test – One Assert

In previous post, I defined a good unit test as one that:

  • tests single unit of work
  • contains only one assert
  • is self contained

Presented sample of code with one unit test, unfortunately had two asserts. Clear violation of the second rule. One of the fellow bloggers MJ pointed out this mistake. It is time to “fix” it and talk about “Only one assert per test” rule.

Why only One Assert

There are couple of problems with multiple asserts.

Unit Test Misinformation

Frameworks like NUnit do notify about failing unit test when one of the asserts is not met. You get the message that some condition failed, but only this one condition. Code, behind the failing assert, is not executed. In a scenario with multiple asserts, when the first one fails, test procedure is lost and potential problem looks like related to the first assertion check. This is a misinformation.

Presented example tests GenerateDocumentNumber function. This function creates simple string based on provided ID.

We want to check if :

  • document number contains ‘id’ value
  • document number contains keyword ‘new’

If procedure fails on newString assertion we know that one part of the algorithm doesnt work. The problem is that check for ID wasn’t done at all. We don’t know if ID is set correctly. Test like this, with multiple asserts, can’t be trusted.

Complicated Tests

There is another problem with the presented unit test sample. It is too complicated. Unit test has to be focused only on one part of the algorithm. First assertion, checks if there is a ‘new’ keyword. Second, looks for ‘ID’. Both of these scenarios are great candidates for separate test.

Also, part of the code responsible for the ‘ID’, is probably more general and doesnt apply only to ‘new’ documents scenario. It is misleading, based solely on the unit test code and the name, we can assume that ‘ID’ is only added to new documents code.

We can split this test in two:

  • GenerateDocumentNumber_when_new_document_then_contains_string_new
  • GenerateDocumentNumber_contains_id_of_the_document

With one assert per unit test mindset there is better chance of creating good unit test, concentrated on one particular problem.

Going back to previous post example.

There are three behaviours that we have to test.

  • output ‘*’ char for each char in provided password
  • return password
  • ConsoleKey.Enter breaks the procedure

‘Output char’ and ‘return password’ logic should be tested separaterly. The Enter key functionality is unfortunately more complicated beacuse it is mandatory in each test scenario. However still we can test some edge scenarios like “What happens when there is no Enter key ?”

One test per concept

There are of course exceptions and unit tests that could use multiple asserts.

Quote by Roy Osherove from Yeah it’s a blog

My guideline is usually that you test one logical CONCEPT per test. you can have multiple asserts on the same *object*. they will usually be the same concept being tested.

This rule allows multiple asserts but they have to be related and linked with simillar CONCEPT. For instance, this is not bad if multiple asserts are testing something like this.

We have three asserts but they are basically testing the same thing. If one of them fails then the rest can’t be ulfilled. Fail on the first one automaticlly means that whole test failed and something bad happened. Nothing is hidden.

Good Unit Test – Summary

  • try to use one assert per test
  • if there is a need for multiple asserts, remember one test per concept rule

Links

Roy Osherove Site

Post with solution to “hide” asserts

Unit Test code with static method Console.Write

tl;dr : Wrap theses methods inside the layer of abstraction. Then create a stub and use it to create test scenarios.

This post is based on my answer on the Stack Overflow – “How to unit test this function?”

The original question is about writing unit test for a code that uses Console methods inside its body. This problem is more general and in this post, I want to show one of the ways to unit test code with static method.

Example of code with static methods

This example is from the Stack Overflow question.

Little Explanation

Method GetMaskedInput() does two things.

  • Whenever your press a key it shows you a ‘*’ char
  • All the keys are also appended to the string and returned

It’s a simple implementation of the hidden input. Something like a password text box on login screens.

Whats wrong with static method ?

This sample method is highly dependant on the Console.ReadKey and Console.Write methods. Code like this is only usable when we have access to console. Running it in for instance web.app enviroment would be problematic. This is one of the reasons that static methods are evil. Not like famous “goto”, beacuse there are scenarios in which statics are ok.

  • extension methods
  • simple helpers with input, output contained in the scope of the function (no globals, external dependancies )

Use of static methods seems like an easier solution, but in the long run, code written like this becomes problematic. It’s simple, clear and easy, but when you want to write unit test there is a problem. You are not able to write correct unit test for it.

What’s the correct unit test ?

  • it has to test unit of work
  • contains only one assert
  • most important it is self contained

With static methods like Console.ReadKey and Console.Write you can’t do it. These methods are dependant on the Windows Console implementation. We can’t control this behaviour, we don’t know exactly how it works inside. What we can do is to get rid of them.

Getting rid of static method

In this approach, I will show you how to hide “static” methods behind a layer of abstraction. Instead of using Console methods directly, let us inject some class that uses Console.

New Method

Interface definition

The sample method now have one parameter. This parameter is an interface IConsoleWrapper that has two methods. Their name is similar to the methods provided by the console Class. New code now calls the IConsoleWrapper interface. It doesn’t need to know implementation details.

Interface implementation

The implementation of Console is now hidden. It was done by wrapping the static methods inside a class that can now be injected to the GetMaskedInput method.

We are able now to write unit test for the code.

Unit Test Example with Stub

In order to test this code, we can create a stub that implements the IConsoleWrapper interface. This stub will just simulate Console. We can control it’s behaviour and thus create a stable test scenarios.

Test Stub

This stub simulates Write method by maintaing the Output variable. It’s a string and calling Write now appends this Output. We can now check the Output easily in the unit test.

ReadKey method is simulated by returning predefined data provided through a stub constructor. This behaviour is similar to replaying a recorded message. For each test a new stub is created with predefined key collection. Each call to ReadKey returns next key from the collection.

Test

This test will simulate a scenario with user clicking A,B,Enter keys. Enter should finish the procedure. We are expecting to see two “*” chars in the output and “AB” should be returned. Test has two asserts so it’s not a perfect example, but this particular logic required us to do this.

Summary

  • static methods are evil get rid of them if you want to write unit test
  • do this by hiding them behind a layer of abstraction
  • write unit tests by mocking this layer or create a stub that simulates behaviour needed for the test

Site with project – NancyFX fun

Projects, source code, different concepts. Those are the byproducts of our work . Every programmer in his carrer develops a lot of different stuff.

I allways planned to host mine “toys” somewhere. Sure there there is github, assembla and other hosting possibilities, but to be honest I need more customization options, and the feeling that I can do something on my own is tempting. There is also NanyFx framework that I read good things about, I just had to try it out and created simple site www.projects.mfranc.com.

This will be my playgroud for Knockout.js, Nancy framework, SignalIR, Twitter Bootstrap and other cool stuff. Nancy is quite awesome and it is a something new for me. I like the “less code” feeling. Compared to Asp.Net Mvc there is quite a huge gain in number of lines.

I tried out Nancy, which is based on Sinatra framework from RoR community. My first impressionit is good. I like the whole idea of writing less code. Also I think that “modules” are more readable and maintanable beacuse you are forced to simplify your “controller” layer. This leads to really good code. The only problem I had was the lack of knowledge/documentation available on the Web. While developing I enountered some problems that took me a while to fix. This won’t be a problem with more mature product, bigger community and adoption rate.

New Design

Hurray we have survived the armageddon. To celebrate this marvelous achievement, I redesigned my blog.

Well seriously my site needed new layout, fonts and colors.  Previous version was just unreadable,  I barely was able to focus on anything. My blog is mostly about content, so I wanted to shift focus onto this content. Previous version caused a lot of problems, with all the different colors, weird fonts and odd headings. There is still a lot to learn for me in the typography, editing and writing, but this new design is a first step in good direction.

I am planning to write more and more and more. My english is improving (slowly) and writing right now is not so a big problem, as it was like 2 years ago. I had a lot of problems with words, grammar etc. but It gets better. Those dread full deadlocks, caused by lack of the words, are becoming almost extinct. When i was starting with all this non-native writing, it was just a way to for myself to learn language. More writing means more mistakes, more mistakes equals bigger knowledge and experience.

<>I am thinking about taking some writing lessons, but not the ones related with books,novels. I want to improve my editing skills a bit. What do you think about it ?

Goals for year 2013

It is almost the end of the year. Hopefully we will get through Armageddon on 21st December, so following Pawel Klimczyk idea, I am posting my own list of personal goals for 2013 year.

Prepare a session for wroc .net

I was planning to do this for a long time. There are couple of ideas that, I could talk about. This year, I have done some presentations for students. This was fun, I always enjoy it.

Read more books / watch more screencasts / write more blog posts

I have a big list of stuff. There is still Oredev, NDC waiting, and a big pile of books. Also i have to try and write more often. One post per month is unacceptable. I increased my activity on Twitter so the time has come for blog. I have a lot ideas but motivation is not one of my best friends, also decision that I am going to write everything in English makes a lot of things difficult. I still have a lot to learn on writing not in my native language.

RoR project

There was a time when i only focused on .Net stack, but then I started to use GIT and I fell in love with BASH and keyboard only habit. This led me to Ruby on Rails. I am currently learning it and doing some little fun project for myself.

Get Involved with some open source projects

I have some little projects hosted on Github but still, I haven’t tasted any pull request for some open source project. This has to change. I will try and focus on some of the frameworks, I am using in my every day job and hobby projects.

It is not so much but, I have to focus on the most important goals.

Log levels – my approach

There are some options available when it comes to logging mechanisms on .Net platform. Fortunately we have standarized log levels.

Currently i am using mostly NLog,this library is very popular and at the moment has all the options i need. There is also Log4Net lib, bit out dated but still good, we are using it at my company mostly because it is used in open source projects integrated into our product. In this post i don’t want to go into details, I just want to talk about logging levels.

Log levels

Trace

Used to log all the details of the function. Parameters, all the actions etc. I am just using it in a more complex debugging process. There is really no need to mess the log files with too much of information.

Debug

Turned off by default.

When i am done with debugging, I am converting some of the Trace messages. Just in case I need them and part of the “fixed” code is still not stable enough. Also with some complex algorithms, I am often leaving some Debug log level messages that contain data about transformations and steps performed by the code. This is often very useful, but I am just turning this level when I need additional data.

Info

Only some “big” notifications like new module activated, services started / stopped, or information that user performed some significant action like: logged out. This log should be mainly used to track the big picture and the flow of application. For more detailed information, I am using other type of messages.

Warning

First of all, Expected exceptions and some weird behavior that should be noted and there is still possibility to run application. For instance there is a timed job that performs some action that is not affecting overall

Error

Mostly Unhandled exceptions. Errors that are not recoverable and you can’t run the app or perform user action again.

Fatal

This should be logged when some error causes destabilization of whole app and we know that this will affect all the users.

It can be for instance:

     – problem with connecting to the database.

     - some important config variable missing that can’t be replaced by default value.

Those are serious errors that should be noted as soon as possible. In one of the project i was sending this kind of errors to my mail so, I can fix them as soon as possible.

Important tips:

- Logging everything is not the way to go. In order to create log you need to write code. Code is our enemy. More code means more maintenance and more bugs. That’s why, I am always defining my logging “strategy” eg. what i need to log, when and why. Most of the time Exception logging is all you need. That’s why you have to treat log levels strategy seriously.

- Debugger is your friend but in some of the projects you don’t have access to production server and you won’t be able to reproduce some failure scenarios. In this situation your only source of information is the logfile

- Even if log file is only a text and you can open it in simple Notepad, I encourage you to use specialized tools like Log2Console.