When you're coding, you might run into situations that your program doesn't handle well. These are called "edge cases".
Here's how you can correct your code when you encounter one:
Imagine you have a blog app where users can create posts. You want to display the most recent post's title on the homepage. Your initial code might look like this:
class HomeController < ApplicationController
def index
@latest_post_title = Post.order(created_at: :desc).first.title
end
end
This works fine as long as there's at least one post. But what if there are no posts yet? This is an edge case that will cause an error.
To fix it, you could modify the code like this:
class HomeController < ApplicationController
def index
@latest_post_title = Post.order(created_at: :desc).first&.title || "No posts yet"
end
end
Now, if there are no posts, instead of crashing, your app will display "No posts yet" on the homepage.
Without edge case handling:
def divide(numerator, denominator)
numerator / denominator
end
Issue: This will raise a ZeroDivisionError if denominator is zero.
With edge case handling:
def safe_divide(numerator, denominator)
return 0 if denominator.zero?
numerator / denominator
end
Solution: We check if the denominator is zero before performing the division, returning 0 in that case.
Without edge case handling:
def get_page_number(params)
params[:page].to_i
end
Issue: This could return 0 or negative numbers, which aren't valid page numbers.
With edge case handling:
def get_page_number(params)
page = params[:page].to_i
page.positive? ? page : 1
end
Without edge case handling:
def date_range_filter(start_date, end_date)
start_date..end_date
end
Issue: This doesn't handle nil inputs or ensure start_date is before end_date.
With edge case handling:
def date_range_filter(start_date, end_date)
start_date = start_date.presence || 30.days.ago.to_date
end_date = end_date.presence || Date.today
[start_date, end_date].min..[start_date, end_date].max
end
Solution: We provide default values for nil inputs and ensure the range is always from the earlier date to the later date.