r/learnprogramming • • Oct 26 '26

How thoroughly should I check arguments to a function

Below is a function that takes in an array of objects and averages their `count` properties:

function computeAverageCount (group) {
  let n = 0
  let sum = 0
  group.forEach(curr => {
    const count = curr.count
    sum = sum + count
    n++
  })
  return n > 0 ? sum / n : 0
}

Let's say that these objects containing count properties were retrieved from a server, which documents that the `counts` are a number greater than or equal to zero. Also, this function is used as an internal helper in an application.

To what extent should I check the data coming in to the function? I could add checks in the function to ensure that the `count` is an integer that is greater than or equal to zero. But if I expect the server to only send those kinds of values, are these checks overkill? I suppose it's possible for something to go wrong server-side that would cause unexpected counts to be sent.

I appreciate the feedback.

UPDATE: Thank you for your responses! It means a lot being able to learn from this community. To summarize the main takeaways:

  • It's definitely a good idea to validate the `count` data. The server may promise that counts are always a number >= 0, but the application should still double check that the data is as expected. In general, validating all server data where it enters the application is the cleanest approach. That way, the validated data can be used anywhere inside of the application and avoids the "shotgun parsing" anti-pattern.
  • As far as unit testing the function goes, it's important to establish the function's contract. How it should behave when given various inputs, including ones that we don't expect to pass in. Writing unit tests for all of these cases helps to reinforce the contract. The function might not include logic to specially handle negative counts because we validated the data beforehand. But it's still good to test these edge cases to confirm the function's behavior. I think that's the general recommendation. There were a couple posts that leaned toward less defensive testing: if we really don't expect negative counts and the function doesn't specifically handle them, then it's not necessary to test this case.
13 Upvotes

28 comments sorted by

7

u/West-Anteater-1917 Oct 26 '26

I'd validate once at the boundary where the data comes in, not inside every helper. Parse the server response there, reject or log anything that isn't a non-negative number, and then pass clean data down so the averaging function can just trust its input. Your helper is fine as it is, and a failed check at the edge gives you one obvious place to look when the server misbehaves. In PHP I usually do the same with a small mapper or DTO that fails loudly on bad shapes.

1

u/czerilla Oct 26 '26

I appreciate languages that provide an assert-syntax for this. That's exactly what this part of your code should be doing: assert the conditions you are expecting to be true at this point in the code (typically at the beginning of a function, validating the input, as you said) and carry on with the knowledge that you've excluded the predicted edge cases.
At that point it's just a matter to document this requirement of that function, especially when it's public, and you've done your due diligence.

2

u/West-Anteater-1917 Oct 27 '26

Good point on documenting it, that part gets skipped a lot. A short note about what the function assumes about its input saves the next person a lot of guessing.

1

u/Hembhorg Oct 26 '26

Thanks so much for the responses so far! This has been very helpful. I have a follow-up question. When it comes to unit testing the function as it's currently implemented, does it make sense to test `count` values that are not expected (e.g. negative, undefined, numeric string counts)? I think testing these cases helps to document how the function currently handles them. But it might also be confusing to include them because it suggests that the function properly handles those cases even if it doesn't.

2

u/POGtastic Oct 26 '26

You should absolutely test those because it is a good idea to figure out how you want to handle those kinds of invalid inputs. It is totally okay to return NaN or throw an error, but you should test it so that those things are rigorously defined.

properly handles

Throwing an error or returning NaN falls under "properly handling" those cases.

1

u/Hembhorg Oct 26 '26

CelebrityChess made a point that locking in whatever the function happens to do with bad input can make refactoring more challenging. I'm curious what your response is to that.

For example, let's say I decide to validate the server data where it enters the application. That way, my function doesn't need to do its own checks for the counts it receives. Returning NaN due to an undefined count is not desired behavior, but it is what the function currently does. And I don't care to change that behavior since I validate the server data prior to calling computeAverageCount. Is it still a good idea to include a test that asserts NaN is returned when one of the counts is undefined?

1

u/POGtastic Oct 26 '26

