テキストをダウンロードして読み取るドキュメントクラスを作成しました。スマートなことは、ドキュメント内のテキストを必要な場合にのみダウンロードして読み取ることです。Text プロパティを使用して、ドキュメントを読み取ろうとします。ダウンロードされていない場合は、ダウンロードしてから読み取ります。
それは非常にうれしいです。ただし、例外を使用すると、ファンキーなコードになることに気付きました。下記参照。
ドキュメント クラス
public delegate byte[] DownloadBinaryDelegate(IDocument document);
public delegate string TextReaderDelegate(IDocument document);
public class Document
{
public DownloadBinaryDelegate DownloadBinaryDelegate { private get; set; }
public TextReaderDelegate TextReaderDelegate { private get; set; }
private bool _binaryIsSet;
private byte[] _binary;
public byte[] Binary
{
get
{
if (_binaryIsSet)
return _binary;
if (DownloadBinaryDelegate == null)
throw new NullReferenceException("No delegate attached to DownloadBinaryDelegate.");
Binary = DownloadBinaryDelegate(this);
DownloadBinaryDelegate = null; // unhock delegate as it's no longer needed.
return _binary;
}
set
{
if (_binaryIsSet)
return;
_binary = value;
_binaryIsSet = true;
}
}
private bool _textIsSet;
private string _text;
public string Text
{
get
{
if (_textIsSet)
return _text;
if (TextReaderDelegate == null)
throw new NullReferenceException("No delegate attached to TextReaderDelegate.");
Text = TextReaderDelegate(this); // this delegate will call Binary and return the translated text.
TextReaderDelegate = null; // unhock delegate as it's no longer needed.
return _text;
}
set
{
if (_textIsSet)
return;
_text = value;
_textIsSet = true;
}
}
問題
最初に書いたこと。
if (document.Text == null) // text is not set
{
if (document.Binary == null) // binary has not been downloaded
document.DownloadBinaryDelegate = Util.DownloadDocument;
document.TextReaderDelegate = Util.ReadDocument;
}
Text プロパティが例外をスローすることを完全に忘れています。だから私はこのようなものを書かなければなりませんが、これはちょっと変わったコードです。
// check if text has already been read and set
try
{
var isTextSet = document.Text == null;
}
catch (NullReferenceException)
{
document.DownloadBinaryDelegate = Util.DownloadDocument;
document.TextReaderDelegate = Util.ReadDocument;
}
私の言いたいことがわかると思います。
私の質問は、これは悪い設計ですか? どうやってそれをしたでしょうか?私はまだ現在の機能が欲しいことを心に留めておいてください。