Re: will map:put() never fail?
- Posted by jeremy (admin) Sep 10, 2011
- 1098 views
I prefer the method it currently uses. For example:
map m = map:new() sequence name = "John" map:put(name, "age", 22)
is an exceptional problem. It is a programming error and one cannot recover from it by checking the return result. The proper thing to do is an application crash. If it fails because of memory, your app is going to fail regardless. If it fails because you pass a bad operation:
map:put(name, "age", 22, 192839283)
then it's a programming error and it cannot be recovered from by checking an error return value. It's better to fail early than late. Failing late only obscures the real problem. It's also better to check ALL function returns. By turning an exceptional error into a passable situation, you introduce errors into everyones code. If the routine is going to pass 99.9% of the time, who is going to check the return result with every call to that routine? No one. That would lead to horrid code as well:
if map:put(name, "age", 22) != map:SUCCESS then error() end if if map:put(name, "city", "Smalltown") != map:SUCCESS then error() end if if map:put(...) then .... end if
Now, number 3 in Dereks list is pretty debatable.
3. The OPERATION argument is invalid for the case when the KEY does not exist in the map.
For that, an error code result actually makes sense, but one can handle this a bit differently and save the terrible coding techique given above. They can do it by:
if not map:has(my_map, "name") then map:put(my_map, "age", 100) else map:put(my_map, "age", 4, map:DIVIDE) end if
Thus, you have provided a solution for the potential failure of map:put() w/o having to fall back on checking the errror result. Now, the code may be slightly better if map:put returned an error code in this condition, ONLY IF the majority of the iterations you are doing a divide operation:
if map:put(my_map, "age", 4, map:DIVIDE) != map:SUCCESS then map:put(my_map, "age", 100) end if
but that is only a good case if you know the majority of the time age already exists. Not sure that warrants an error return value when a valid method exists for avoiding it.
Jeremy