2017-12-08 29 views
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 }; 
} 

答えて

1

、あなたは、解析のために、すべての動作をカプセル化し、クラス内のタグを検索することができ、多分このような何か:

public class Tags 
{ 
    private readonly IEnumerable<Tag> contextTags; 
    private readonly string rawTags; 

    public Tags(string tags, IEnumerable<Tag> contextTags) 
    { 
     this.rawTags = tags ?? string.Empty; 
     this.contextTags = contextTags; 
    } 

    public IEnumerable<Tag> ToList() 
    { 
     List<Tag> tags = new List<Tag>(); 

     string[] tagNames = this.rawTags.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); 

     foreach (string tagName in tagNames) 
     { 
      tags.Add(this.GetTag(tagName)); 
     } 

     return tags; 
    } 

    private Tag GetTag(string tagName) 
    { 
     return this.contextTags.FirstOrDefault(x => x.Name == tagName) ?? new Tag { Name = tagName }; 
    } 
} 

その後に作成する方法コントローラは次のようになります。

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(); 

    Tags tagsList = new Tags(tags, this._context.Tags); 

    post.Tags = tagsList.ToList(); 
} 
+0

これは絶対に美しいです。ありがとう! – AllocSystems

関連する問題