Hello any way to improve the equality between checkpoints in this class?
data class Tracking(
val id: TrackingId,
val parcelId: TrackingParcelId,
val trackingPlatform: TrackingPlatform,
val genericTrackingMethod: GenericTrackingMethod,
val orderReference: OrderReference,
val orderId: OrderId,
var status: Status,
private val config: MutableMap<String, Any?>,
val checkpoints: List,
val createdAt: OffsetDateTime,
val updatedAt: OffsetDateTime,
val shipmentId: Int?,
val externalId: ExternalTrackingId?,
val trackingNumber: TrackingNumber?,
val trackingUrl: TrackingUrl?,
val orderValidatedAt: OffsetDateTime?,
val carrierOfferId: Int?,
val legacyTrackingId: Int?,
var notTrackableReason: TrackingNotTrackableReason?,
) {
@JvmInline
value class TrackingId(val value: Int)
code
Assistant
@JvmInline
value class TrackingParcelId(val value: String)
@JvmInline
value class ExternalTrackingId(val value: String)
enum class Status {
PENDING_DATA,
IN_PROGRESS,
TERMINATED,
EXPIRED,
;
fun isFinalStatus(): Boolean = this == TERMINATED || this == EXPIRED
}
enum class TrackingNotTrackableReason {
EMPTY_TRACKING_NUMBER,
OFFER_NOT_NORMALIZED,
MISSING_CONFIGURATION,
UNAUTHORIZED,
FORBIDDEN,
NOT_FOUND,
TOO_MANY_REQUESTS,
INTERNAL_SERVER_ERROR,
INVALID_JSON,
TRACKING_ALREADY_EXISTS,
TRACKING_DOES_NOT_EXISTS,
INVALID_TRACKING_NUMBER,
TRACKING_OBJECT_REQUIRED,
TRACKING_NUMBER_REQUIRED,
INVALID_FIELD_VALUE,
MISSING_FIELD,
INVALID_SLUG,
INVALID_REQUIRED_FIELD,
INVALID_TRACKING_NUMBER_FORMAT,
UNKNOWN_ERROR,
}
fun isActive(): Boolean {
return !status.isFinalStatus()
}
fun incidents(): List<Checkpoint> = checkpoints.filter(Checkpoint::isIncident)
fun hasIncident(): Boolean = incidents().isNotEmpty()
fun customerHasToContactCarrier(): Boolean = checkpoints.any { it.type == Checkpoint.Type.WRONG_ADDRESS || it.type == Checkpoint.Type.FAILED_DELIVERY_ATTEMPT }
fun isTraced(): Boolean =
notTrackableReason == null && trackingPlatform != TrackingPlatform.NONE && status != Status.PENDING_DATA && !(status == Status.EXPIRED && checkpoints.size == 1)
fun isIncidentSolved(): Boolean = !hasIncident() || !isLastPassedCheckpointInIncident()
fun lastPassedCheckpoint(): Checkpoint? = checkpoints.lastOrNull()
fun isLastPassedCheckpointInIncident(): Boolean = lastPassedCheckpoint()?.isIncident() ?: false
fun expire() {
if (status.isFinalStatus()) {
throw LogicException("Tracking is already in a final state")
}
status = Status.EXPIRED
}
fun terminate() {
if (status.isFinalStatus()) {
throw LogicException("Tracking is already in a final state")
}
status = Status.TERMINATED
}
fun updateDetectedSlug(slug: String) {
config["detected_slug"] = slug
}
fun slugDiffers(slug: String): Boolean = slug != config["slug"]
fun cannotBeTracked(reason: TrackingNotTrackableReason) {
notTrackableReason = reason
terminate()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Tracking
if (id != other.id) return false
if (parcelId != other.parcelId) return false
if (trackingPlatform != other.trackingPlatform) return false
if (genericTrackingMethod != other.genericTrackingMethod) return false
if (orderReference != other.orderReference) return false
if (orderId != other.orderId) return false
if (status != other.status) return false
if (config != other.config) return false
if (checkpoints.filterIndexed { index, checkpoint -> other.checkpoints.getOrNull(index) != checkpoint }.isNotEmpty()) return false
if (createdAt != other.createdAt) return false
if (updatedAt != other.updatedAt) return false
if (shipmentId != other.shipmentId) return false
if (externalId != other.externalId) return false
if (trackingNumber != other.trackingNumber) return false
if (trackingUrl != other.trackingUrl) return false
if (orderValidatedAt != other.orderValidatedAt) return false
if (carrierOfferId != other.carrierOfferId) return false
if (legacyTrackingId != other.legacyTrackingId) return false
if (notTrackableReason != other.notTrackableReason) return false
return true
}
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + parcelId.hashCode()
result = 31 * result + trackingPlatform.hashCode()
result = 31 * result + genericTrackingMethod.hashCode()
result = 31 * result + orderReference.hashCode()
result = 31 * result + orderId.hashCode()
result = 31 * result + status.hashCode()
result = 31 * result + config.hashCode()
result = 31 * result + checkpoints.hashCode()
result = 31 * result + createdAt.hashCode()
result = 31 * result + updatedAt.hashCode()
result = 31 * result + (shipmentId ?: 0)
result = 31 * result + (externalId?.hashCode() ?: 0)
result = 31 * result + (trackingNumber?.hashCode() ?: 0)
result = 31 * result + (trackingUrl?.hashCode() ?: 0)
result = 31 * result + (orderValidatedAt?.hashCode() ?: 0)
result = 31 * result + (carrierOfferId ?: 0)
result = 31 * result + (legacyTrackingId ?: 0)
result = 31 * result + (notTrackableReason?.hashCode() ?: 0)
return result
}
fun orderSentAt(): OffsetDateTime? = checkpoints.find { it.type == Checkpoint.Type.COLLECTED_BY_CARRIER }?.occurredAt()
fun orderInDistributionAt(): OffsetDateTime? = checkpoints.find { it.type in listOf(Type.OUT_FOR_DELIVERY, Type.CUSTOMER_CONTACTED) }?.occurredAt()
fun orderInRelayPointAt(): OffsetDateTime? = checkpoints.find { it.type == Type.AVAILABLE_FOR_PICKUP }?.occurredAt()
fun orderDeliveredAt(): OffsetDateTime? = checkpoints.find { it.type == Type.DELIVERED }?.occurredAt()
}
data class Checkpoint(
val id: CheckpointId,
val trackingId: TrackingId,
val type: Type,
private val occurredAt: OffsetDateTime,
val message: String?,
val rawData: Map<String, Any?>,
val timezone: String = occurredAt.offset.toString(),
val createdAt: OffsetDateTime = OffsetDateTime.now(ZoneOffset.UTC),
) {
@JvmInline
value class CheckpointId(val value: Int)
code
enum class Type {
UNKNOWN,
INFO_PENDING,
INFO_RECEIVED,
COLLECTED_BY_CARRIER,
IN_TRANSIT,
FORWARDED_TO_NEW_ADDRESS,
PARCEL_AT_HUB,
OUT_FOR_DELIVERY,
AVAILABLE_FOR_PICKUP,
DELIVERED,
EXPIRED_TRACKING,
CUSTOMER_CONTACTED,
BUSINESS_CLOSED,
FAILED_DELIVERY_ATTEMPT,
DELAYED,
DELAYED_BY_CUSTOMS,
LOGISTICS_ERROR,
CUSTOMER_ATTENTION_REQUIRED,
WRONG_ADDRESS,
PARCEL_DELIVERY_REFUSED,
PAYMENT_PENDING,
PICK_UP_MISSED,
REJECTED_BY_CARRIER,
PARCEL_RETURNING_TO_SENDER,
PARCEL_RETURNED_TO_SENDER,
PARCEL_DAMAGED,
PARCEL_LOST,
;
companion object {
private val INCIDENT_TYPES =
listOf(
LOGISTICS_ERROR,
FAILED_DELIVERY_ATTEMPT,
PARCEL_DELIVERY_REFUSED,
DELAYED_BY_CUSTOMS,
DELAYED,
PAYMENT_PENDING,
WRONG_ADDRESS,
PICK_UP_MISSED,
REJECTED_BY_CARRIER,
PARCEL_RETURNING_TO_SENDER,
PARCEL_RETURNED_TO_SENDER,
PARCEL_DAMAGED,
PARCEL_LOST,
)
}
fun isIncident(): Boolean = this in INCIDENT_TYPES
}
init {
require(rawData.isNotEmpty()) { "rawData must not be empty" }
}
fun isIncident(): Boolean = type.isIncident()
fun occurredAt(): OffsetDateTime = occurredAt.withOffsetSameInstant(ZoneOffset.of(timezone))
}
Yes, you can improve the equality comparison for the checkpoints list in your Tracking class to make it more efficient, readable, and idiomatic. Here's how you can achieve that:
1. Leverage Kotlin's Built-in List Equality
Kotlin's List class implements structural equality out of the box, meaning that two lists are considered equal if they have the same size and all corresponding elements are equal. Instead of manually filtering and comparing each checkpoint, you can utilize this feature directly.
if (checkpoints != other.checkpoints) return false
Explanation:
The != operator checks for structural equality between the two lists.
It's more concise and leverages Kotlin's optimized list comparison.
2. Simplify the equals Method
If the primary customization in your equals method is handling the checkpoints comparison, simplifying it as shown above can make the method cleaner. However, considering that you have mutable properties (var status and var notTrackableReason) and private fields (private val config), retaining a custom equals and hashCode might still be necessary to accurately capture the state of the object.
3. Consider Immutability for Data Classes
Data classes in Kotlin are best suited for immutable data. Since you have mutable properties, it's essential to handle equals and hashCode carefully to maintain consistency. If possible, you might consider:
Making Properties Immutable: Change var properties to val where possible.
Separating Mutable State: Keep mutable state outside the data class or manage it in a way that doesn't interfere with equality checks.
4. Full Revised equals Method Example
Here's how your equals method might look after incorporating the improvement:
kotlin
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Tracking
if (id != other.id) return false
if (parcelId != other.parcelId) return false
if (trackingPlatform != other.trackingPlatform) return false
if (genericTrackingMethod != other.genericTrackingMethod) return false
if (orderReference != other.orderReference) return false
if (orderId != other.orderId) return false
if (status != other.status) return false
if (config != other.config) return false
if (checkpoints != other.checkpoints) return false // Simplified comparison
if (createdAt != other.createdAt) return false
if (updatedAt != other.updatedAt) return false
if (shipmentId != other.shipmentId) return false
if (externalId != other.externalId) return false
if (trackingNumber != other.trackingNumber) return false
if (trackingUrl != other.trackingUrl) return false
if (orderValidatedAt != other.orderValidatedAt) return false
if (carrierOfferId != other.carrierOfferId) return false
if (legacyTrackingId != other.legacyTrackingId) return false
if (notTrackableReason != other.notTrackableReason) return false
return true
}
5. Rethink Data Class Necessity
If Tracking doesn't fit well with the concept of a data class due to its mutable properties and custom logic, you might consider using a regular class instead. This way, you can have more control over the equals and hashCode implementations without being constrained by the data class's default behavior.
6. Additional Recommendations
Use copy for Modifications: If you still want to leverage some benefits of data classes, consider using the copy method to create modified instances rather than mutating existing ones.
Document Equality Semantics: Clearly document how equality is determined, especially if certain fields are excluded or handled uniquely.
Test Thoroughly: Ensure that your equals and hashCode implementations are thoroughly tested to prevent subtle bugs, especially when mutable properties are involved.
By simplifying the checkpoints comparison and considering the overall design of your Tracking class, you can make your codebase more maintainable and efficient.