1
ブログを作成する際のチュートリアルに従っていますが、混乱しているコードのいくつかをどのようにリファクタリングすることができますか?具体的には、タグを解析する際に多対多の関係になります。これをコントローラ上の小さな機能に減らすためのよりよい方法はありますか?むしろ、コントローラに新しいメソッドを作成するよりも多対多の関係を持つコントローラをリファクタリングする
public ActionResult Create(int? id, string title, string body, DateTime datetime, string tags)
{
Post post = GetPost(id);
post.Title = title;
post.Body = body;
post.Tags.Clear();
// I'D Like to refactor this point on to look something like this: ParseTags(tags);
rather than this
tags = tags ?? string.Empty;
string[] tagNames = tags.Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries);
foreach(string tagName in tagNames)
{
post.Tags.Add(GetTag(tagNames));
}
}
private Tag GetTag(string tagName)
{
return _context.Tags.Where(x => x.Name == tagName).FirstOrDefault() ??
new Tag() { Name = tagName };
}
これは絶対に美しいです。ありがとう! – AllocSystems