Talks

Summarized using AI

Let's Get Creative with Arguments

Polly Schandorf • June 16, 2017 • Earth

In "Let's Get Creative with Arguments," Polly Schandorf discusses the various ways to handle method arguments in Ruby, focusing on enhancing clarity and flexibility in programming. Drawing from her experience as a developer, Polly outlines different techniques, each with its distinct advantages and disadvantages, and emphasizes the importance of selecting appropriate argument types based on specific situations.

Key points discussed include:
- Positional Arguments: Typically simple and commonly used, these rely on the order of parameters but can lead to confusion and poor error messages when the order is mixed up. Polly illustrates this through an example involving a function that describes her cat, highlighting how errors occur when arguments are not passed in the expected order.
- Optional Hashes: These allow flexibility by accepting key-value pairs, making it possible to call functions with various parameters while also assigning default values. However, hidden details about parameter requirements can complicate usage.
- Destructuring: Offers efficient extraction of multiple values from hashes, leading to cleaner and more readable code while noting that over-reliance on this technique may lead to misuse.
- Keyword Arguments: Introduced in Ruby 3.0, this method enhances clarity and provides explicit error messages compared to positional arguments. Each argument must be named, improving readability, although too many keyword arguments may indicate a need for refactoring into objects.
- Splat Syntax: This allows handling a variable number of arguments gracefully, supporting both positional and keyword arguments in a streamlined fashion. Polly provides a scenario with splats, examining how they can succinctly process data for practical applications such as a family adopting shelter cats.

Polly concludes with a call to engage in community events like Ruby for Good, emphasizing the importance of collaboration within the Ruby community and the opportunities available from participating in such gatherings. She encourages attendees to seek connections that could lead to professional growth while reflecting on the camaraderie developed during these events.

Let's Get Creative with Arguments
Polly Schandorf • June 16, 2017 • Earth

Let's Get Creative with Arguments by Polly Schandorf\n\nWould you
like better error messages? Or methods that are clearer to the caller. How about
more flexibility ? Most of us have a preference for parameters, but sometimes
there are better options in certain circumstances. We’ll look at keyword arguments,
option hashes, splats and destructuring. \n\nIn her previous life, Polly was a
teacher of elementary through high school students. After being introduced to
coding using a Rasberry Pi in a teacher workshop - she was hooked, and never looked
back. She is totally fascinated with fermented foods and makes her own Kombucha,
Kefir and Red Wine Vinegar.

RubyNation 2017

