New answers tagged

4

The simplest thing to do is to make a map<string, string -> object) where string -> object just means a function taking a string and producing an object. If the language you are using doesn't support first-class functions you can use the Strategy pattern. The Factory pattern is essentially just a special case of the Strategy pattern and thus just ...


4

Generally, it is often a good idea to separate the responsibilities of testing something like externally provided settings, and the "core businesss code" like GiveApples. On the other hand, having functions which group together what belongs together is also a good idea. You can accomplish both goals by refactoring your code like this: private void ...


5

Place the guard within the method itself. The consumer of GiveApples() or GiveBananas() shouldn't be responsible for managing the guards of GiveApples(). From a design standpoint SomeMethod() should only knows that it needs fruit and shouldn't care about what your application needs to do in order to get it. The abstraction of fruit retrieval becomes ...


13

I think of guards as something the method must obey. In your example, the method must not give apples if Settings.GiveApples is false. If that is the case then the guard definitely belongs inside the method. This prevents you from accidentally calling it from another point in your application without checking the guards first. On the other hand if the ...


2

So, you're asking how to protect your code from clumsy future devs? That's a tough task which is usually handled by applying code organisation techniques and not language constructs. In this specific case, I would simply make sure that reorderring the if blocks didn't functionally change my method. Like this: subroutine foo(int index) { bool checkA = ...


4

In probably all relevant languages, the statements are processed in order. And that's valid for the whole program code. Even the simplest programs wouldn't work otherwise. If someone is allowed to change the code but doesn't understand anything about it, there's not much you can do about it, except removing his rights to do so. Nothing wrong with a ...


9

Anyone who can edit the source code can remove anything that you might put in there to "protect" them. You can do two things: Choose a good name for the function that conveys your intention Provide Unit Tests that will break if someone ever changes what the function does Both do not prevent future programmers from changing anything if they need to, but ...



Top 50 recent answers are included