Strategy Design Pattern- choosing between strategies with counters - java

I am programming in Java but this is a more of a design question so any OO programmer could probably answer this question. I have a question concerning the Strategy design pattern. Here are several inks I have found useful:
Strategy Pattern Explained-OO Design.
I am using the strategy pattern twice with one group of four strategies and one group of three. In each case I am deciding which strategy to use by maintaining a decaying counter. if the strategy the software decides to use is successful then the counter is incremented by one. If the strategy used is not successful then the counter is decremented by one. Regardless of success or failure ALL counters are multiplied by a number around .9 to "decay" the counters over time. The software will choose which strategy to use based on which strategy has the highest counter. An example of my very simple UML is shown below:
.
And in Link form (for easier reading):
Example UML
The UML above is the mockup I would like to use. If you can't tell from the above UML, I am writing a Rock, Paper, Scissors game with the intention of beating all of my friends.
Now, on to the problem:
I cannot decide how to implement the "counter system" for deciding which strategy to use. I was thinking about some kind of "data" class where all counters and history strings could be stored, but that just seemed clunky to me. At all times I am maintaining about 2 strings and about eight counters (maybe more maybe less). That is why I was thinking about a "data" class where everything could be stored. I could just instantiate the class to be used in the chooseStrategy() and chooseMetaStrategy() methods, but I just don't know. This is my first project that I will be working on my own for and I just cannot decide on anything. I feel like there is definitely a better solution but I am not experienced enough to know.
Thanks!
------------------------------------follow-up 1--------------------------------------------
Thank you so very much on everyone's answers and kind words. I do have a few follow up questions though. I am new to StackOverflow (and loving it) so if this is not the correct place for a followup question please let me know. I am editing my original post because my follow-up is a little lengthy.
I was looking into Paul Sonier's advice about using the composite pattern and it looked very interesting (thanks Paul!). For the purpose of the HistoryMatching and "intelligent" AntiRotation strategies I want to implement a string of all opponent plays accessible to both classes. Also, I want the history string to be edited no matter what strategy my program played so that I can keep an accurate record of the opponent's plays. The more comprehensive the string (actually I will probably use a LinkedList but if anyone knows of a better (sub-String/sub-List) search method/collection please let me know) the better the strategy can predict the opponent's behavior.
I was wondering how I could implement this "string" or collection while still using the composite pattern.
Also, TheCapn brought up that it would be a good idea to store different counters and history collections for each opponent. Any thought on how to implement this with the composite pattern?

