I am creating a sudoku game using the android sdk. I have a PreferenceActivity filled with different settings, such as "Highlight all digits" or "activate the visual helper". The problem is that I am trying to avoid using the if else pattern everywhere in my code in order to check if each settings is activated to execute a specific code. I am looking for the best pattern that could help me to handle my different settings. My code is pretty clear(I think), I have a Grid class containing all the grid information and a Game view, that handles inputs and interacts with the Grid class.
One way to avoid using a load of You start by defining the different states that influence the behaviour, based on the player preferences. Then you extract the behaviour from where it is now, and add it to a method of a class that derives from a base class. Depending on the user's preferences, you instantiate the appropriate derived class, and delegate the function calls to that object. If you have these states:
And if your code looks like (pseudo code):
You would split your code into something like this:
And your Grid:
This way, your code is very clean: you can see clearly what it's doing without getting bothered by a bloat of |
|||
|
As mentioned by @alexandre, without specific examples it's hard to offer specific fixes... But! It sounds like your intuition is, reasonably, that by simplifying your code structure, you'll reduce the maintenance burden and reduce the chance of bugs. Another approach to help in this regard is unit tests. This aims to nail down the functionality independently from the implementation. A unit test is like a "mini app" that uses your code/classes/engine, but only does one thing at a time and confirms the result.
This moves your focus from coding style to code correctness. And then, as you add features and maybe think there's too many if-elses or what not, and want to try a different approach, you can refactor but keep the same tests. Code always trends towards messiness. Sometimes we can reduce the decay a little... And unit tests are a way to know that it still works, even when it's messy. |
|||||||||||||||||
|
What you can do is combine the Strategy pattern and Factory pattern. Use the Factory pattern to build a drawer class that implements a given drawing strategy. In this way, you use composition or inheritance to determine behaviour at run time, and your if-else statements would be concentrated in the factory, instead of being scattered everywhere. An example:
|
||||
|
if
/else
you're trying to work your way around? – Alexandre Vaillancourt Aug 8 at 13:52