In the following code:
public class MovieRepository : IMovieRepository
{
private readonly IHtmlDownloader _downloader;
public MovieRepository(IHtmlDownloader downloader)
{
_downloader = downloader;
}
public Movie FindMovieById(string id)
{
var idUri = ...build URI...;
var html = _downloader.DownloadHtml(idUri);
return ...parse ID HTML...;
}
public Movie FindMovieByTitle(string title)
{
var titleUri = ...build URI...;
var htm开发者_如何学编程l = _downloader.DownloadHtml(titleUri);
return ...parse title HTML...;
}
}
I asked for something to review my code, and someone suggested this approach. My question is why is the IHtmlDownloader variable readonly?
If it's private and readonly
, the benefit is that you can't inadvertently change it from another part of that class after it is initialized. The readonly
modifier ensures the field can only be given a value during its initialization or in its class constructor.
If something functionally should not change after initialization, it's always good practice to use available language constructs to enforce that.
On a related note, C# 9 introduces the init
accessor method for properties, which indicates the property value can only be set during object construction, e.g.:
class InitExample
{
private double _seconds;
public double Seconds
{
get { return _seconds; }
init { _seconds = value; }
}
}
This ensures that the value of _downloader
will not be changed after the constructor was executed. Fields marked as readonly
can only be assigned a value from within the constructor(s) of a class.
A readonly field is useful for modelling data that should not change after it has been initialized. You can assign a value to a readonly field by using a initializer when you declare it or in a constructor, but thereafter you cannot change it.
精彩评论