Wednesday, March 9, 2011

Required And Optional Function Parameters

I love using different programming languages. Whether it's C#, PHP, Python or Ruby on Rails, they each have their strengths, which makes finishing projects faster. Choose the best tool for the problem.

Today a project I'm working on required an additional parameter to a  Javascript method that was already called in several files. In C# I could write an overload method

Use Overloading in C# versions below 4
[csharp]
public void MyFunctionA (int par1, int par2)
{
//some code
}

public void MyFunctionA (int par1, int par2, string par3)
{
//some code
}
[/csharp]

Use Default values in C# 4
[csharp]
public void MyFunctionA(int a, int b = 0)
{
//some code
}
[/csharp]

A solution I just found today is using named parameters with defaults
[csharp]
public void MyFunctionB(int par1, int par2,
string par3 = "test")
{

}

MyFunctionB(par1: 10, par2: 4);
MyFunctionB(par1: 10, par2: 4, par3: "My Test");
[/csharp]

One way to do it in PHP is through a default value function parameter. If nothing is passed into the function for that parameter, the default is used:
[php]
function myFunctionA ($par1, $par2 = "test") {
//some code
}
[/php]

And in because I'm just starting to learn Ruby on Rails, I wondered how it handled function defaults or overloads. This is what I found on StackOverflow. Pretty clean, and similar to PHP.

[ruby]
def hello_world(name, message="Hello World"):
print "name = "+name
print "message = "+message
[/ruby]

And finally to Javascript, the real piece I needed to solve. Javascript let's you create a method with no defined parameters, but gives you an array you can check for values. Here is an example:

[javascript]
function myFunctionA() {
alert(arguments[0]);
alert(arguments[1]);
}
[/javascript]

This Javascript option worked great for our needs. We were able to leave the code written originally, but allow new references to the function to add in a new parameter. I didn't want to have another method with duplicate code just to handle the one new parameter, and this seemed to be the best solution.

I'm sure some of you would solve it a different way, so please share.

Thanks to Noah Sparks for helping resolve this issue.
Share this article

2 comments:

  1. Nicely done! It's always interesting to learn a bunch of different languages and see how they approach problems differently.

    ReplyDelete
  2. Thanks Mike, yes, I like seeing the differences. Remembering them in a time of need is something all together different. And your comment means a lot.

    ReplyDelete

 
Copyright © 2003 - 2014 Thom Allen Weblog • All Rights Reserved.