Page 1 of 2

Let's Build Objects in GForth Jan 2

Although FORTH is considered by many to be a procedural language, its flexibility has allowed it to adapt other programming styles as well. If you are running GForth (HINT: sudo apt-get install gforth), you already have access to a great object oriented programming (OOP) library called oop.fs.

The documentation is well written, but might be a little bit wordy if you just want to play around.

Below is an example of OOP in GForth that will cover 80% of the use cases:

  • Instance CRUD
  • Instance level variable CRUD
  • Method definitions
  • Method calls
  • Inheritance

\ include oof.fs for GFORTH OOP. There's also mini-oof.fs, which is
\ only 12 lines long and gives you (most of) the same functionality
\ in a smaller package

include oof.fs

\ Let's define a class called "square". It inherits from the object
\ class, which  is the mother of all classes in oof.fs.
\ Syntax: <parent> class <child>
object class square
    \ Give it an instance method called "area"
    method area

    \ Give instances of square 2 cells of memory.
    \ On my system, that means 128 bytes.
    1 cells var length
    1 cells var width

  \ Now that class "square" is defined, we can implement it.

    \ Constructor expects 2 integers on the stack when called: width
    \ and length.
    : init ( n-width n-length -- self )
      \ Take the first item on the stack (length) and store that into
      \ the  instance variable "length".
      length !
      \ Same thing for width
      width ! ;

    : area ( self -- n-area )
      \ Grab length and push onto stack
      length @
      \ Grab width and push onto stack
      width  @
      \ Multiply length by width
      * ;

\ Create a new instance of square called "my-square"
20 30 square : my-square

\ Call the method "my-square" on square instance "my-square"...
\ ... Print the return value to screen.
my-square area . cr

\ Destroy the square object (for example purposes)
my-square dispose

\ gracefully exit.

I hope that helps. If you have any questions, you can always ask the friendly folks at /r/forth.

FORTH Echo Server Revisited Dec 29

GForth comes with a special library called unix/socket.fs for dealing with TCP socket connections. Unfortunatly, there is (as far as I know) no formal documentation on using socket.fs aside from reading the source code. If you’re a FORTH novice like me that isn’t much help.

The best thing I could find was an example TCP echo server on Rosetta Code. You can try it out for yourself by:

  1. Copy the code into a local file.
  2. Execute the file via gforth FILENAME
  3. Connect to the echo server using telnet (telnet localhost 12321).
  4. Send it messages via telnet, seperated by a carriage return.

I decided to factor down the code some more and add additional comments:

\ Pull in the library
include unix/socket.fs

\ Set some defaults
128 constant buffer-size
4 constant maximum-connections-allowed

: 3drop
  drop drop drop ;

: read-the-buffer
  2dup 2dup buffer-size read-socket nip
  dup 0> ;

: print-the-data
    ."  got: " 2dup type ;

: echo-back
    rot write-socket ;

: (echo) ( sock buf-- sock buffer )
  3drop ;

create buffer buffer-size allot

