How to avoid nesting method calls?

I have an object Question. Each Questioncontains instances of subsequent questions, which should then be displayed. When a question is displayed, a parameter is passed string.

If I have Question: Q1, Q2, Q3, Q4, Q1 may contain the following data:

Q1:
    questions: {
        "abc": Q2,
        "def": Q3,
        "xyz": Q2
    }

When selected "abc", the Q2 instance is passed a string "abc"and displayed.

How I implemented it:

class Question {
     public void Show(string option){
         // ... display
         var selectedOption = GetSelected();
         // questions["abc"] = Q2
         questions[selectedOption].Show(selectedOption);
}

I immediately had the feeling that I was wrong somewhere. This will not happen, but with a lot of questions I would fill the call stack. And even in a real scenario, it will make stack traces horrible and unreadable.

I was thinking about changing it to:

class Question {
     public Question Show(string option){
         // ... display
         var selectedOption = GetSelected();
         // questions["abc"] = Q2
         var next = questions[selectedOption];
         next.SetValue(selectedOption);
         return next;
}

, . , , : , , , ?

+4
2

:

class Question {
 private Dictionary<string, Question> questions = ...
 public Question Show(){
     // ... display
     var selectedOption = GetSelected();
     // questions["abc"] = Q2
     var next = questions[selectedOption];

     if(next != null)
         next.SetValue(selectedOption);

     return next;
}

{ \\ in some method
  Question q = Q1;
  do{
    q = q.Show();
  } while( q != null)
}
0

. :

for (Question q = initialQuestion; q.Next != null; q = q.Next)
 yield return q;

"" :

foreach (var q in GetQuestionChain(initialQuestion))
 q.Show(); //No recursion.
0

Source: https://habr.com/ru/post/1569979/


All Articles