2016-09-28 1 views
3

프로젝트를 진행하면서 중복 된 코드가 많다는 것을 알고 있으므로 중복 된 코드를 단일 메서드로 통합하고 싶습니다.사소한 차이가있는 중복 루프 방지

foreach (var glider in gliders) 
{ 
    List<PriceDataModel_New> bestPrices = PriceService.GetBestPrices(prices, glider.Value.No, string.Empty, string.Empty, string.Empty, 1); 
    var priceGroups = bestPrices.GroupBy(p => p.SalesCode); 
    var salesCodePrice = priceGroups.ToDictionary(k => k.Key, v => v.First()); 
    AddEmptyines(fieldMapping, lines); 
    var last = lines.Last(); 

    foreach (var keyValuePair in fieldMapping.Postions) 
    { 
     int index = keyValuePair.Key; 
     var key = keyValuePair.Value.InternalHeading; 
     InsertInLines(last, key, index, "CODE_Id", modelNo + "_" + glider.Value.No); 
     InsertInLines(last, key, index, "ItemId", glider.Value.No); 
     InsertInLines(last, key, index, "CODE_OptionalName", (glider.Value.ComponentType + " " + glider.Value.ProductFamily).ToLower()); 
     InsertInLines(last, key, index, "Attr_Family name", family); 
     InsertInLines(last, key, index, "CODE_IsOptional", "true"); 
     InsertInLines(last, key, index, "Model", modelNo); 
     InsertInLines(last, key, index, "CODE_OptionalInfo", glider.Value.Size.ToLower()); 

     if (AddToLinePrice(salesCodePrice, keyValuePair.Value.InternalHeading, index, last)) 
      continue; 
    } 
} 

     //AppendLines(seatPads, prices, lines, fieldMapping, "", modelNo, family, "linking.Value.SimpleMaterial", ""); 

foreach (var seatPad in seatPads) 
{ 
    List<PriceDataModel_New> bestPrices = PriceService.GetBestPrices(prices, seatPad.Value.No, seatPad.Value.Variant.Substring(0, 3), string.Empty, string.Empty, 1); 
    var priceGroups = bestPrices.GroupBy(p => p.SalesCode); 
    var salesCodePrice = priceGroups.ToDictionary(k => k.Key, v => v.First()); 
    AddEmptyines(fieldMapping, lines); 
    var last = lines.Last(); 

    foreach (var keyValuePair in fieldMapping.Postions) 
    { 
     int index = keyValuePair.Key; 
     var key = keyValuePair.Value.InternalHeading; 
     InsertInLines(last, key, index, "CODE_Id", modelNo + "_" + seatPad.Value.No); 
     InsertInLines(last, key, index, "ItemId", seatPad.Value.No); 
     InsertInLines(last, key, index, "CODE_OptionalName", seatPad.Value.ModelNo.ToLower()); 
     InsertInLines(last, key, index, "Attr_Family name", family); 
     InsertInLines(last, key, index, "CODE_IsOptional", "true"); 
     InsertInLines(last, key, index, "Model", modelNo); 
     InsertInLines(last, key, index, "CODE_OptionalInfo", seatPad.Value.UpholsteryFabric.ToLower() + " black"); 

     if (AddToLinePrice(salesCodePrice, keyValuePair.Value.InternalHeading, index, last)) 
      continue; 
    } 
} 

     //AppendLines(linkingDevices, prices, lines, fieldMapping, "", modelNo, family, "linking.Value.SimpleMaterial", ""); 

     foreach (var linking in linkingDevices) 
     { 
      List<PriceDataModel_New> bestPrices = PriceService.GetBestPrices(prices, linking.Value.No, string.Empty, string.Empty, string.Empty, 1); 
      var priceGroups = bestPrices.GroupBy(p => p.SalesCode); 
      var salesCodePrice = priceGroups.ToDictionary(k => k.Key, v => v.First()); 
      AddEmptyines(fieldMapping, lines); 
      var last = lines.Last(); 

      foreach (var keyValuePair in fieldMapping.Postions) 
      { 
       int index = keyValuePair.Key; 
       var key = keyValuePair.Value.InternalHeading; 
       InsertInLines(last, key, index, "CODE_Id", modelNo + "_" + linking.Value.No); 
       InsertInLines(last, key, index, "ItemId", linking.Value.No); 
       InsertInLines(last, key, index, "CODE_OptionalName", linking.Value.ComponentType.ToLower()); 
       InsertInLines(last, key, index, "Attr_Family name", family); 
       InsertInLines(last, key, index, "CODE_IsOptional", "true"); 
       InsertInLines(last, key, index, "Model", modelNo); 
       InsertInLines(last, key, index, "CODE_OptionalInfo", linking.Value.SimpleMaterial); 

       if (AddToLinePrice(salesCodePrice, keyValuePair.Value.InternalHeading, index, last)) 
        continue; 
      } 
     } 

