When creating a new Blazor project, there is a page called FetchData which gives an example of a razor page using a service to pull data to a page.
I set myself a challenge to improve on the service, so that instead of a random label being assigned to a temperature for a forecast, it separates the label categories evenly across the range of temperatures.
Here is the original code for the service:
namespace MyBlazorApp.Data { public class WeatherForecastService { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; public Task<WeatherForecast[]> GetForecastAsync(DateTime startDate) { return Task.FromResult(Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = startDate.AddDays(index), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }).ToArray()); } } }
And here is my new code:
namespace MyBlazorApp.Data
{
public class WeatherForecastService
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
public Task<WeatherForecast[]> GetForecastAsync(DateTime startDate)
{
var minTemp = -10;
var maxTemp = 40;
return Task.FromResult(Enumerable.Range(0, 14).Select(index => getWeatherForecast(startDate, minTemp, maxTemp, index)).ToArray());
}
public WeatherForecast getWeatherForecast(DateTime startDate, int minTemp, int maxTemp, int index)
{
maxTemp += (maxTemp - minTemp) % Summaries.Length;
var rng = Random.Shared.Next(minTemp, maxTemp);
var categorySize = (maxTemp - minTemp) / (Summaries.Length);
var pointer = (rng + (0 - minTemp)) / categorySize;
if (pointer >= Summaries.Length)
{
pointer = Summaries.Length - 1;
}
return new WeatherForecast
{
Date = startDate.AddDays(index),
TemperatureC = rng,
Summary = Summaries[pointer]
};
}
}
}
The code seems to work fine, but I feel that the error handling as well as the code optimization, readability and simplicity can be improved. Any tips on how I can look to find these improvements myself would also be extremely helpful. I changed some of the numbers to feel more appropriate to the context, but ideally the solution should work no matter what variables are set.
In summary, I am trying to find a solution to the problem in the absolute best way possible, as a way of giving an example of what perfect code looks like.