Ideally, the intent is to have the counters be associated with the strategies, because they're counting the successes of the strategies. However, you don't necessarily want the strategies to know anything about the fact that they're being counted. To me, this indicates a Composite pattern, whereby you wrap your Strategy class in a class which has logic for tracking / degrading / modifying the count of usages.
This gives you locality (the count is stored with the strategy it's counting) and functional composition (count functionality is encapsulated in the composition class). As well, it maintains the isolation of the strategy class from other influences.
Your design breakdown so far looks good; you're certainly on a good and interesting path. Hope this helps!

Firstly, i'd suggest you try something a bit simpler: move-to-front. Keep your strategies in a list, initially in an arbitrary order. Work through them like this:
List<Strategy> strategies;
Strategy successfulStrategy = null;
for (Strategy strategy: strategies) {
boolean success = strategy.attempt();
if (success) {
break;
successfulStrategy = strategy;
}
}
if (successfulStrategy == null) throw new NoSuccessfulStrategyException();
// now move the successful strategy to the front of the list
strategies.remove(successfulStrategy);
strategies.add(0, successfulStrategy);
Basically, a successful strategy moves straight to the head of the queue; over time, good strategies accumulate near the head. It's not as subtle as something based on counts, but it's simple, and in practice, for all sorts of uses, it works very well.
However, if you're dead set on a count, then what i'd do is create a Decorator which wraps a strategy and keeps a count, and which can be compared with other such objects. Code is the easiest explanation:
public class ScoredStrategy implements Strategy, Comparable<ScoredStrategy> {
private final Strategy delegate;
private float score;
public ScoredStrategy(Strategy delegate) {
this.delegate = delegate;
}
public boolean attempt() {
boolean success = delegate.attempt();
score = (score * 0.9f) + (success ? 1 : -1);
return success;
}
public int compareTo(ScoredStrategy that) {
return -Float.compare(this.score, that.score);
}
}
In the main object, take your actual strategies, and wrap each in a ScoredStrategy. Put those in a list. When you need a strategy, work over the list, calling each strategy until you hit one that works. Then, simply sort the list. The strategies will then be in order, from best to worst.

Although "clunky" I think your intuition is correct. Store all data in a collection that can be accessed by the strategy you choose to implement. Keep separate data objects for each of your opponents and create new data objects when you define new opponents, storing them in a collection such as a Map will provide easy accessability.
The reason behind this is if/when you decide to change "MetaStrategies" you'll need the relevent information accessible to your objects, by storing them in other, abstract objects you may find the searching/parsing/gathering of data more difficult then it should be. This also closely matches the mental model you've generated for yourself so attempting to go against that flow will possibly lead to design mistakes.
The only other logical away around this (from my brief brainstorming) is to better define the surrounding logic or heuristics you plan to implement. If you create a more concrete way of picking a MetaStrategy you'll have a better understanding of how the data needs to be collected for access. Tom Anderson's method looks promising for your project!

Related

Using Massive Amounts of Implemented Interfaces

I am trying to create a game involving machines and items. I have a simple item interface and every item will implement this.
I would usually just create a class for every item, but there could potentially be thousands of items, and it doesn't feel right to create thousands of files for all the items. This applies to other large amounts of types of objects I might have. (ground tiles, entities)
I need a type safe way to store all these implemented interfaces. I need to easily be able to create a new item in my code, with only the name of the item.
I was thinking of having a huge class with subclasses holding lots of final constants that would all be anonymous classes, but this also seems like a bad way of doing this.
Is there any good way to do what I have in mind? (Sorry that this is a little vague)
My item interface is currently,
package com.bobona.craftable.model;
import com.bobona.craftable.CraftableGame;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
public interface Item {
String getId();
Map<String, Integer> getValues();
void onUse(AtomicReference<CraftableGame> game, Long entityUsedByIndex);
void onSecondaryUse(AtomicReference<CraftableGame> game, Long
entityUsedByIndex);
}
You're going to need to think about the hierarchy of your game first before you start coding anything.
You haven't described anything about this game, like what's in it or what the objects are or what things can interface with what, so I'll describe a popular game I like - Factorio.
In this game, amongst other things, there are a few things to describe:
Items which allow you to craft other items
Belts which move items
Assemblers which turn items into other items
So I would start with describing the basic hierarchy of how these things interact.
A class for items, and an enum to allow us to describe what the item is and how we can interact with it (if it's craftable or not, which are rules owned by the assemblers)
A class for belts, with as many belt types as we want to support (right now the game has 3)
A class for assemblers, which describe how many items can be accepted at once as well as how fast they craft things
You'll have to understand how your items interact with the environment before you describe rules. For example:
Items can be placed on belts through the use of an inserter.
Items can be placed into an assembler through the use of an inserter.
This will require more thought on your part. But, the number of classes you should have would be small provided that there are only a handful of elements in the world.
This is a difficult design problem, and there is no one size fits all answer as far as I know. As mentioned by Makoto in another answer, much of your approach will be dictated by the actual details of your specific game.
I would usually just create a class for every item, but there could potentially be thousands of items, and it doesn't feel right to create thousands of files for all the items.
I completely agree with this statement.
I need a type safe way to store all these implemented interfaces.
I'm not sure that this is possible (literally as written), if we accept the previous statement that separate classes or interfaces aren't the correct approach. However, if instead of type safe you'll settle for verifiable at runtime by some yet-unspecified mechanism, then I think it's quite doable.
[From Comment] It also wouldn't be nice to use non type-safe values to define items in recipes, as that would quickly become a pain to debug and refactor.
I agree you'll want some sort of verification, but as previously mentioned full-blown compile-time type safety might not be feasible while also avoiding thousands of separate classes. I think the key here is to reliably detect errors, respond to them in a way that doesn't break the game, and generate sensible debug messages for the developer.
There are a lot of ways to go about accomplishing this; which one you choose is going to depend on your exact requirements, your preferences, and a number of implementation details that I have no way of knowing. Some things that I think you should look into or consider:
Inheritance probably won't work at all, for the reasons you've already identified.
Composition or the flyweight pattern might improve things initially, but probably won't scale the way you want.
You could go for a RDBMS approach, as outlined here.
You might try a JSON based approach or equivalent, as outlined here.
The component pattern fits my understanding of your problem very well.
This is an incredibly well written answer detailing how to implement the component pattern for entities (which I think include the types of items you were describing) using bit fields.
This is a very similar question to yours on the gamedev stackexchange with some good answers.
Personally I like the component pattern, and am a fan of using JSON or an equivalent language for specifying the items themselves. Hopefully at least some of the above information will help you as you iteratively modify your architecture to meet your gameplay requirements.
would usually just create a class for every item, but there could potentially be thousands of items, and it doesn't feel right to create thousands of files for all the items.
Yes, you should not be doing that. Classes act as blueprint of your object. We don't create a new class for every new object. If you see that all your items share a common attribute (e.g. name), then those can be used as the attribute of your base class:
public abstract class Entity{
protected String name;
public Entity(String name){
this.name = name;
}
}
Then for those object which is an Item, you can extends it to base class:
//example
public abstract class Monster extends Entity{
protected int damage;
//constructor not shown
}
If you also need to indicate whether an Entity is Ground or Air. You can also use Interface as such:
public Interface OnAir{
}
public Interface OnGround{
}
Then you can have:
//example
public class FlyingMonster extends Monster implements OnAir {
//your other attributes here
}
public class LandMonster extends Monster implements OnGround {
//your other attributes here
}
Now you have the flexibility to manipulate the type of object you want.
To store all your monsters (ground and air):
ArrayList<Monster> monsters = new ArrayList<>();
To store all entities including monsters:
ArrayList<Entity> entities= new ArrayList<>();
The above solution is to reply your question. However, I should mention that in game making, I wouldn't want to create that many classes. But instead I would store all my entities in a datafile. If there are special attributes for your entity. For example, a fire-based weapon which does 30% extra damage to all ice-based creture. I would not code this in Java as well. But instead store it in a script file. That fire-based weapon will then be referenced to the script file.
The same logic applies to your Non-Playable Characters.
So what is the benefit of storing them in scripts and datafiles? You can add / remove / edit your entities without the need to recompile your codes. You can change how the weapons work, how your character behaves, how your NPCs talk without changing anything in Java.
This means that you can now add new items into the game by just typing into the textfile.

How to refactor a large class with many methods that have single responsibility?

Searching for design patterns and better code optimization mostly pops up articles on inheritance and relationships between classes and tools on how to create class diagrams. I would like a little insight on how to, say split, a big class. Am working on a java program with a class that has crossed 1600 lines of code and about 20 methods. What it does is query for data from a data source and generate huge text file.
Now there are lots of data modification logic(for each logic I have created small methods) that goes on to queried data like:
-check data dates of users and perform changes
-append strings
-logic to check if a record needs to be ignored
and storing filtered data in Collection and generating text file. I don't think creating separate class for each small logic is good idea. Perhaps I can create separate utility class and stuff static methods into it? I can't post code for confidentiality issues. If someone can shed a little light to get me thinking in right direction that would be great. Thanks.
The best thing you can do is forget what the code does, and think about what it is.
From the description you gave, you are "still" thinking about what your code is supposed to do. It queries a data source, checks dates, appends strings, filters, etc. This is not wrong for a functional or procedural approach, but not ideal for object-oriented code.
Try a little bit to forget what it supposed to do, and think about what "things" it is about. Are those things Accounts, Users, Machines, VirtualServers, etc. What is that huge text file? Is it a UsageReport, a BalanceSheet, etc.
Once you got the "things", you can start thinking about what "responsibilities" you need to assign each of them. Again, "querying the database" is not a responsibility. You have to do something with the data you get, for example generating a UsageReport, that is a responsibility.
That is OO in a nutshell. A few more pointers: Try to avoid utilities, try to avoid getters, try to avoid setters even more. Try to avoid Services, Processor, Handler, Renderer and similar classes. Those are not "things", but usually procedures in disguise.
Perhaps you should consider whether your initial premise is correct. The single responsibility principle states that a class should only have one reason to change.
In the case of the class you're describing, there are multiple responsibilities: querying a data source, filtering, string manipulation (presentation?), text file generation.
Each of these should be separated into its own class. This decouples the concerns and provides smaller more manageable code.
SRP (Single Responsibility Principle) suggests that we should have only one reason to change a class. i.e. a class should have only one single responsibility. So one class should do only one thing. So in an ideal object oriented environment, we would have classes for each of our work.
Ex:
Assume you are building a Calculator app with basic math support. Assume you have to implement Summing two numbers feature. In ideal way, you would have to do something like this.
public interface NumberMath{
public float value();
}
public class Sum implements NumberMath{
private float num1;
private float num2;
public Sum(float num1, float num2){
this.num1 = num1;
this.num2 = num2;
}
#Overrride
public float value(){
return num1 + num2;
}
}
I think you already found that it will make our code much verbose. So practically no one will follow object orientation (or SRP) in ideal way. Instead most of us would prefer one class containing methods for sum, subtract, division, multiplication etc. It makes our code less verbose.
But in your case 1600 lines of code with 20 methods for 1 class can't be good.
The best ways you can decompose your huge single class into multiple simple classes
Identify independent methods.
Combine similar small methods(behaviors) into a single class with a proper scope for that class, and a name that would properly define that scope.
Try to completely avoid code duplication by adhering into method reuse instead.
Again it is somewhat difficult to provide a very specific answer for your problem since details are limited. Anyway hope this helps. :)

Implicit vs Explicit data structures

Lately I've been struggling with some recurrent design problem which I don't know how to solve elegantly.
Say I am making a game with a couple of players and for each player some connected pieces. Together these pieces form a semi-complex collection or structure. Now I could implement this structure in 2 ways: Either store the structure implicitly through pointers in the pieces themselves i.e:
class BigPiece extends Piece {
Piece opposingPiece, nextPiece, previousPiece, index;
}
Or I could implement this structure in a collection class and keep the information centralized:
class SomeCollection<Collection<Piece>> {
SomeOtherCollection<Collection<Piece>> collection
= new SomeOtherCollection<Collection<Piece>>();
public SomeCollection() {
collection.add(new PieceCollection<Piece>();
collection.add(new PieceCollection<Piece>();
collection.add(new PieceCollection<Piece>();
}
public Piece getPiece(int playerIndex, int pieceIndex) {
collection.get(playerIndex).get(pieceIndex);
}
public Piece getOpposingPiece(int playerIndex, int pieceIndex) {
int nextPlayerIndex = collection.listIterator(playerIndex).nextIndex();
return this.collection.get(nextPlayerIndex).get(pieceIndex);
}
}
Now I usually favor the second one, but that's just based on my guts and I don't have that much experience in class design, especially not with big applications. I can see pros and cons on both sides.
The problem I usually have with the first solution is that you still have to create the associations in some builder or factory which actually links the objects together. This doesn't seem very robust to me. Who can reassure me all the pointers are actually correct throughout the application's lifetime?
The second solution centralizes the data more. This really dumbs down the higher classes though (such as individual Pieces). The problem I usually have with this is that whenever I want to traverse this collection, I have to do it on some lower level. You can't ask a piece 'Hey, what's your opposing piece?'. No, you'd have to get a game object to get a pointer to your collection which you then ask what the opposing piece is. This makes more 'managery' classes which collect data from all around your application (method chaining =( ) to finally implement your algorithm. This seems to violate the Law of Demeter.
Sure I could add a pointer to the corresponding collection from each individual piece as well, but I don't know if that's such a good idea since this only seems to be duplicate information.
My personal recommendation is moreso the second option as opposed to the first. As you pointed out, a piece shouldn't (at least in this context) know what its opposing/next/previous piece is.
A manager class would make more logical sense to better facilitate communication between the classes instead of pieces having references to other pieces. I admit I don't fully know about the Law of Demeter but Wikipedia leads me to believe it is all about encapsulation which the manager classes would actually help as well!
I don't think Pieces (again, in this context) should be able to, say, move another piece. However a manager class would logically want to.
That is my suggestion, I hope it helps!

OO Design Issue with IDs

Say as an example I have a Player class that has a race via a Race class. These races are fixed in number and are loaded into an array which can be accessed statically.
My question is whether the Player class should have an index ID number which would then need to call the static function getRaceByID(int) to retrieve the Race class to do some internal calculations. Now I could get around having to do this if I was to have the race reference directly in the Player class, but then saving the player to a file becomes problematic. I only want a reference to the Race be stored along with the Player data. Like an ID.
I want to avoid storing a copy of the Race data and instead just reference it. Is there anything I should be doing differently? Are there any patterns to address something like this? Databases deal with IDs, but it doesn't seem to work very well in OO development. Any help is appreciated, thanks.
class Player
{
Race race;
}
In this case I would need to compare this race to the races in my static array so that I can properly write out the index ID. Another solution is to store the ID in the Race class itself so that I can reference it directly from the Race class like so:
race.getID();
Or would it be better to go with something like this to enforce this relationship:
class Player
{
int raceID;
}
Race r = MyFile.getRaceByID(raceID);
// can now use race
What you have in memory does not have to be what you store in a database.
The details will depend upon the language you're using and the Object-to-Database technology.
If you have
Player {
Race myRace;
// etc
}
This does not necesserily imply that you have a copy of the Race, in some languages this would imply a "reference" or "pointer" to a Race.
When you come to store in the database it would be quite normal for just the Id of the race to be stored.
In other words, you don't need to compromise the OO design to achieve the effect you want.
Of some relevance to using IDs in an OO design: Modern C++ Design by Alexandrescu has an excellent chapter on object factories. If you have a big switch statement on your ID, then you could probably benefit from reading this chapter, as it will show you the OO way to handle that sort of thing. As the book says:
The Shape-Drawing example [of
polymorphism] is often
encountered in C++ books, including
Bjarne Stroustrup's classic
(Stroustrup 1997). However, most
introductory C++ books stop when it
comes to loading graphics from a file,
exactly because the nice model of
having separate drawing objects
breaks.... A straightforward implementation
is to require each Shape-derived
object to save an integral identifier
at the very beginning. Each object
should have its own unique ID. Then
reading a file would look like this:
[code with big switch]
.... The only
problem [with this type of code] is that it
breaks the most important rules of
object orientation: [E.G.,] It
collects in a single source file
knowledge about all Shape-derived
classes in the program....
There's no reason that your ID based concept won't work. It doesn't violate any OO principles, and has several benefits. I see no reason NOT to go that route, especially if you've already determined that it would work well for you.
As an aside, if you want to avoid having static_races[player.race_id] scattered throughout your code, a simple wrapper function would suffice in maintaining a more "OO feel" (Psudocode, since you haven't stated a language:
function Race Player::GetRace() {
return static_races[this.race_id];
}
Simple, but effective. No need to over complicate things.

Secret Handshake Anti-Pattern

I've just come across a pattern I've seen before, and wanted to get opinions on it. The code in question involves an interface like this:
public interface MyCrazyAnalyzer {
public void setOptions(AnalyzerOptions options);
public void setText(String text);
public void initialize();
public int getOccurances(String query);
}
And the expected usage is like this:
MyCrazyAnalyzer crazy = AnalyzerFactory.getAnalyzer();
crazy.setOptions(true);
crazy.initialize();
Map<String, Integer> results = new HashMap<String, Integer>();
for(String item : items) {
crazy.setText(item);
results.put(item, crazy.getOccurances);
}
There's reasons for some of this. The setText(...) and getOccurances(...) are there because there are multiple queries you might want to do after doing the same expensive analysis on the data, but this can be refactored to a result class.
Why I think this is so bad: the implementation is storing state in a way that isn't clearly indicated by the interface. I've also seen something similar involving an interface that required to call "prepareResult", then "getResult". Now, I can think of well designed code that employs some of these features. Hadoop Mapper interface extends JobConfigurable and Closeable, but I see a big difference because it's a framework that uses user code implementing those interfaces, versus a service that could have multiple implementations. I suppose anything related to including a "close" method that must be called is justified, since there isn't any other reasonable way to do it. In some cases, like JDBC, this is a consequence of a leaky abstraction, but in the two pieces of code I'm thinking of, it's pretty clearly a consequence of programmers hastily adding an interface to a spaghetti code class to clean it up.
My questions are:
Does everyone agree this is a poorly designed interface?
Is this a described anti-pattern?
Does this kind of initialization ever belong in an interface?
Does this only seem wrong to me because I have a preference for functional style and immutability?
If this is common enough to deserve a name, I suggest the "Secret Handshake" anti-pattern for an interface that forces you to call multiple methods in a particular order when the interface isn't inherently stateful (like a Collection).
Yes, it's an anti-pattern: Sequential coupling.
I'd refactor into Options - passed to the factory, and Results, returned from an analyseText() method.
I'd expect to see the AnalyzerFactory get passed the necessary params and do the construction itself; otherwise, what exactly is it doing?
Not sure if it does have a name, but it seems like it should :)
Yes, occassionally it's convenient (and the right level of abstraction) to have setters in your interface and expect classes to call them. I'd suggest that doing so requires extensive documentation of that fact.
Not really, no. A preference for immutability is certainly a good thing, and setter/bean based design can be the "right" choice sometimes too, but your given example is taking it too far.
I'm not sure whether it's a described anti-pattern but I totally agree this is a poorly designed interface. It leaves too much opportunity for error and violates at least one key principle: make your API hard to misuse.
Besides misuse, this API can also lead to hard-to-debug errors if multiple threads make use of the same instance.
Joshua Bloch actually has an excellent presentation (36m16s and 40m30s) on API design and he addresses this as one of the characteristics of a poorly designed API.
I can't see anything bad in here. setText() prepares the stage; after that, you have one or more calls to getOccurances(). Since setText() is so expensive, I can't think of any other way to do this.
getOccurances(text, query) would fix the "secret handshake" at a tremendous performance cost. You could try to cache text in getOccurances() and only update your internal caches when the text changes but that starts to look more and more like sacrifice to some OO principle. If a rule doesn't make sense, then don't apply it. Software developers have a brain for a reason.
One possible solution - use Fluent chaning. That avoids a class containing methods that need to called in a certain order. It's a lot like the builder pattern which ensures you don't read objects that are still in the middle of being populated.

Categories