I have a car object. The car cannot be driven unless it is turned on. When should I check to see if the car is on before I try to drive it?
In the main program?
class Program { static void Main(string[] args) { Car myCar = new Car(); if (myCar.isOn == false) //check here if car is on { myCar.Start(); } myCar.Drive(); } } class Car { public bool isOn; public void Drive() { Console.WriteLine("Car is driving"); } public void Start() { Console.WriteLine("Car is starting"); isOn = true; } } Or in the drive method of the class itself?
class Program { static void Main(string[] args) { Car myCar = new Car(); myCar.Drive(); } } class Car { public bool isOn; public void Drive() { if (this.isOn == false) //Check here if the car is on { this.Start(); } Console.WriteLine("Car is driving"); } public void Start() { Console.WriteLine("Car is starting"); isOn = true; } } This is an extremely simplified example, but when you have a large complex object with complicated logic, the need for organizing and controlling the object's behavior becomes apparent. Where is the proper place of determining and correcting an object's readiness before calling one of its methods? Should the method itself be responsible or the subroutine calling that method?