Comment

Comment by danuker

The best way I've seen to handle such problems full of possible mistakes is to use Test-Driven Development.

Write a test for a trivial case, like a zero-length array. Think of the design. What should it return? Should it throw an exception? Do that, and only that, in the implementation.

Each iteration after you add a test, you should first focus on getting every test to pass, then commit to version control, then refactor to get the clearest implementation.

A next iteration would be to test with a single element - a matching one, case in which it should return its index (zero in zero-indexed languages).

Then with a non-matching one - again, you have to make a design decision: throw an exception, return -1, or something else.

Then a case with two elements, when the first is the match. Then two with the second matching. Then two with none matching.

For as long as you can think of tests breaking your implementation, keep thinking of edge-cases. Eventually you end up with a formidable collection of test cases, and you will not be afraid of refactoring or changing things, because you will find out quickly and easily which tests break.

Edit: boxed mentioned Property-Based Testing and Mutation Testing. These are amazing ways to come up with more corner cases to cover.

parent danuker 4 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton