Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

     

Quick Tip: Programming by Wishful Thinking

You can also read this post onmy own blog.

You've probably heard the advice to break your work up into manageable chunks, or to break a complex problem down into simpler parts. This is a handy technique to use while programming as well

You write a function to solve a particular problem, and you write it as if any complex functionality you wish for, has already been written. Afterwards,, you go fill in these functions, and apply the same technique.

An Example

Let's say you're writing a Tic-Tac-Toe game, and you need to write a function calledgetWinner. It takes the board as a 2D array. Each cell in the array contains the string "X", "O" or "." ("." is an empty cell). It returns "X" or "O" if the respective player has a row of 3, andnull otherwise. Here's what the process for checking that looks like

  • Check the horizontal rows. If there's no winner, ...
  • Check the vertical rows. If there's no winner, ...
  • Return whether there's a winner on the diagonals.

So here's how you'd write that function in #"http://www.w3.org/2000/svg" width="20px" height="20px" viewbox="0 0 24 24">Enter fullscreen modeExit fullscreen mode

We just wish thatgetHorizontalWinner and its friends existed, so our problem would be as simple as this. However, wishing upon a star doesn't get you very far, so we still have to implement each of these functions, but at least they're smaller problems to solve.

Let's dig in and writegetHorizontalWinner first

functiongetHorizontalWinner(board){for(vari=0;i<3;i++){varwinner=getLineWinner(board[i])if(winner!==null){returnwinner;}}returnnull;}
Enter fullscreen modeExit fullscreen mode

Again, we just write our code as if we already havegetLineWinner, which takes an array of 3 board cells, and returns the player who made a winning line there, if any, otherwise null.

getVerticalWinner will look very similar:

functiongetVerticalWinner(board){for(vari=0;i<3;i++){varwinner=getLineWinner([board[0][i],board[1][i],board[2][i]])if(winner!==null){returnwinner;}}returnnull;}
Enter fullscreen modeExit fullscreen mode

You could, if you want, add agetColumn function that abstracts away getting an array for a given column of the board, but in this case, I don't think it's necessary.

Now forgetDiagonalWinner:

functiongetDiagonalWinner(board){returngetLineWinner([board[0][0],board[1][1],board[2,2]])||getLineWinner([board[0][2],board[1][1],board[2,0]]);}
Enter fullscreen modeExit fullscreen mode

Pretty simple, right? Now the only thing we have left to write isgetLineWinner:

functiongetLineWinner(line){if(line[0]!=="."&&line[0]===line[1]&&line[1]===line[2]){returnline[0]}returnnull}
Enter fullscreen modeExit fullscreen mode

And we're done! You could replace the check forline[0] !== "." with a function likeisEmpty, which would then do the check. This function would be pretty handy when implementing the rest of the game as well, for example to check whether it is valid for a player to put a symbol in a specific cell. But for this example, I'm leaving it as-is.

The most important thing to note here, is that you abstract away details by calling functions you wish existed. This way, you're naturally splitting your code into reasonably-sized functions, dealing with different levels of abstraction.

I hope this has been helpful to you.

Top comments(5)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
aigarius profile image
Aigars Mahinovs
  • Work
    Systems Integration Test Automation Engineer at BMW CarIT Gmbh
  • Joined

This combines very well with Test Driven Development and Mocks. At every step, before writing out a function, write 1-2 simple tests that call that function with a sample input and check its sample output. Once you have written the function plug the wished for functions with mocks that return expected results for the inputs. And presto - you already have test data for your next level of functions! When all is done, add a couple more calls to the top level function without any mocks and see how they all work in concert. Done!

CollapseExpand
 
dmerejkowsky profile image
Dimitri Merejkowsky
Software writer. Blogger. Teacher.
  • Location
    Paris, France
  • Joined

If you're willing to go through arather long article I've written you can get an other example of using the pattern.

TL;DR: I was integrating some C++ code in an Android app, but to get started I justpretended the library code existed while starting working on the GUI.

Worked pretty well ;-)

CollapseExpand
 
_bigblind profile image
Frederik 👨‍💻➡️🌐 Creemers
I'm never sure what to put in a bio. If there's anything you want to know, don't be afraid to ask!
  • Email
  • Location
    Maastricht, the Netherlands
  • Education
    Knowledge Engineering & Data Science at Maastricht University
  • Pronouns
    he/him
  • Work
    Developer at TalkJS
  • Joined

I'm not sure how much of a quick tip this is actually. I wanted my series of quick tip posts to be short and snappy posts, but this one grew slightly longer than expected.

CollapseExpand
 
jwmevans_77 profile image
James Evans
  • Joined

How does that differ from the top down development model?

CollapseExpand
 
_bigblind profile image
Frederik 👨‍💻➡️🌐 Creemers
I'm never sure what to put in a bio. If there's anything you want to know, don't be afraid to ask!
  • Email
  • Location
    Maastricht, the Netherlands
  • Education
    Knowledge Engineering & Data Science at Maastricht University
  • Pronouns
    he/him
  • Work
    Developer at TalkJS
  • Joined

In practice, I don't really think it does. It's just my way of thinking about solving problems.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Frederik 👨‍💻➡️🌐 Creemers
I'm never sure what to put in a bio. If there's anything you want to know, don't be afraid to ask!
  • Location
    Maastricht, the Netherlands
  • Education
    Knowledge Engineering & Data Science at Maastricht University
  • Pronouns
    he/him
  • Work
    Developer at TalkJS
  • Joined

More fromFrederik 👨‍💻➡️🌐 Creemers

Quick tip: Check Out the Code Review Stack Exchange
#quicktip#codereview#community
DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp