Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

16
  • 3
    Yeah I think these other answers have missed the point, "Don't throw in constructors" isn't really avoided by returning null or throwing in a factory. You have just dodged the rule. Commented Apr 19, 2024 at 16:18
  • 1
    It might not be a good idea to introduce additional complexity to your class for the sake of not throwing or otherwise rejecting behaviour that isn't really needed. Let's say 99% of people are going to use this class with date1 <= date2, and you have a bug that only occurs when date2 > date1 - how long until such a bug gets caught when it's likely that even maintainers of Foo are going to forget you can provide the dates backwards? What if such a bug is an exploitable vulnerability? Commented Apr 19, 2024 at 18:26
  • 2
    Would it not be simpler to have the constructor simply swap the dates if they're in the wrong order? e.g. this.startDate = DateUtils.min(date1, date2); this.endDate = DateUtils.max(date1, date2); Then you don't have to override Equals() or provide those getStartDate(), and getEndDate() functions, since every object will have the dates in the correct order. Commented Apr 19, 2024 at 18:34
  • 1
    Ewan, throwing in a constructor is tricky. You’ll have to consult the C++ standard to do it safely and it is always tricky. I don’t like tricky things. Commented Apr 19, 2024 at 19:35
  • 2
    @MaciejStachowski I think you have an incorrect impression here. If you define the class such that instead of passing in min and max dates, you just pass two dates and the smallest one is assigned to the min, then your not "over stuffing" you class with logic, youve just provided a constructor that cant fail. Commented Apr 21, 2024 at 12:07