Checking the state inside a function or before calling it?

Which of these two programming styles do you prefer? What for? Are there any particular advantages to one over the other?

// Style 1 if (doBorder) doTheBorder(); if (doFrame) doTheFrame(); if (doDraw) doTheDraw(); void doTheBorder() { // ... } void doTheFrame() { // ... } void doTheDraw() { // ... } // Style 2 doTheBorder(); doTheFrame(); doTheDraw(); void doTheBorder() { if (!doBorder) return; // ... } void doTheFrame() { if (!doFrame) return; // ... } void doTheDraw() { if (!doDraw) return; // ... } 
+4
source share
1 answer

First. The second, it seems ... lacks confidence. Why call doTheBorder() if you don’t even know if you want the border to be drawn? IMO, you must argue that the border is really needed, and then call doTheBorder() with confidence!

... In addition, from a technical point of view: if doTheBorder() is in a closed API, the developer can call it in the distant future, and if the second style is used, they may wonder why the border was not working, despite their call for doTheBorder() . Of course, sometimes certain circumstances or restrictions or restrictions may dictate the use of the second style, but I would avoid it when it was possible.

+2
source

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


All Articles