Coding Quality of life improvements

February 1, 2023
dev tips

We code all day. We do the same thing, every day. Why not make some Quality of Life improvements to your coding life. Here's an example.

If you code daily (or whatever you do) there are probably things that you do multiple times a week, day….an hour. I know that there are paradigms for given apps or clients where it's always the same thing.

Well, make sure that you make that experience the best you can. This isn't a “go buy the best chair” type post. This is code. A really good example, for me, to show you, that I do, that you might, is dates in websites especially around reporting.

I code a lot of reports. A lot. So many. And all reports need dates. 

All my reports (with one minor exception) have 

public DateTime StartDate {get;set;}
public DateTime EndDate {get;set;}

More commonly, though, we get it from the query string (Razor, Blazor):

[FromQuery]
public DateTime StartDate {get;set;}
[FromQuery]
public DateTime EndDate {get;set;}

There are some versions, though less likely, though perhaps semantically and technically better, which is the use of DateTime? since the value can be null. But:

I moved away from using DateTime? because I am then required ot use GetDefaultOrValue() (because it's more performant than .Value) and I will ALWAYS have to set a value so even if it is null it won't stay that way. So, I got away from it.

If I do this on EVERY. SINGLE. PAGE. Why not make my life easier? With this:

[FromQuery]
public DateRange Dates {get;set;}

Which is 

public class DateRange
{
   public DateTime StartDate {get;set;}
   public DateTime EndDate {get;set;}
   
        public void SetDefaultsAsMtd()
        {
            if (StartDate == DateTime.MinValue)
            {
                StartDate = DateTime.Today.StartOfMonth();
            }

            if (EndDate == DateTime.MinValue || EndDate.Date < StartDate.Date)
            {
                EndDate = StartDate.EndOfMonth();
            }
        }
        
        public void SetDefaults(DateTime startDate, DateTime endDate)
        {
            if (StartDate == DateTime.MinValue)
            {
                StartDate = startDate;
            }

            if (EndDate == DateTime.MinValue || EndDate.Date < StartDate.Date)
            {
                EndDate = endDate;
            }
        }    
                
        public override string ToString()
        {
            return $"{StartDate:g} - {EndDate:g}"
  
        }    
}

As you can see, I can replace a lot of boiler plate, copy pasta code with a minor change. Which could be furthered minimized with a page base class.

Summary

Ultimately, this wasn't about using this example in your code. Though you could if you wanted to. It's about recognizing your own patterns in your coding habits and determine if YOU have an opportunity, stranger, to improve your workflow and allow you to focus on the good stuff, not the menial work.