How to make a line foloower robot that goes back and forth the same line

Somehow the robot must "know" when to backtrack. How do You make that?
I suggest You make the robot turn around 180 degrees and use the same code for going back.