Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Carbon is a similar class in the PHP world that's inherited from DateTime. This gives a good description of how working with mutable timestamps can cause problems, because methods like $newInstance = $instance->addDay() modify the original instance and return it, rather than returning a copy that's a day later:

https://carbon.nesbot.com/docs/

So it's best to mostly use CarbonImmutable so that a new instance is always returned, which works better for higher-order programming style that's closer to pure functional programming. I do wish that Carbon was immutable by default, with CarbonMutable as a fallback when necessary, but it's too late for them to change it now.

I could see a project using use..as statements and/or aliases in config/app.php (edit: in Laravel) to import CarbonImmutable and Carbon as aliases like CRBN and CRBNMUT respectively, so that code works as intended without monkey patching or otherwise swapping the classnames and losing code portability.



> I could see a project using use..as statements and/or aliases in config/app.php (edit: in Laravel) to import CarbonImmutable and Carbon as aliases

This wouldn't work the way you're hoping for. use statements are file-scoped; a use statement in config/app.php would only affect that configuration file, not the entire application.


Oh I was thinking of adding the custom CRBN or Carb or whatever as class aliases to the original CarbonImmutable class in config/app.php. I actually haven't used aliases yet though, so I'm going by the assumption that they "just work".

I've had problems in other projects too where I wanted to disallow use of classes like Carbon after declaring a child class that overrides certain behaviors, so that the code is more future-proof for newly onboarded developers who don't know the pitfalls yet. In C/C++ I would just do:

  #define Carbon "Please don't use Carbon, use CRBN or CRBNMUT instead."
So attempts to use Carbon would show up as compiler errors. But there are no #defines in PHP, so I haven't figured out a way to do that yet :-/ Maybe I could declare Carbon as a constant somewhere or something. But I don't think there's a way to undefine constants for times when the original word is needed, like with #undef.


Honestly, the best way of going about this would probably be a static analysis rule. Enforcing "use CarbonImmutable, not Carbon" doesn't need to happen at runtime.


This has bitten me a couple times too but it's usually easy to figure out the first time you botch it and you're more careful after that.

Immutability is double edged. If I'm doing a bunch of math on a date, I don't want to be creating a dozen copies either.

SQL query builders also have this problem.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: