Monday, April 25, 2011

Optional Parameters

Did you know that the parameters you create for methods can be optional? There are two easy ways to do this and they can even be combined. The simplest way to make a parameter optional is to add the Optional keyword:

MyMethod(x as integer, Optional y as integer)

In the above example, the keyword Optional makes the "y" parameter optional. If only one parameter is passed, y will have the default value for an integer which is zero. You can also include the default value if you want it to be different that the default value for the data type you are using:

MyMethod(x as integer, Optional y as integer = 5)

When you provide a default value, the Optional keyword is, well, optional. But it's good to use it because it makes your code a bit more explicit.

You can even have the same parameter use two different data types by making two methods with the same name but with different parameters. For example:

Foo(x as integer)
Foo(x as boolean)

Both methods can have their own code or you could have one call the other. So as you can see, there's a lot you can do with parameters.


Jason said...

It's definitely a good technique. I often use overloading (having a method with the same name and different parameters) and optional parameters. Optional parameters are great for giving extra strength to a method without eliminating its simple uses, and I've often overloaded many native RS methods to expand their functionality. For example, sometimes I want to convert an entire array of strings to doubles, so I made the following in a Utilities module:

Function Val(List() As String) As Double()

Steveorevo said...

This is important information for the newbie programmers out there. Suggestion: Newbies may want to know what the tech-speak that seasoned pros use (Not to mention other programmers that don't know what RealStudio is capable of)...

'Optional Parameters' (as you defined) and 'Overloading', where the programmer defines two methods of the same name. This is also referred to in 'polymorphism', a feature of object oriented programming languages like RealStudio. Outside of Real Studio's documentation (which doesn't mention this). Giving user's a subtle background with accepted terminology from other languages can help users transition or find more documentation/resources that can apply to Real Studio too! Has anyone created a Design Pattern book based on RealStudio's syntax yet?

DrScott said...

It's very difficult to write a programming book that will make significant money when you have a restricted audience. I'm saying this as the author of two books, plus several articles for RBLibrary (including a 45 page article). Each took 1-2 years to write and generated a total of only a few thousand dollars each. That's a very poor work to earnings ratio. You really have to write a book a with a very broad audience to sell many copies.