Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I have the four methods, they are pretty similar.
C#
private void MovePieceToUpperStation(Button currentButton, string rowId, string colId)
       {
           if (rowId == "8")
               return;
           var nextButtonName = ButtonNameNextToCurrentOneGetter.GetButtonNameOfTheUpperStation(colId, rowId);
           MovePieceToNextStation(currentButton, nextButtonName);
       }

       private void MovePieceToLowerStation(Button currentButton, string rowId, string colId)
       {
           if (rowId == "1")
               return;
           var nextButtonName = ButtonNameNextToCurrentOneGetter.GetButtonNameOfTheLowerStation(colId, rowId);
           MovePieceToNextStation(currentButton, nextButtonName);
       }

       private void MovePieceToRightStation(Button currentButton, string rowId, string colId)
       {
           if (colId == "H")
               return;
           var nextButtonName = ButtonNameNextToCurrentOneGetter.GetButtonNameOfTheRightStation(rowId, colId);
           MovePieceToNextStation(currentButton, nextButtonName);
       }

       private void MovePieceToLeftStation(Button currentButton, string rowId, string colId)
       {
           if (colId == "A")
               return;
           var nextButtonName = ButtonNameNextToCurrentOneGetter.GetButtonNameOfTheLeftStation(rowId, colId);
           MovePieceToNextStation(currentButton, nextButtonName);
       }


My question is I do not want repeat them. Is there a good way to do that?
For example, using generic.

What I have tried:

May pass another parameter to the method?
Posted
Updated 18-May-17 4:36am

Hello,

there's not much to simplify here.
You are calling a different method in each of them. That's not something that generic can help you with.
 
Share this answer
 
Those methods are only similar in structure, not in function. The problem is each method deals with different data and executes different code depending on different conditions imposed on that data.

There's no way to condense that code down to a single method in any elegant manner.
 
Share this answer
 
v2
Not easily - they do different things that just look similar.
You'd need to pass three extra parameters: the "comparison id" (either rowId or ColId), the "compare value" ("8", "1", "H", or "A") and a delegate for the method to execute (GetButtonNameOfTheUpperStation, GetButtonNameOfTheLowerStation, GetButtonNameOfTheRightStation, or GetButtonNameOfTheLeftStation)
And that means that every call has to know the details of what is going to happen, and why in order to call the "common" method - that's messy and prone to error.

I wouldn't do it.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900