What is Programming By Wishful Thinking?

A great way to implement your programs when using Test Driven Development is using a top-down approach. Top-down programming
is a programming style whereby the large concepts of a program are implemented and then broken down into successively smaller pieces.
When implementing the larger design of a program, we implement stubs or mocks that will return what we expect but are not fully implemented
functions. A way of modelling top-down development is as follows:

© i-programmer.info

A method stub or mock is a piece of code that acts as a substitute for our not-yet-implemented code. Implement stubs or mocks
while coding is the act of coding by wishful thinking.

An example

To illustrate the approach of programming by wishful thinking, let's look at an example. Let's look at a simple problem of setting up the colours of a chess board and
displaying them to the console.

In order to setup the colours of a chessboard, the following needs to occur.

  • We must model our chessboard.
  • We must iterate the cells of our chessboard.
  • We must check if the current cell is a white or black colour.
  • We must display the correct color and print it to the console.
An example chess board

To implement the theoretical solution above, let's begin our example solution with stubs.

{% highlight php %}

{% endhighlight %}


The takeaway from our example was not the solution but the way that we coded the solution by first creating mocks and then expanding and implementing
the functionality needed in order to reach our final solution.

The main advantage of coding by wishful thinking is that you abstract away the low-level
implementation of your program and focus on the high-level (i.e. top down) approach first. This methodology allows you to
deal with varying levels of abstraction. This is also a very natural way to code when writing tests (as we will see in another tutorial) as
it allows you to focus on the test by using stubs and demonstrate expected test functionality before you have actually implemented
the functions.

Let me know if you have any questions or feedback in the comments below.

Happy Coding!