dimanche 29 octobre 2023

Prevent input validation on an input prarameter of a method

Currently:

`void deleteCase(caseId, version){ var case = getCase(caseId); if(case is null) throw ArgumentNullException(caseId);

if(verifyVersion(case, version) == false) return;

return delete(case); } bool verifyVersion(case, version){ if(version is null) throw ArgumentNullException(version);

// call db to verify the version is mathching

}`

deleteCase(1, null) => it throws an exception as version cannot be null

Question: now we have a situation we can delete a case without providing its version, it means being able to call deleteCase without providing version.

Solution 1: add an optional flag indicating no need to check version `void deleteCase(caseId, version, checkVersion = true){ var case = getCase(caseId); if(case is null) throw ArgumentNullException(caseId);

if(checkVersion == true AND verifyVersion(case, version) == false) return;

return delete(case); }`

old calls: deleteCase(1, null) => works as expected before since checkVersion is by default true deleteCase(1, "1.0") => works as expected before since checkVersion is by default true new calls: deleteCase(1, null, true) => works as expected before deleteCase(1, null, false) => works as we want deleteCase(1) => works as we want

The problem with that is we've added a new parammer to control another parameter => not accepted. And also we should not be able to do deleteCase(1, "1.0", false) which version is redundant

Solution 2: overload deleteCase to not having version parameter

`void deleteCase(caseId){ var case = getCase(caseId); if(case is null) throw ArgumentNullException(caseId);

return delete(case); } void deleteCase(caseId, version){ var case = getCase(caseId); if(case is null) throw ArgumentNullException(caseId);

if(verifyVersion(case, version) == false) return;

return deleteCase(caseId); }`

Now any deleteCase calls wrok as expected. But the only problem is getCase gets called twice if pass version which makes it anti performant.

Any idea what can we do to make one call?

Aucun commentaire:

Enregistrer un commentaire