Why is the Java date API (java.util.Date, .Calendar) such a mess?

前端 未结 4 1191
南笙
南笙 2020-11-21 21:58

As most people are painfully aware of by now, the Java API for handling calendar dates (specifically the classes java.util.Date and java.util.Calendar

4条回答
  •  鱼传尺愫
    2020-11-21 22:54

    Someone put it better than I could ever say it:

    • Class Date represents a specific instant in time, with millisecond precision. The design of this class is a very bad joke - a sobering example of how even good programmers screw up. Most of the methods in Date are now deprecated, replaced by methods in the classes below.
    • Class Calendar is an abstract class for converting between a Date object and a set of integer fields such as year, month, day, and hour.

    • Class GregorianCalendar is the only subclass of Calendar in the JDK. It does the Date-to-fields conversions for the calendar system in common use. Sun licensed this overengineered junk from Taligent - a sobering example of how average programmers screw up.

    from Java Programmers FAQ, version from 07.X.1998, by Peter van der Linden - this part was removed from later versions though.

    As for mutability, a lot of the early JDK classes suffer from it (Point, Rectangle, Dimension, ...). Misdirected optimizations, I've heard some say.

    The idea is that you want to be able to reuse objects (o.getPosition().x += 5) rather than creating copies (o.setPosition(o.getPosition().add(5, 0))) as you have to do with immutables. This may even have been a good idea with the early VMs, while it's most likely isn't with modern VMs.

提交回复
热议问题