averbraeck / opentrafficsim

Open Source Multi-Level Traffic Simulator
BSD 3-Clause "New" or "Revised" License
28 stars 8 forks source link

Implement records where suitable #114

Closed WJSchakel closed 4 months ago

WJSchakel commented 4 months ago

With the use of java 17 we can now use records to simplify and reduce our code in various places.

WJSchakel commented 4 months ago

The following classes were transformed to a record:

org.opentrafficsim.road.network.RoadNetwork.LaneChangeInfoEdge org.opentrafficsim.base.TimeStampedObject org.opentrafficsim.core.gtu.RelativePosition org.opentrafficsim.core.gtu.plan.operational.Segment org.opentrafficsim.core.network.LinkPosition org.opentrafficsim.draw.graphs.GraphPath.Section org.opentrafficsim.editor.XsdOption org.opentrafficsim.kpi.sampling.SpaceTimeRegion org.opentrafficsim.road.network.factory.xml.parser.ScenarioParser.ParameterWrapper org.opentrafficsim.road.network.factory.xml.utils.RoadLayoutOffsets.OffsetElement org.opentrafficsim.road.gtu.generator.headway.DemandPattern org.opentrafficsim.road.gtu.lane.perception.categories.neighbors.NeighborTriplet org.opentrafficsim.road.gtu.lane.tactical.LanePathInfo org.opentrafficsim.road.gtu.lane.tactical.NextSplitInfo org.opentrafficsim.road.gtu.lane.tactical.util.AnticipationInfo org.opentrafficsim.road.gtu.lane.tactical.util.lmrs.Desire org.opentrafficsim.road.network.LaneChangeInfo org.opentrafficsim.road.network.lane.LanePosition org.opentrafficsim.road.network.lane.conflict.ConflictBuilderRecordSmall org.opentrafficsim.road.network.lane.conflict.ConflictBuilderRecordBig org.opentrafficsim.road.network.speed.SpeedInfoCurvature org.opentrafficsim.road.od.OdApplier.GeneratorObjects

Note that records are final and cannot be extended. Therefore certain classes that appear suitable to be a record, were not changed.

An interesting feature is the compact constructor in which only input checks can be performed. For example in record SpaceTimeRegion:

    public SpaceTimeRegion
    {
        Throw.whenNull(startPosition, "Start position may not be null.");
        Throw.whenNull(endPosition, "End position may not be null.");
        Throw.whenNull(startTime, "Start time may not be null.");
        Throw.whenNull(endTime, "End time may not be null.");
        Throw.when(endPosition.lt(startPosition), IllegalArgumentException.class,
                "End position should be greater than start position.");
        Throw.when(endTime.lt(startTime), IllegalArgumentException.class, "End time should be greater than start time.");
    }