2017-12-08 33 views
1

블로그 작성에 대한 지침을 따르고 있으며 엉망으로 보이는 코드를 어떻게 리펙토링 할 수 있는지 궁금합니다. 특히 태그에서 파싱하는 동안 many-to-many 관계. 이것을 컨트롤러의 더 작은 기능으로 축소하는 더 좋은 방법이 있습니까?다 대다 관계가 포함 된 컨트롤러 리 팩터링

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