CSC/ECE 517 Fall 2007/wiki1b 1 c4

From Expertiza_Wiki
Jump to navigation Jump to search

Introduction

Problem

If multiple methods with the same name are defined, there needs to be some way of determining which method a call refers to. The general rule is given on p. 123 of Programming Ruby. But questions still remain.

Questions

  • Is it possible to get unexpected behavior if one of the modules you are using is "enhanced" to contain a new method that happens to conflict with a name of an existing method?
  • Is it possible to refer to these methods using a qualified name?
  • Is it possible to use method aliasing to resolve the ambiguity?
  • What approach does good o-o design dictate?

Method

What is it?

A section of code that does or performs a task and then returns a value. A synonym for a method is a function. Methods can also be included within classes and used as accessors, mutators and setters.[2] Methods are created with the keyword def and the name of the method and end with the keyword end. A method is called by simply typing the name of the method and enclosing any parameters to the method in "()". i.e. some_method(some_parameter).[1]

General Rule For Multiple Methods

If multiple methods with are defined with the same name and a call is made to that method, Ruby will look in the immediate class of an object first for the method definition. It then will look in any mixins included within the class and lastly in any superclasses and their mixins. If multiple mixins are present the rule for searching is that the last one included will be search first.[1]

Resolving Ambiguity with Method Aliasing

It Is Possible

It is possible to use method aliasing to resolve ambiguity. The odds of a class having a method with the same name is very small. However aliasing will take care of if a module is included and the module includes a method that has the same name as a method within the class. You would now simply refer to the method in the class by the alias method and ambiguity is solved because the class definition is now independent on whether the module methods are aliased or not.

To truly take out all ambiguity you would need to also alias all methods within the module.

every module and class has alias and reference the alias ambiguity should be avoided providing alias is descriptive. classes and modules

Example

Negatives

copy is created with method aliasing thats alot fo aliasing to do. simply giving more descriptive names would work alot better/

References

  1. Programming Ruby: The Pragmatic Programmers' Guide
  2. http://en.wikibooks.org/wiki/Programming:Ruby_Method_Calls