Last 3 weeks I am trying to convert my biggest project to API2.
But one thing decided me to stop converting to API2.
That’s changing Instr to IndexOf. The biggest problem here is that Instr returns 1 for the first char, while IndexOf returns 0. I do understand the switch to zero based instead of 1 though. It is logical to do so.
This may seem an easy fix, but in very complex code, it is almost impossible unless you debug everything. In my case, the risk is way too high to break my code.
Create a Global Module called InstrNew that takes the same parameters as Instr but uses IndexOf internally and returns +1 then global replace Instr for InstrNew. Either forget about it as it should be optimized out at compile time (not tested), go through it at your leisure later, or don’t change it until you need to.
Be careful of subtract 1 (-1) to StartPosition too.
And be also careful that if StartPosition is greater than the text you are searching in, you will raise an OutOfBoundsException. issues #69674
Instr returned 0 (not found) in this case.
I never had any trouble remembering that string functions are 1-based and arrays are 0-based. Another instance of Xojo fixing something that wasn’t broken for the sake of some kind of abstract purity, at the expense of users.
Yes, but that’s not a good reason. It’s a good reason not to change InStr, but a bad reason to make IndexOf 1-based. IndexOf is a new function. I can’t say it has no legacy attached to it, but there is very little.
I went through all this. Took me about a weekend to convert my project. Yes, InStr to IndexOf is an area that needs special attention. But I found my code simpler to read as a result. It’s a good change despite the growing pains.
Remembering that InStr is 1-based is the easy part. How it works with similar methods is what makes its response tricky. Tim posted my reasoning, so I’m not going to recap. It’s mentally easier to do Haystack.Left(Haystack.IndexOf(Needle)) than Left(Haystack, InStr(Haystack, Needle) - 1). This is a basic example, but with more complexity, the need to counter offsets is very taxing. Even now, I’m doubting wether or not I got the API1 version of the code correct.
i guess new api2 throw an error for everything like methods in c#.
as example left 100 with a 80 char string fail.
it is not just replace and care about 0 or 1 index.
you have to care about it behave too.