는 foreach는 위의 몇 줄에 차이가 루프 :

는 중복 된 코드의 샘플입니다. 이 일반화하는 방법을 알아낼 수 없습니다. Reflection, Func <> 및 대표자들과 함께 시도해 봤지만 어떤 제안이라도 대환영입니다.

+2

. 이것은 특정 리팩토링에 대한 요청이므로, 나는 그것이 너무 광범위하다고 생각하지 않습니다. –

+0

@ Jean-FrançoisFabre [this] (http://meta.codereview.stackexchange.com/q/5777/31562)를 읽으셨습니까? 또한 CR을 이전 대상으로 추가하는 것이 새로운 것은 아닙니다. 그러나 그것은 여러 가지 이유로 문제가되는 것입니다. 필요 이상으로 여기에 의견을 남기고 싶지 않으므로 그것에 대해 이야기하고 싶다면 여기에서 나를 찾을 수 있습니다 : http://chat.stackexchange.com/rooms/8595/the-2nd-monitor –

+0

예, 저는 내가 내 질문에 부딪혔을 때 그것을 읽으십시오. 보시다시피 질문은 끝났습니다. CodeReview에서 나는 심지어 대답하려고 노력했을 것입니다.그래서 SO 또는 CR에 있어야하는지 여부는 기본적으로 의견 : –

답변

0

우선, 글라이더, 좌석 패드 및 링크 하위 클래스에 대한 기본 클래스가 있습니다.

내부 foreach의 몸체를 xtract하여 고유 한 방법으로 이동합니다. 전달 된 매개 변수는 기본 클래스 유형이어야하므로 모든 자식 유형에 대해 코드가 작동합니다.

나머지는 해협이되어야합니다.

3

글라이더, seatpads 및 linkingdevices 개체에 대한 다음과 유사한 인터페이스를 구현합니다 modelNo처럼 (제품의 외부 무엇이든

private void Generic<T>(IEnumerable<T> products, string modelNo) 
     where T: IProduct 

수락 :

public interface IProduct 
    { 
     string No { get; } 
     string CodeName { get; } 
     string Family { get; } 
     string ModelNo { get; } 

     string CodeInfo { get; } 

     IDictionary<string, string> FieldMapping { get; } 
    } 

다음과 같은 일반적인 함수를 만들를 입력)을 입력하고 제품에 특정한 것을 넣으십시오 ('제품'이 여기에 적합하지 않은 경우 이름을 변경하십시오).

선택적으로, 나는 (내가 비록 기본 복잡성 확실하지 않다) 의미가 있습니다 경우도 있으므로 같은 특성을 평평하게하기 위해 Fieldmapping 사전을 변경 할 것은 :

public interface IProduct 
    { 
     string No { get; } 
     string CodeName { get; } 
     string Family { get; } 
     string ModelNo { get; } 

     string SalesCode { get; } 
     string CodeInfo { get; } 

     IEnumerable<IProductAttribute> Attributes { get; } 
    } 

    public interface IProductAttribute 
    { 
     string InternalHeading { get; } 
     int Index { get; } //not sure what this is for. 
    } 
+0

@Blorgbeard이 대답이 유용 했습니까? 그렇다면 다른 사람들을 도울 수있는 답으로 표시해야합니다. –

0

음, 하드입니다 매우 주관적이므로 최상의 솔루션을 제안하십시오. Func<>은 미성년자이거나 몇 가지 차이점이있는 경우도 있습니다.

원래 인터페이스를 사용하면 (원래 개체를 변경하고 싶지 않은 경우 일부 어댑터/facade/bridge를 사용하는 것이 더 적절할 수 있습니다.)

또는 원하는 필드가있는 다른 클래스를 만들어 원본 데이터를 새 형식으로 변환 할 수도 있습니다.

어떤 솔루션이 더 합리적인가요? 음, 평가하는 것은 당신에게 달려 있습니다. 내가 스택 오버플로이 오프 주제를 고려하지 않는 장 - FrançoisFabre @

Class adapter pattern

또한 다른 관련 디자인 패턴을 보일 수 있습니다 ...