function getMonthName(monthNumber) {
const date = new Date();
date.setMonth(monthNumber - 1);
return date.toLocaleString([], { month: 'long' });
}
function getMonthName(monthNumber) {
const date = new Date();
date.setMonth(monthNumber - 1);
return date.toLocaleString([], { month: 'long' });
}
The point is that this scenario exists in Js in the first place. It’s a completely unnecessary rake left around for people to step on. Also, the function isn’t side effecty since it doesn’t make implicit references outside its scope. The fact that the date is mutable is an internal concern there. You could just as easily do
function getMonthName(monthNumber) { const date = new Date(); date.setDate(1); date.setMonth(monthNumber - 1); return date.toLocaleString([], { month: 'long' }); }
The problem here isn’t with side effects, but with having to know that you want to set your date to first day to get the next month reliably.
The rake has nothing to do with JS (which I agree is cursed, but for its own reasons, not this).
You have called a function in a way that does not give a consistent value (
Date()
). Such functions are hardly the preserve of JavaScript. You’ve failed to adequately deal with the range of values produced, with code that tries to insist that the “31st February” can be a meaningful date in February. You should accept that this is your mistake and learn to (better) avoid side effects where possible.Edit responding to your edit:
The
Date()
function’s output varies according to something other than its input (and even the rest of your program). Using its output without accounting for that variation means that your function, as originally written, also gives inconsistent return values, varying according to something other than its input, because it does, in fact, reference something outside the function. If it did not, the results would only depend on themonthNumber
argument, and would always be consistent. I don’t know what you call that, but I view it as a side effect.As you have said, the rake is that months have different lengths, and you need to account for that. But that’s not one of JavaScript’s many issues.
The idea is to get the current data that will have the current year, month, day in it, and then to query this date for the previous month. A sane API would just throw an error when the date is out of range. A Js API will quitely give you nonsense instead. Again, side effects have absolutely nothing to do with anything here.
You’ve replied while I was editing, so see that regarding what I mean by side effects.
As far as throwing an error when you try to create “31st February”, this wouldn’t actually help much, since the error would still only occur on some days of the year, because your original code doesn’t account for the range of outputs from
Date()
when called without arguments.To perform correctly, your code needs to normalise the day of the month, or just create the date more explicitly to begin with, but this is a calendrical issue, not a JavaScript one.
Side effects are when your function has a reference to some state outside its scope and modifies that state. A function that produces different outputs when it’s called, such as getting a current time is not an example of a side effect. Again, the issue here is that Js tries to infer what to do with a bad input, a number outside acceptable range, instead of simply rejecting it.
My point isn’t that you can’t write a better function that’s less error prone, but the fact that Js allows such things to happen in the first place. It’s a very easily avoidable problem at the API level.
I was taught that side effects are not so one-sided, and that changing output in response to outside state (such as the date) is also a side effect, a side effect on the function, rather than a side effect of the function, but I’m happy to use other definitions so long as they’re commonly understood.
As I said before, though, even if JavaScript did throw an error as you’d prefer, it would still allow your function to have date-based problems. They’d be a bit noisier perhaps but no less present, and just as “well it’s worked fine so far”. And that’s because, as I keep saying, the real problem here is using a function with inconsistent output and not thoroughly dealing with the possibilities. An API change wouldn’t alter that. Most of the time it would still let you write bad code.
I also probably agree with you that errors are generally better than silence in response to bad input but, as someone else has said (more or less) it’s not always unreasonable to consider “31st [Month]” as 31 days after the end of [Previous Month]. Without throwing errors, this flexibility is possible. Perhaps the creators believed having to mutate the day-of-month first was an acceptable trade-off for that.
Right, my only point here is that it’s better to throw an error when encountering bad or ambiguous input than trying to infer what should happen. I think tha a lot of problems in Js come from it being too accommodating regarding input, and the just trying to figure out what you might’ve meant. In vast majority of cases, an input of this kind if an indication of an error in the program logic and it’s better to fail on such inputs than to accept them. If somebody passes a date that doesn’t make sense for a current month, it’s almost certainly because they have some logic error in their code. Accepting this date as a parameter simply results in creating a subtle bug in a program that the user likely won’t be aware of and that’s going to be difficult to find in testing.
I agree with you that errors are useful feedback for coders who don’t know the ins and outs of an API. And every programmer is in that group at some point. But the difficulty in identifying this particular bug doesn’t stem from the API decisions.
Whether
Date
s throw an error, or work with what they’re given, has no bearing on the subtlety of this bug. Either way, tests that don’t replaceDate
will fail to identify it most of the time, and tests that do, based on its use within the function, would be called wrong-headed by many.Either way, the bug only shows up at the end of months longer than the target month, and that infrequency has nothing to do with the peculiar design choices of the
Date
API. It stems exclusively from the evaluation ofDate()
called with no arguments returning different values at different times—behaviour you have not objected to, and which I’d expect to be considered entirely appropriate, in fact its very point—combined with an attempt to use that value, whatever it may be, without due consideration.Since the month is the only part of interest, there’s no reason to allow the other parts to vary at all. Fixing them, as I suggested at the beginning of all this, is the simplest approach, but setting them first, as has also been suggested, would work too.
You can once again complain about JS design decisions and I’ll agree about many of them, but, as much as you might like it to be, and as annoying as so many of us think they often are, here it is beside the point. The perniciousness of this particular bug stems from unnecessarily calling a function with inconsistent output and then improperly processing that, instead of using a function call with always-predictable output.
I’ve tried to point that out in all the ways I can think of, so if it’s still not getting through, I give up. And if your acknowledgement was too subtle for my sleepy brain, and I’ve ended up overexplaining, then I’m sorry.
The difference is that hrowing an error makes it much easier to find the bug early, while doing the wrong thing silently makes it much harder to do so. If an error is thrown by the API then the first time wrong input is supply the application will fail and you’ll know you have a problem. If the API silently does the wrong thing, then the application will keep doing the wrong thing until somebody notices and that tends to be far more costly.
Finally, I’d like to note that this isn’t a hypothetical debate. This is how APIs work in sane languages such as Java:
java.time.LocalDate.of(2023, 2, 31) > java.time.DateTimeException: Invalid date 'FEBRUARY 31' java.time.LocalDate.of(2023, 2, 3) > #object[java.time.LocalDate 0x2bc77260 "2023-02-03"]