\ This is the main loop. It expects the TCP port number
\ to be  on the  stack when called (12321 in this case).
: echo-server ( port -- )
  \ Call 'create-server', passing in the desired port
  \ number on top of stack.
  \ ^ Socket id is now on top of stack...
  \ .. after that, set the socket ID to listen with a
  \ max backlog of 4 connections.
  dup maximum-connections-allowed listen
    \ This word will block the thread and listen to the socket.
    dup accept-socket
    cr ." Someone just connected to the socket! " cr
    \ Push the buffer on the stack...
    \ ...then grab the execution token for (echo)
    ['] (echo)
    \ Execute the XT for `(echo)` and push the
    \ exception onto the stack (or 0 if OK)
    cr ." Disconnected with status code " .
    drop close-socket
  again ;

12321 echo-server


Building Structs in FORTH20XX Dec 28

Newer (> 2012) versions of FORTH allow you to create struct datatypes in a similar fashion to C.

\ Define a structure named point
   FIELD: ->x
   FIELD: ->y

\ Create a new point named vertex
variable vertex point

\ set the x value of vertex to 128
128 vertex ->x !

\ Push the value of vertex's x value onto the stack
vertex ->x @

\ show the results
." The value of x in variable `vertex` is: " dup . cr


UP NEXT: Defining float, char, byte and double member types. further reading

Life is Short, You Need FORTH FFL Dec 28

The GForth FORTH interpreter does a lot of stuff out-of-the-box, but it can’t do everything. The FORTH foundation library supplements a FORTH environment with a lot of the things you would expect from a language.

It provides stuff like:

  • JSON readers / writers
  • Dynamic arrays
  • Dynamic map data structures
  • Linked lists
  • Random numbers
  • Regexs
  • XML
  • Unit tests
  • rainbows
  • unicorns

Here’s how you get it:

  1. git clone
  2. The /ffl folder has all the files you need to include them into your project.
  3. include ffl/ffl.s will add all FFL libraries to a program
  4. For finer grained includes, include the file directly (eg: include ffl/jis.fs for JSON input stream only)

Productivity Fatigue Dec 28

After several weeks of high productivity at work and in my personal life, I finally hit the wall. This doesn’t surprise me, nor has it caused any serious issues in my personal life, but deep down, I know that I followed an unsustainable pace and that people must take breaks to keep a healthy outlook on things.

A year ago, I talked about the importance of fun for programmers. It would seem that it is time to take my own advice.

The FORTH programming language has always intrigued me but I never let myself explore it because:

  1. It’s weird. Like, weirder than Lisp weird.
  2. Few people use it anymore
  3. I should spend my freetime doing useful things.

Well, it’s break time, and I’m throwing practicality out the window. During this break period, I will devote my free time to FORTH projects. And only if it’s fun. And never if it’s useful.

How long of a break will I take? 40 hours of free time seems reasonable.

Here we go!

Testing Is Easy Dec 20

Many new developers have trouble wrapping their heads around the concept of unit testing. There are a lot of reasons for this, and I think most of it comes from the overhead of learning a test framework.

An example of a powerful (but daunting) test framework is Rspec. It’s a test framework that let’s you write very readable, easy to maintain tests. The downside of its power is that it can take a while time to learn. In the case of Rspec, there are even books and websites that showcase all the things you need to learn and all the ways you can do it wrong.

When you’re struggling to just learn the syntax of a new language, all of this testing stuff can sound pretty confusing.

Why Bother Writing Tests?

When writing small apps it is common to write code, run it locally and manually test that it is working. It only takes a few seconds and you can be sure that the code works. When you have an app with hundreds of features and thousands of lines of code, the task becomes more time consuming or impossible.

Somewhere along the way, developers came up with the idea to write “unit tests”. Unit tests make sure that every method in your code works as expected. The expectation is that when all the units are pieced together, they will work properly because they all worked fine in isolation.

There are some other issues that testing solves, too. Some examples are:

  • Being able to know if you’ve introduced a bug to a once-working method.
  • Find failing code before it crashes in the wild
  • Give other developers the ability to know if they’ve installed the app correctly (just run the tests after installation)

That Sounds Hard!

Learning a new framework can be hard, but the concept doesn’t have to be. Let’s write a small method that we will write tests for later:

def add(first, second)
  first + second

It’s a simple addition method that adds two numbers together. Here’s an example of how you might run it:

add(2, 2)
# => 4

Great. Now let’s test it. Instead of using a scary test framework, let’s write our own library to test this code.

Your Own Testing Library

Our test “library” only has one method: test. It is a method that takes two arguments and tells you if your method is acting as expected.

# test.rb
def test(expected, actual)
  if expected == actual
    puts "PASS. #{actual} is #{expected}."
    puts "FAIL. Expected #{actual} to equal #{expected}."

Then we can write a test file in tests.rb

# test.rb
test 4, add(2, 2)

Now we can test the method (and any future methods we decide to write) by running a single file.

> ruby test.rb

PASS. 2 is 2.

Next Steps

That’s really all there is to testing. If you still are too scared to learn a full flavor test framework like Rspec, perhaps you can try an alternative like MiniTest, Riot or Wrong.

There’s no reason to not to write tests for your projects.

Author’s Note: This article is a reconstruction from memory of a great TDD article I once read but failed to find again. If you know the author, please let me know.

The Value of Old Textbooks Dec 16

I read a great article on NPR recently entitled “When Woman Stopped Coding”. The article made the point that gender norms and nerd culture of the ‘80s excluded girls and created an unfair advantage for boys by the time they showed up for their freshman year as computer scientists.

One particularly interesting part of the article:

"I remember this one time I asked a question and the professor stopped and
looked at me and said, 'You should know that by now,' " she recalls ...

In the '70s, that never would have happened ...

This situation is still true today for many people who enter tech at an older age, especially woman. If you were not around when the digital revolution started, you have a lot to catch up on. This is enough to drive away many people from ever becoming programmers.

Despite how fast the industry moves forward, I recently surprised myself when I read an old textbook related to assembly languagee for the z80 microprocessor .

A 34 year old textbook that is still useful.

The book made no assumptions about what the reader knew about computers, because it came from a time when barely anyone knew how a computer worked. It explained the difference between bits and bytes, assembly versus high level languages and a multitude of other concepts that a new programmer today might be expected to “know by now”.

By the end of the book, it was covering topics that are advanced even by today’s standards.

As a learner, one must always challenge assumptions. As a teacher, one must build complex understanding from simple parts. There is still a lot to learn from the past, even in a forward facing field such as computing.

Javascript Quirk of the Day- Negative Zero Dec 12

Want to have some fun with Javascript? Try typing this in your console:

0 * -1
// => -0

Well, that was unexpected. I would tell you all about it, but it seems as these folks have already done a good job of explaining why it is the way it is.

Nested JSON: The Root of all API Evil Dec 11

When developing an API, it is best to stay generic. This keeps your API ready for future changes and encourages API users to write clients that are flexible to change also.

One pitfall many developers fall into is making JSON endpoints that try to do everything in one request. Usually, this takes the form of deeply nested JSON structures.

An example might be a /users endpoint that embeds all of the user’s blog_articles, profile_data, personal_settings, and friends into one JSON structure.

This can create a lot of problems down the road such as:

  • Unexpected circular references in your return JSON that crash your JSON encoder
  • Slow request cycles and wasted bandwidth
  • Slow N + 1 queries, even for simple GET requests
  • JSON that is hard or impossible for humans to read
  • Inability or difficulty in creating new API clients because endpoints are too specific to the needs of current API consumers

The alternative is simple: never nest more than one level deep, exercise discipline when deciding to embed resources and use hypermedia resource URLs where possible as an alternative to shipping the kitchen sink with every request.

It's Hard to Commoditize Talent Dec 10

I’ve been afforded the opportunity to help several people enter the developer world professionally. Helping people enter a lucrative career that they enjoy doing has been a rewarding experience.

One question that new developers often ask me is “What certifications can I take to become a better Ruby/Javascript/thing_x developer?”. The simple answer is that there is no such certificate out there, or if there is, it is of little value to prospective employers. That’s not a bad thing.

In fields such as network administration*, one can study for an exam, pass the test and start looking for work. We’re not so lucky as developers. Or are we?

The great thing about software development when compared to other IT occupations is that we have an uncapped potential value offering to employers. We can build platforms that generate millions of dollars or solve unbearable pains. Programming skill goes beyond an ability to measure facts and requires us to use be creative in ways that can’t be easily measured.

My advice to new developers looking to polish their resumes is to avoid certifications completely and instead focus on how they can showcase their ability to solve problems with computers. Usually, this means contributing to opensource projects, teaching or speaking at events (there are plenty of other outlets, but these are the most common).

So put down your flash cards and go have fun solving some problems in front of others. It will make you a more marketable developer and you will learn more in the process.

Further reading: Coding Horror

*FULL DISCLOSURE: I used to be a network administrator

Next page