You should hard code the idea, not the value

time to read 3 min | 456 words

I am reading NServiceBus' code at the moment, and I run into this idea:

[Serializable]
[Recoverable]
[TimeToBeReceived(“0:01:00.000")]
public class ScheduleInterviewMessage : IMessage
{
    public Guid InterviewerId;
    public Guid CandidateId;
    public DateTime RequestedTime;
}

I don't like hard coding this value in the message. Obviously this is something that is tied very closed to the idea of the message. Time to live is certainly something that I would want to closely tie to the message itself. But hard coding the value goes against a lot of instincts.

A while ago I faced a similar issue, in that case, it was scheduling tasks. The timing of the task was tied to what it did. The last example that I had on that post is this:

[Occurances(OccureEvery.Day, At = "08:00", RunAtHolidays = false)]
public class SendSmsTwoDaysBeforeEventStart : ScheduledTask

Notice the At = "08:00" ? It bothered me for a while, until I came to the conclusion that I was embedding the wrong piece of information in the code.

I didn't want this to run at 08:00, I want it to run in the morning. 08:00 was just a handy designation for that. That thought was quickly followed by:

public enum ScheduledTimes
{
     Midnight,
     EarlyMorning,
     Morning,
     Noon,
     Afternoon,
     Evening    
}

And the code turned to:

[Occurances(OccureEvery.Day, At = ScheduledTimes.Morning, RunAtHolidays = false)]
public class SendSmsTwoDaysBeforeEventStart : ScheduledTask

The difference here is that I no longer hard code a specific value, I put the idea there. During deployment, I could have modified what morning meant, very easily.

Using the same approach, I would define something like:

public enum TimeToLive
{
    Immediate,
    Short,
    Medium,
    Long,
    Forever
}

I would probably allow to configure the time that each of those values map to, as well.

This allows to do things like update them on the fly (imagine having to survive a burst of traffic that slows the entire system), so you can increase the time to process a message without losing it.