Some thoughts about pair programming &Code Pointers #06 — Arguing with keywords…

I’m up bright and early to get cracking into the last week of our makers academy pre-course. This week we’re supposed to be pair programming with anyone and everyone we can find…

I’ve got to admit, I am a little bit apprehensive about pair programming. I’ve always preferred working out problems myself — it will be really interesting to see what I discover about myself through pair programming.

The few times I’ve done it so far, I’ve found that I kind of go silent while I’m figuring out the problem and looking things up then suddenly resurface with the solution!

I don’t think there will be any issues though, I think it will be a really good experience in learning how to collaborate on a project, an important skill for hackathons for example.

Code Pointers #06 — Arguing with keywords

This morning I came across the concept keyword arguments (or named parameters).

Keyword arguments are a way of allowing you to pass specific pieces of information to methods in a hash-like way (in fact, pre-Ruby 2, you used to have to use a hash to do this).

def foo(bar: ‘default’) 
puts bar end foo # => ‘default’
foo(bar: ‘baz’) # => ‘baz’

Note how you can define a default value, so that if you do not provide a parameter to the method it will use that.

You can also set it so the keyword argument is required. For example:

def foo(bar:) 
puts bar end foo # => ArgumentError: missing keyword: bar
foo(bar: ‘baz’) # => ‘baz’

Note how this returns an exception in the form of ArgumentError.

Another blog I read makes the point that one of the benefits of keyword arguments is that it makes methods more readable — you know which parameter is which. For example consider this method:

def mysterious_total(subtotal, tax, discount) 
subtotal + tax — discount
mysterious_total(100, 10, 5)                             # => 105

Yes this method does its job, but a reader wouldn’t know which value was which. By using keyword arguments, we can make it more explicit and readable:

def obvious_total(subtotal:, tax:, discount:) 
subtotal + tax — discount
obvious_total(subtotal: 100, tax: 10, discount: 5)       # => 105

We can also switch the order of the arguments, for example:

obvious_total(subtotal: 100, discount: 5, tax: 10)        # => 105

If we switched the order of the arguments in the original “positional argument” method, we would get a completely different answer because it is expecting the parameters to be in a certain order.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.