00:00:27.260 - Hear me!
00:00:32.099 Yes, we're going to talk about arguments today, as I mentioned on Polish and/or Twitter. I'm a nerdy teacher; I used to be a teacher for 15 years, and I'm pretty nerdy. But now I’m a developer, and while I love being a teacher, I am so grateful to have this second career. I don’t even miss my summers off. I worked at Stack, an ad tech data aggregation company in Baltimore. My colleagues are here at the table, and they can probably give you a much better explanation of what we do than I can. Ruby for Good is my favorite event, and I look forward to it all year. I'm helping to organize Code for Good this year, and supporting Land has been awesome. For Ruby for Good, we’re using Python. I'm also helping to organize V Camp this year, the pair programming and unconference event in the woods for Rubyists. It's a ton of fun, and we have great people who come.
00:01:11.370 So, if your company is interested in getting involved with us or the great community, please get in touch with me. I’d love to hear more about any of these events or talk about them; that would be great! Come stop by and talk to me. Now, today we're going to discuss two paths: the happy path and what happens when you've learned a little bit, have a great plan, and then start executing that plan, only to find out it’s not such a good idea.
00:01:46.890 First of all, raise your hand if you're part of the Ruby community! Awesome! For those of you who haven't heard of it, Yukihiro Matsumoto is the creator of Ruby. We very fondly call him Matz. He's a super kind and humble person. He created Ruby to make developers happy, and that's carried into the community. In the early days of Ruby, if people in the community were chatting about something, some would jump in and say, 'Hey, minasan', which is Japanese for 'everyone'. So we are nice! It’s a fantastic community of friendly people who welcome newbies and have created plenty of space for people to join.
00:02:07.140 I’m grateful to have this language and the wonderful community that came along with it. I’ll let you know that I was part of Ruby for Good this year, which gave us lab access as team leads. It was super cool — I mean, it was super awesome! It had very nice bathrooms, besides being even more creepy than expected. I know you're all super jealous, so be sure to sign up for Ruby for Good this year and be a team lead; you might just get whatever cool swag they decide to give out next year.
00:02:26.230 I love Ruby, and I love how flexible it is, with so many ways to do things. It's really exciting to explore new ways of doing things. I've been mentored by my CTO, Mike Subielski, who has introduced me to some new concepts, and I became fascinated with them. I wish I had learned more about them earlier, so I want to share them with you today.
00:02:50.230 We have lots of methods in Ruby, but they are not all created equally. So, let's take a look. Most of us are using plain positional arguments the majority of the time. A positional argument names input based on the position of the input. Let's start with the pros: positional arguments are super simple to set up. For positional arguments, we can just name the parameters in the function definition, and when we call the function, we name the values in that same order.
00:03:09.600 This works very well, especially in simple cases where it's intuitive what the parameters should be, since they are so commonly used and easily recognizable. However, order matters. So anytime we call a function, the first argument will always be named 'the first argument', the second 'the second argument', and so on. Since the position matters, we have to be careful when passing a branch in the function call and make sure the parameters line up correctly.
00:03:40.040 Imagine I’ve got a function that takes a bunch of arguments about my cat and gives me a sentence that describes it. My cat has gray fur that is short and small in size, with a temperament characterized as wonderful. But this works out really well if I remember the order! It goes terribly wrong when I mix up the order; I end up with a cat that has skittish fur that is brown and long in size, with a temperament that characterizes it as large. Positional arguments do not give us great error messages. They don’t help us figure out how to fix them. If I go through my arguments and get told that I provided four arguments but needed five, I have to go through and pair them up to find out what I might have missed.
00:04:19.620 This becomes problematic, especially if you’ve forgotten the order. You could be staring at it for a long time, trying to decipher what went wrong. If you have great test coverage, this can help mitigate the pain, but if you're working with legacy code and it lacks decent coverage, it can be a nightmare. So in summary, positional arguments are simple to set up and are commonly used, but the order matters. The error messages can be unhelpful, and adding new arguments may force us to refactor our code.
00:05:02.490 To address these issues, we can add an argument with an empty hash designed for it, allowing us to pass key-value pairs. When we call the function, we can add whatever keys and values we want and also assign default values in the function definition. We can default the values for breed and legs, which means we get those for free anytime we call this function. Optional hashes are very flexible, allowing us to customize the arguments we use without requiring a complete refactor of our code.
00:05:43.030 Let’s look at the pros of optional parameters. If you provide a default value, you automatically get that when you call the function. However, if we ever need to override those defaults, we can easily do that as well. Optional hashes allow us to call a function with just a name, since that's required as a positional argument, or we can include various other values such as length or temperament. Each time we call it, we get to decide what we want to pass in, which allows for significant flexibility. If we have a particular need to include new parameters, we don’t have to refactor the existing code, which is a massive advantage.
00:06:30.570 However, there are some cons. When passing parameters in an optional hash, the caller usually has very little information up front. To know how to call the function, you might need to look at the function body to see what variables are required. The keys and values are stored as a hash, which means you have to do a bit more work pulling them out into usable variables. This can become cumbersome and difficult to manage, especially in larger codebases.
00:07:19.370 Next, we can use structuring, which allows us to assign multiple values to variables at the same time. This method is more efficient and makes the code easier to read. Historically, when we work with a hash, we would need to extract and assign each value manually. However, through structuring, we can name the keys and values inside the pipe in Ruby so that they are automatically assigned within the block. This greatly simplifies the code.
00:08:03.460 With structuring, we can also use parallel assignment, which clarifies what’s happening in the code; it’s easy to follow. For example, when pulling instance variables out of a hash, we could do that more elegantly with structuring. Instead of assigning them one by one, we can extract them all within one straightforward call. This provides clarity and cleanliness in our code, rather than pulling each variable separately.
00:08:43.420 One of the main drawbacks, however, is that destructuring doesn't fit every situation. It can become an overused tool, akin to using a hammer for every problem, and it's best to remember that there are alternative methods available. These include keyword arguments and optional hashes, like we’ve talked about. Using the right tool for the job is key, and while a destructured approach can be simple for clean code, it doesn’t always suit every single situation.
00:09:12.190 Ruby 3.0 introduced keyword arguments, bringing the power of hashes into arguments. The major benefits include clarity and clearer error messages compared to positional arguments. When using keyword arguments, you must include the keyword when calling the function, which may feel verbose but is incredibly clear for both the caller and the reader. When dealing with multiple arguments, calling a function with keyword arguments looks a lot like calling a hash, providing a stronger similarity.
00:09:50.270 With keyword arguments, if you forget to include one like 'size', the error message will explicitly state that 'size' is missing, instead of just saying you're missing an argument. This is incredibly helpful for debugging. Additionally, we can still use default values for keyword arguments. This means we only have to pass in the parameters we want to change or omit entirely every time we call the function. This structured yet flexible approach is another great strength of Ruby's keyword arguments.
00:10:29.750 However, keyword arguments can start to become tedious if there are too many. In some cases, if a large number of keyword arguments are present, it may be a code smell indicating the need for creating an object instead to manage the multiple parameters more elegantly. Furthermore, keyword arguments only work in Ruby 2.0 or greater. So if you find yourself working with legacy Ruby, it might take a while before you can fully utilize this feature.
00:11:13.460 There’s a common pitfall here: if you don’t realize a method has keyword arguments, you may accidentally try to call it like you would with positional arguments. This can lead to funny error messages indicating you sent in more arguments than expected. Also, it's crucial to place keyword arguments last in the method signature, to avoid confusing the interpreter. Ultimately, the pros of keyword arguments are their clarity, excellent error messages, and the necessity only to supply the parameters we need.
00:11:46.080 Finally, we come to splats. Splat syntax allows us to receive an undefined number of arguments, providing flexibility in the types of arguments we can accept. Instead of going back and forth between the pros and cons, I will highlight some fun tricks for using splats in tandem with the arguments we've already looked at today. The flexibility splats bring can also allow for interesting grouping of data.
00:12:31.580 What’s clever about using splats is that they allow us to handle varying numbers of arguments gracefully. Imagine you're working in a scenario where a family wants to adopt the youngest and oldest cats from a shelter. By utilizing a min/max function with splat arguments and structuring, you can easily extract the required information without convoluted logic. This way, splats streamline both positional and keyword arguments efficiently.
00:13:11.870 That concludes my talk on the various ways we handle arguments in Ruby. Thank you all for your attention! Are there any questions?
00:14:04.560 I’m so glad you asked! If you've never been to Ruby for Good, that's awesome! Ruby for Good is a weekend-long retreat focused on programming, splicing, and collaboration. We stay at this beautiful campus in the woods. It's a serene setting where we hack on projects for nonprofits. We have dinner together, socialize afterward, and even engage in games and karaoke. If you’re lucky, they might even throw in some dance lessons. It’s a fantastic opportunity to build community, find a mentor, create friendships, and many have secured jobs through connections made there.
00:14:55.830 I truly believe it's an amazing experience, and I hope to see all of you there next year. This year, we sold out in just ten days, so it's a competitive process to get involved. I know you’ll want some of those fantastic swag bags, so make sure to sign up early and consider being a client as well.
00:15:12.850 Thank you very much!
Explore all talks recorded at RubyNation 2017
+3