When extension methods aren’t a suitable replacement

A lot of API 2 is extension methods that are replacements for the classic global framework methods.

String.LowerCase is for all intents and purposes the equivalent of Lowercase(string).

Except when its not.

If you happen to have methods that can return a wide variety of types you may not be able to use the extension methods.

For instance if you have something like

Function Foo(NameOfTypeToReturn as string) as Variant
     // this code IS just for illustration purposes !
     select case nameOfTypeToReturn
       case "String"
           return "string"
       case "Double"
           return 1.234
       case "Integer"
           return 99 // yeah that many red balloons !
       else
           return nil
       end if
End Function

and you were to try and do

Dim s As String

s = Foo("Double").Lowercase

s = Lowercase(Foo("Double"))

only one of these will compile. It’s NOT the extension method style.

And it makes perfect sense why not.

An extension method has a specific signature.

Lowercase is defined like

Function Lowercase(extends str as string) as String

essentially for this to MATCH the parameter to it has to already BE a string. But the return value from Foo is a variant – that can be turned into a string – but isnt already a string. So that usage “doesnt match”. An dyou get a compilation error.

The second however will accept something that can be turned into a string. Which a variant can do. So it compiles just fine.

2 Replies to “When extension methods aren’t a suitable replacement”

  1. 1) it was a dead simple example so yes you could manually write the correct conversion each time
    2) You have to write custom code for each possible return which is not useful

    Try now
    Make foo do

    Function Foo(NameOfTypeToReturn as string) as Variant
    static r as new random
    // this code IS just for illustration purposes !
    select r.inRange(0-3)
    case 0
    return “string”
    case 1
    return 1.234
    case 2
    return 99 // yeah that many red balloons !
    else
    return nil
    end if
    End Function

    😛
    The OLD API version still works
    The API 2 one, made of an extension, doesnt

    There are other cases where the function call ones work where extensions dont. For many of the same reasons

Comments are closed.