It depends, but I would prefer to consider changes in terms of failing unit tests (and then think about how the tests need to change) rather than to have the behavior be completely unspecified (which might break things in ways that you don't anticipate).

As long as the behavior across your codebase is consistent, I wouldn't mind too much. ... but you also can't be sure that the behavior across your codebase is consistent unless you test it and start asking "Is the default error behavior actually what I want?"

1

u/mrbaggins Oct 26 '26

If you're writing a unit-test suite that runs automatically, why would you NOT test those?

Solve the confusion by debug.logging the warning/error. Anyone looking at the code will see it's catching something unintended.

1

u/Ill-Answer1919 Oct 26 '26

Validate the API response once when it enters the application rather than repeating checks in every helper function. For your unit tests, I'd cover valid counts, empty arrays, and unexpected values like undefined or strings. The important part is deciding whether invalid data should throw an error or be rejected, instead of letting JavaScript silently produce a misleading average.

1

u/Hembhorg Oct 27 '26

Is it worth implementing extra logic in the function to, for example, throw an error if there's an undefined count, assuming that you've already validated the API response when it enters the application? The function shouldn't be receiving any unexpected values thanks to the validation.

5

u/josephjnk Oct 26 '26

Spreading defensive checks throughout your code to deal with untrusted inputs is an antipattern, sometimes called “shotgun parsing”. If you catch an error in an input deep inside a nested utility, then what? Your program may have already started processing the input elsewhere, and now you’re in an invalid state. Plus, it’s hard to guarantee that your system will be safe over time. It’s called “shotgun parsing” because it’s a blast of checks scattered all over the place, and it means that you can’t be sure that every invalid input is checked without looking at the whole codebase at once.

The alternative to shotgun parsing is sometimes called “full recognition before processing”. If your program is going to accept untrusted input you should validate all of the relevant invariants up front at the outermost layer, and the rest of the codebase should trust that these checks have been performed. This keeps your logic focused and makes it easy to audit whether any checks have been forgotten by looking at a single place.

If you control both the server and the client then server responses are not technically “untrusted”, so strictly speaking you could skip them. In practice I find that it’s _usually_ best to still have checks at the boundaries between systems, to catch issues early and prevent bugs from spreading across architectural boundaries. An exception would be if you’re using something like graphql, which provides a typed query layer, or if you’re autogenerating your clients from OpenAPI specs provided by the server.

Finally, I recommend using TypeScript. So many checks for internal consistency can be avoided by just having a type system.

2

u/grc007 Oct 26 '26

You’ve had a lot of good answers. But give yourself a pat on the back for a really good question. This is the sort of questioning approach that is key to software development.

1

u/HealyUnit Oct 26 '26

The unhelpful answer is probably "it depends". I'd agree with u/QuarterlyHandling that you should write defensive code, and it can't hurt to put in some checks to make sure curr has a property count, but only you can really be the judge of whether that's necessary or not.

You also might want to consider what happens when you get something - an object, a number, whatever - that does not fit your pattern. For example, if you have a function computeTotalCharge(items) for your store that totals up the items in a user's cart, silently filtering out items that can't be processed is not acceptable. You'd basically be saying "we can calculate this item, so you get it for free". Not a good business decision. However, if the thing you're calculating is, say, "number of 100-meter dashes run by each student in some high school", then of course some of those might be null (not every student runs track!).

A few nitpicky things I'd change about your code as is, regardless of whether you choose to filter or not:

  1. End your lines with semicolons. Normally, it doesn't matter, but there are some edge cases where lack of semicolons can lead to unexpected behavior. Better to get in the habit.
  2. On your 5th line, change const count = curr.count; to const { count } = curr;. Use destructuring when you can.
  3. sum += count; rather than sum = sum + count;. Reads more cleanly (you're incrementing sum by count.
  4. I'd actually avoid using a forEach here. They're less performant than for() or for..of loops, because you're instantiating a function each time.
  5. This whole loop deally feels like it'd better be served by a reduce() method.
  6. Finally, I'd actually move that final ternary above the loop. In other words, if your array has no items, just return 0: if (group.length) return 0;

1

u/Available_Safe1818 Oct 26 '26

Isn't his 'n' just the array length, too?

I would do

sum += curr.count 

to avoid the extra line.

1

u/MrMcRolan Oct 26 '26

The tricky thing about javascript is that it isn't type safe. You could theoretically get the "wrong" parameter type input but the code will still compile, only the return value may not be what you actually want.

Generally if you are expecting to return a certain type then you should check for it before returning.

1

u/CelebrityChess Oct 26 '26

for the follow up i'd say test the contract not the garbage. if the server promises non negative numbers then test things like empty array and a single item, zero counts, big sums. only add tests for negative or undefined if you decided the function should throw or skip those, because then that's behavior you're promising too. otherwise you end up locking in whatever it happens to do with bad input and it just makes refactoring annoying

1

u/Initial_Two_8239 Oct 26 '26

So what I have done would be I would validate the data as it comes to server rather than checking everything in the internal function. If you have already validated it at the server then you can generally trust it inside your application . And keep in mind of handling edge cases like null , undefined or any invalid data type .

1

u/dariusbiggs Oct 26 '26

Defensive programming is key. Do not trust any input, validate and verify everything, especially if it comes from outside. You can keep the validation and verification at the edge of your exposed surface, but you should have it there at a minimum.

1

u/quts3 Oct 26 '26

At this function. Nothing. The only thing you should check are inputs in the design for the function and that is for early exit.

Single responsibility principle applies.

You state what you expect and the caller agrees to work within that constraint.

1

u/StewedAngelSkins Oct 26 '26

in this case i would definitely not put a check because taking the average of a list involving negative numbers is a perfectly well defined operation. it's not really this function's job to enforce something like this, it's just responsible for averaging.

basically i tend to only enforce checks that the function itself depends on.

1

u/binarycow Oct 26 '26

Validate at the boundary between untrusted code and trusted code.

User input - always untrusted.

Database results - untrusted unless there is schema enforcement

External libraries - always untrusted.

A call from one function to another, in the same file? Probably trusted.

1

u/lurgi Oct 26 '26

In this particular case I'd say that the function works perfectly well with negative numbers, so why should it check to ensure all the numbers are positive?

That may sound like side-stepping the question, but I think it faces it head on. Check at the places that care. Don't check to see if the file is open because someone else cares about the file being open. Check to see if the file is open because you need the file to be open.

1

u/heisthedarchness Oct 27 '26

This function is doing at least two jobs already; adding input validation would definitely be out of scope.

There are three responsibilities here: validating the input, transforming each "curr" into a count, and averaging the elements.

Validating the input should be done at the same time as the input is read from the server. This assures that only valid data will ever be inside your system.

computeAverageCount, then, can assume that the counts are all valid and doesn't have to check the inputs again. In fact, it shouldn't, since the encodes information about how the numbers will be used in what should be a simple utility function.

1

u/Logical-Second-6781 Oct 27 '26
  1. Use a language with a type system
  2. Model concepts as types. Email, name, age etc.
  3. Construct types at the outermost layer and pass them into the system. Thus no need to validate anything when the types are proof you already did. Known as "Parse, don't validate" and is the opposite of "shotgun parsing"