How would you avoid context/class explosion in this case with MSpec? - mspec

I love mspec. It is great for providing key examples in way that is easy to communicate with non technical people but sometimes I find it provides an unnecessary verbosity, specifically an explosion of classes.
Take the following example.
I want to model the movement of a knight piece in chess. Assuming the knight is not near any other piece or the boundaries of the board there are 8 possible moves that knight can have I want to cover each of these possibilities but to be frank I am too lazy to write 8 separate specifications (8 classes). I know that I can be clever with behaviours and inheritance but as I want to cover the 8 valid moves I cannot see how I can do it with out 8 becauses so therefore 8 separate classes.
What is the best way to cover these scenarios with mspec?
Some code.
public class Knight
{
public string Position {get; private set;}
public Knight(string startposition)
{
Position = startposition;
}
public void Move
{
// some logic in here that allows a valid move pattern and sets positions
}
}
What I might do.
[Subject(typeof(Knight),"Valid movement")]
public class when_moving_the_knight
{
Establish that = () => knight =new Knight("D4");
Because of = ()=> knight.Move("B3");
It should_update_position = ()=> knight.Position.ShouldEqual("B3");
It should_not_throw;
/// etc..
}
But not 8 times.

Honestly, I couldn't tell you the best way to do that in MSpec. But I've experienced a similar class explosion problem with MSpec when using it in similar circumstances. I don't know if you have ever tried RSpec. In RSpec contexts and specifications are built up within the confines of executable code. What that means is you can create a data structure, iterate on it, and create several contexts and specs using one block of code. This becomes especially handy when you are trying to specify how something based in mathematics behaves (prime factors,tic tac toe, chess, etc...). A single pattern of behavior can be specified across each member of a set of given and expected values.
This example is written in NSpec, a context/spec framework for C# modeled after RSpec. I purposefully left a failing spec. I just went down this kata far enough to find a place to use iteration. The failing spec forces you to resolve the shortcomings of the naive implementation.
Here's another example of prime factor kata: http://nspec.org/#dolambda
Output:
describe Knight
when moving 2 back and 1 left
when a knight at D4 is moved to B3
knight position should be B3
when a knight at C4 is moved to A3
knight position should be A3 - FAILED - String lengths are both 2. Strings differ at index 0., Expected: "A3", But was: "B3", -----------^
**** FAILURES ****
describe Knight. when moving 2 back and 1 left. when a knight at C4 is moved to A3. knight position should be A3.
String lengths are both 2. Strings differ at index 0., Expected: "A3", But was: "B3", -----------^
at ChessSpecs.describe_Knight.<>c__DisplayClass5.<when_moving_2_back_and_1_left>b__4() in c:\Users\matt\Documents\Visual Studio 2010\Projects\ChessSpecs\ChessSpecs\describe_Knight.cs:line 23
2 Examples, 1 Failed, 0 Pending
Code:
using System.Collections.Generic;
using NSpec;
class describe_Knight : nspec
{
void when_moving_2_back_and_1_left()
{
new Each<string,string> {
{"D4", "B3"},
{"C4", "A3"},
}.Do( (start, moveTo) =>
{
context["when a knight at {0} is moved to {1}".With(start,moveTo)] = () =>
{
before = () =>
{
knight = new Knight(start);
knight.Move(moveTo);
};
it["knight position should be {0}".With(moveTo)] = () => knight.Position.should_be(moveTo);
};
});
}
Knight knight;
}
class Knight
{
public Knight(string position)
{
Position = position;
}
public void Move(string position)
{
Position = "B3";
}
public string Position { get; set; }
}

Just use the Its the way you want to. It should be able to move from here to there, it should be able to move from here(2) to there(2), etc. Very common pattern in rspec but not so much in MSpec because it's generally overused so no one ever talks about it for fear of guiding the wrong way. This is a great spot to use this though. You're describing the behavior of the Knight's moving.
You can describe it even better by being more specific in your Its. It should be able to move up two and to the right one, it should be able to move up two and to the left one. It should not be able to move onto a friendly piece, etc.
Yes, you'll need to put more than one line of code in your It, but that's OK. At least in my opinion.

From what I see your design states that the Knight would throw an exception if moved in an invalid position. In this case I think that your method has two different responsibilities, one for checking a valid move and the other for doing the correct move or throwing. I would suggest to split your method into the two distinct responsibilities.
For this specific case I would extract a method for checking whether a move is valid or not, and then calling it from your move method. Something like that:
public class Knight
{
internal bool CanMove(string position)
{
// Positioning logic here which returns true or false
}
public void Move(string position)
{
if(CanMove(position))
// Actual code for move
else
// Throw an exception or whatever
}
}
this way you could test the logic inside CanMove for testing valid positions for a given Knight (which you can do with a single test class and different "It"s), then make just one test for the Move method to see if it fails when given an invalid position.

Related

What is this anti-pattern? Invoking a function for a latent effect

Is there a name for this anti-pattern? The best way I can describe it is "invoking a function for a latent effect, not for its primary purpose".
Function A does X and Z
Function B does Y and Z
Function A calls Function B in order to do Z.
Problems with this anti-pattern:
Lack of code expressiveness
Redundant code execution
Cause: Unwillingness to refactor existing code and create a new function
Example:
void afterWifeSaysHello() {
// I need to say "hello!" back to my wife!
// I do the same thing when the doorbell rings so...
afterDoorbellRings();
}
void afterDoorbellRings() {
openDoor();
// pretend that saying hello is more complex than one simple line of code.
say("hello!");
closeDoor();
}
It should be written as:
void afterWifeSaysHello() {
sayHello();
}
void afterDoorbellRings() {
openDoor();
sayHello();
closeDoor();
}
void sayHello() {
say("hello!");
}
Developer A: "You shouldn't call afterDoorbellRings in afterWifeSaysHello because the doorbell didn't ring."
Developer B: "It's just the function name. afterDoorbellRings does what I need."
Developer A: "But you're opening the door for no reason."
Developer B: "The door is still closed in the end so it doesn't matter."
There is a coupling problem in the original afterDoorbellRings method in that it assumes that the "say hello" functionality is only needed in the context of the door opening and closing. The anti-pattern you describe could also happen where the other parts of afterDoorbellRings don't change state, rather than cancel each other out as in your open/close door example. I'm sure this anti-pattern is common enough, but I've never seen it given a name other than "bad coding"!

Optaplanner: NullPointerException when calling scoreDirector.beforeVariableChanged in a simple custom move

I am building a Capacited Vehicle Routing Problem with Time Windows, but with one small difference when compared to the one provided in examples from the documentation: I don't have a depot. Instead, each order has a pickup step, and a delivery step, in two different locations.
(like in the Vehicle Routing example from the documentation, the previousStep planning variable has the CHAINED graph type, and its valueRangeProviderRefs includes both Drivers, and Steps)
This difference adds a couple of constraints:
the pickup and delivery steps of a given order must be handled by the same driver
the pickup must be before the delivery
After experimenting with constraints, I have found that it would be more efficient to implement two types of custom moves:
assign both steps of an order to a driver
rearrange the steps of a driver
I am currently implementing that first custom move. My solver's configuration looks like this:
SolverFactory<RoutingProblem> solverFactory = SolverFactory.create(
new SolverConfig()
.withSolutionClass(RoutingProblem.class)
.withEntityClasses(Step.class, StepList.class)
.withScoreDirectorFactory(new ScoreDirectorFactoryConfig()
.withConstraintProviderClass(Constraints.class)
)
.withTerminationConfig(new TerminationConfig()
.withSecondsSpentLimit(60L)
)
.withPhaseList(List.of(
new LocalSearchPhaseConfig()
.withMoveSelectorConfig(CustomMoveListFactory.getConfig())
))
);
My CustomMoveListFactory looks like this (I plan on migrating it to an MoveIteratorFactory later, but for the moment, this is easier to read and write):
public class CustomMoveListFactory implements MoveListFactory<RoutingProblem> {
public static MoveListFactoryConfig getConfig() {
MoveListFactoryConfig result = new MoveListFactoryConfig();
result.setMoveListFactoryClass(CustomMoveListFactory.class);
return result;
}
#Override
public List<? extends Move<RoutingProblem>> createMoveList(RoutingProblem routingProblem) {
List<Move<RoutingProblem>> moves = new ArrayList<>();
// 1. Assign moves
for (Order order : routingProblem.getOrders()) {
Driver currentDriver = order.getDriver();
for (Driver driver : routingProblem.getDrivers()) {
if (!driver.equals(currentDriver)) {
moves.add(new AssignMove(order, driver));
}
}
}
// 2. Rearrange moves
// TODO
return moves;
}
}
And finally, the move itself looks like this (nevermind the undo or the isDoable for the moment):
#Override
protected void doMoveOnGenuineVariables(ScoreDirector<RoutingProblem> scoreDirector) {
assignStep(scoreDirector, order.getPickupStep());
assignStep(scoreDirector, order.getDeliveryStep());
}
private void assignStep(ScoreDirector<RoutingProblem> scoreDirector, Step step) {
StepList beforeStep = step.getPreviousStep();
Step afterStep = step.getNextStep();
// 1. Insert step at the end of the driver's step list
StepList lastStep = driver.getLastStep();
scoreDirector.beforeVariableChanged(step, "previousStep"); // NullPointerException here
step.setPreviousStep(lastStep);
scoreDirector.afterVariableChanged(step, "previousStep");
// 2. Remove step from current chained list
if (afterStep != null) {
scoreDirector.beforeVariableChanged(afterStep, "previousStep");
afterStep.setPreviousStep(beforeStep);
scoreDirector.afterVariableChanged(afterStep, "previousStep");
}
}
The idea being that at no point I'm doing an invalid chained list manipulation:
However, as the title and the code comment indicate, I am getting a NullPointerException when I call scoreDirector.beforeVariableChanged. None of my variables are null (I've printed them to make sure). The NullPointerException doesn't occur in my code, but deep inside Optaplanner's inner workings, making it difficult for me to fix it:
Exception in thread "main" java.lang.NullPointerException
at org.drools.core.common.NamedEntryPoint.update(NamedEntryPoint.java:353)
at org.drools.core.common.NamedEntryPoint.update(NamedEntryPoint.java:338)
at org.drools.core.impl.StatefulKnowledgeSessionImpl.update(StatefulKnowledgeSessionImpl.java:1579)
at org.drools.core.impl.StatefulKnowledgeSessionImpl.update(StatefulKnowledgeSessionImpl.java:1551)
at org.optaplanner.core.impl.score.stream.drools.DroolsConstraintSession.update(DroolsConstraintSession.java:49)
at org.optaplanner.core.impl.score.director.stream.ConstraintStreamScoreDirector.afterVariableChanged(ConstraintStreamScoreDirector.java:137)
at org.optaplanner.core.impl.domain.variable.inverserelation.SingletonInverseVariableListener.retract(SingletonInverseVariableListener.java:96)
at org.optaplanner.core.impl.domain.variable.inverserelation.SingletonInverseVariableListener.beforeVariableChanged(SingletonInverseVariableListener.java:46)
at org.optaplanner.core.impl.domain.variable.listener.support.VariableListenerSupport.beforeVariableChanged(VariableListenerSupport.java:170)
at org.optaplanner.core.impl.score.director.AbstractScoreDirector.beforeVariableChanged(AbstractScoreDirector.java:430)
at org.optaplanner.core.impl.score.director.AbstractScoreDirector.beforeVariableChanged(AbstractScoreDirector.java:390)
at test.optaplanner.solver.AssignMove.assignStep(AssignMove.java:98)
at test.optaplanner.solver.AssignMove.doMoveOnGenuineVariables(AssignMove.java:85)
at org.optaplanner.core.impl.heuristic.move.AbstractMove.doMove(AbstractMove.java:35)
at org.optaplanner.core.impl.heuristic.move.AbstractMove.doMove(AbstractMove.java:30)
at org.optaplanner.core.impl.score.director.AbstractScoreDirector.doAndProcessMove(AbstractScoreDirector.java:187)
at org.optaplanner.core.impl.localsearch.decider.LocalSearchDecider.doMove(LocalSearchDecider.java:132)
at org.optaplanner.core.impl.localsearch.decider.LocalSearchDecider.decideNextStep(LocalSearchDecider.java:116)
at org.optaplanner.core.impl.localsearch.DefaultLocalSearchPhase.solve(DefaultLocalSearchPhase.java:70)
at org.optaplanner.core.impl.solver.AbstractSolver.runPhases(AbstractSolver.java:98)
at org.optaplanner.core.impl.solver.DefaultSolver.solve(DefaultSolver.java:189)
at test.optaplanner.OptaPlannerService.testOptaplanner(OptaPlannerService.java:68)
at test.optaplanner.App.main(App.java:13)
Is there something I did wrong? It seems I am following the documentation for custom moves fairly closely, outside of the fact that I am using exclusively java code instead of drools.
The initial solution I feed to the solver has all of the steps assigned to a single driver. There are 15 drivers and 40 orders.
In order to bypass this error, I have tried a number of different things:
remove the shadow variable annotation, turn Driver into a problem fact, and handle the nextStep field myself => this makes no difference
use Simulated Annealing + First Fit Decreasing construction heuristics, and start with steps not assigned to any driver (this was inspired by looking up the example here, which is more complete than the one from the documentation) => the NullPointerException appears on afterVariableChanged instead, but it still appears.
a number of other things which were probably not very smart
But without a more helpful error message, I can't think of anything else to try.
Thank you for your help

Render glitch with custom block boundaries minecraft

I'm creating a mod for Minecraft. Recently, I've tried to make a custom block, and I'm having two issues with it.
My main issue is that the block is rendering incorrectly. I want the block to be smaller in size than a full block. I successfully changed the block boundaries with setBlockBounds(), and while that did make the block render smaller and use the smaller boundaries, it causes other rendering issues. When I place the block, the floor below is becomes invisible and I can see through it, either to caves below, blocks behind it, or the void if there is nothing there. How do I fix that block not rendering? Here's a screenshot:
Additionally, my goal for this block is to emit an "aura" that gives players around it speed or some other potion effect. I have the basic code for finding players around the block and giving them speed, but I can't find a way to activate this method every tick or every X amount of ticks to ensure that it gives players within the box speed in a reliable manner. There are already some blocks in the normal game that do this, so it must be possible. How can I do this?
For your first issue, you need to override isOpaqueCube to return false. You'll also want to override isFullCube for other parts of the code, but that isn't as important for rendering. Example:
public class YourBlock {
// ... existing code ...
/**
* Used to determine ambient occlusion and culling when rebuilding chunks for render
*/
#Override
public boolean isOpaqueCube(IBlockState state) {
return false;
}
#Override
public boolean isFullCube(IBlockState state) {
return false;
}
}
Here's some info on rendering that mentions this.
Regarding your second problem, that's more complicated. It's generally achieved via a tile entity, though you can also use block updates (which is much slower). Good examples of this are BlockBeacon and TileEntityBeacon (for using tile entities) and BlockFrostedIce (for block updates). Here's some (potentially out of date) info on tile entities.
Here's an (untested) example of getting an update each tick this with tile entities:
public class YourBlock {
// ... existing code ...
/**
* Returns a new instance of a block's tile entity class. Called on placing the block.
*/
#Override
public TileEntity createNewTileEntity(World worldIn, int meta) {
return new TileEntityYourBlock();
}
}
/**
* Tile entity for your block.
*
* Tile entities normally store data, but they can also receive an update each
* tick, but to do so they must implement ITickable. So, don't forget the
* "implements ITickable".
*/
public class TileEntityYourBlock extends TileEntity implements ITickable {
#Override
public void update() {
// Your code to give potion effects to nearby players would go here
// If you only want to do it every so often, you can check like this:
if (this.worldObj.getTotalWorldTime() % 80 == 0) {
// Only runs every 80 ticks (4 seconds)
}
}
// The following code isn't required to make a tile entity that gets ticked,
// but you'll want it if you want (EG) to be able to set the effect.
/**
* Example potion effect.
* May be null.
*/
private Potion effect;
public void setEffect(Potion potionEffect) {
this.effect = potionEffect;
}
public Potion getEffect() {
return this.effect;
}
#Override
public void readFromNBT(NBTTagCompound compound) {
super.readFromNBT(compound);
int effectID = compound.getInteger("Effect")
this.effect = Potion.getPotionById(effectID);
}
public void writeToNBT(NBTTagCompound compound) {
super.writeToNBT(compound);
int effectID = Potion.getIdFromPotion(this.effect);
compound.setInteger("Effect", effectID);
}
}
// This line needs to go in the main registration.
// The ID can be anything so long as it isn't used by another mod.
GameRegistry.registerTileEntity(TileEntityYourBlock.class, "YourBlock");

Clean code , testing and re-usability clarification

Aiming for clean code and testing . Each function / method , should do one and only one thing. this is the theory. to illustrate that i want to share with you some code and then question.
Let's say we need a method that will return a list of players if a condition is true and an empty list of the condition is false.
First approach: One method:
public List<int> ListOfPlayersIDs(int InputNumber)
{
if (Condition)
{
return new List<int>(new int[] {1, 2, 3}); // return a list with items
}
else
{
return new List<int>();//return an empty list
}
}
So here the method ListOfPlayersIDs performs two things:
returns a list of players
Verify if a condition is valid and returns an empty list if not
To divide those "functionality" we can have one method to check the condition and one to return the list of players.
Something like this:
Second approach: Two methods:
First Method
public bool ArePlayerValidForThisNumber(int InputNumber)
{
If (condition)
return true;
else return false;
//Or simply return condition;
}
Second method
public List<int> ListOfPlayersIDs(int InputNumber)
{
return new List<int>(new int[] {1, 2, 3}); // return a list with items
}
My question is :
Which approach do you follow and apply in your coding.
For me the second one is testable, reusable and each method does exactly what it suppose to do. but isn't just a theory in books? I read a lot of code and it does not respect this pattern.
What's your take on this?
It depends (tm). And it depends if you make your code cleaner and easier to understand when you break things into smaller methods.
Personally I would keep the external interface the same (the method can return a filled list or empty), as otherwise, if your client needs to do code if/else clause, you might be leaking logic. Also, I would use an approach called 'code at two levels of abstraction' or 'each method should descend one level of abstraction'. By doing this the final code might look like
public List<int> ListOfPlayersIDs(int InputNumber)
{
if (methodDescribingTheBusinessCondition()) {
return methodDescribingPositiveOutcome();
} else {
return methodNameDescribingNegativeOutcome();
}
}
The idea is that all of this should read like "normal" English, so someone reading the code will get the idea of what's going on without having to know all the nitty gritty details. Here each method is also doing just one thing and the method that orchestrates the whole thing is usually called a "policy" (as it describes your functionality).
If your method is simple, this level of abstraction might make it more difficult to understand.
Last but not least, this approach is explained in a few books (Clean Code to be very specific), and it's used as a good practice in professional development.

Can a finite state machine work with persistence without breaking the FSM encapsulation?

Say we have a (UK) Traffic Light simulation app and a class TrafficLight has an associated finite state machine defined as:-
* --> RED --> RED_AMBER --> GREEN --> AMBER --> RED --> ...
(repeat until the proverbial cows make an appearance )
On construction TrafficLight's state is RED
Some kind of time trigger causes a state change.
In the app there may be some code like ( removing any code that takes away from point ) ...
TrafficLight trafficLightsAtBigJunction = new TrafficLight(); // state = RED
trafficLightsAtBigJunction.setState( TrafficLightState.RED_AMBER );
trafficLightsAtBigJunction.setState( TrafficLightState.GREEN );
trafficLightsAtBigJunction.setState( TrafficLightState.AMBER );
trafficLightsAtBigJunction.setState( TrafficLightState.RED );
trafficLightsAtBigJunction.setState( TrafficLightState.RED_AMBER );
:
:
:
The crux is, using the state pattern to implement the state machine, if we do
TrafficLight trafficLightsAtBigJunction = new TrafficLight(); // state = RED
trafficLightsAtBigJunction.setState( TrafficLightState.GREEN ); // Exception!!!!!
an exception is thrown ( by our design ) because it's an illegal state move. That's what we want. Everything is good with the world.
However if we then persist the traffic light and it happens to be at state = AMBER say then there appears to be a problem. When our user comes back 3 days later to watch the awesome traffic light simulation it is restored from the current state in some ( who cares ) persistent store.
How do we get the traffic light instance to be in state AMBER without breaking the encapsulation that the state pattern provides here?
There appears to be 2 choices:-
(1) Create a new instance and run through the relevant states
(2) Provide a special method to set the state to whatever we want that, by convention, is only used after reading from some persistence store. e.g.
trafficLight.setStateAfterReadingFromPersistanceSource( AMBER );
Issue with (1) as I see it is that there may very well be side effects I don't want when running through the states, plus the logic could be quite complex depending on the state machine
Issue with (2) is obviously it only works by convention so could introduce a bug without knowing when incorrectly used. More importantly it pretty much breaks all your nice pattern encapsulating which is what you wanted in the first place.
The question is persistence technology agnostic - same issue with ORM, Files, serialisation etc
I'm assuming there is a solution here but I can't think of one myself and my googling skills have not been sufficient.
Any pointers would be great.
Implementing a state machine by representing states and transitions as objects is certainly possible, but those objects require initialization (which appears to be your problem) and take the precious RAM.
However, there is also a completely different way of implementing state machines as pure code. This has so many advantages that I would never go back to the "state machine as data" method.
For a specific example, the DDJ article "UML Statecharts at $10.99" at http://www.drdobbs.com/architecture-and-design/uml-statecharts-at-1099/188101799 shows exactly how to implement a Pedestrian LIght CONtrolled (PELICAN) crossing as a hierarchical state machine.
This example is coded in C for a low-end microcontroller. If you are interested in C++ implementation, you can take a look at the open source QP/C++ framework available from SourceForge.net at https://sourceforge.net/projects/qpc/files/QP_C%2B%2B/
The way I see it, you want two ways to manipulate the state:
1) Transition from this state to another state, performing all side effects of this transition, throwing exception if illegal, etc
2) Set the machine directly to a state/set of internal values. Do nothing else.
You should persist everything that describes the FSM's internal state and have two methods, one that does the former, one that does the latter.
The latter will be used when setting up or when unpersisting. It's also much simpler to code since it'll just be transferring values into variables without worrying about what else needs to happen.
The former will be used during simulation.
The simplest approach may just be to pass the initial state as a constructor parameter - it's only your convention that the system starts with all lights as red.
Another approach would be to make the function which pulls data from the store a friend or member ( depending whether you're using operator>> to read it or something else ). This gives you the option to either transition to a state as per your example, or read an initial state from a store. There isn't much ambiguity as to what is happening, and it's up to the FSM to pull its state and whatever else it needs to and from the store when persisting.
For the short answer I agree with Pete that, in this simplistic example, you can pass it as
a constructor arg.
But I honestly think the entire design is flawed. I would think this should be modeled using the standard State design pattern. Something like this:
class TrafficLight
{
private TrafficLightState _lightState;
TrafficLight(initialState)
{
// utilize lookup table or factory-method to assign _lightState with the correct TrafficLightState subclass
}
// UI can use this to identify/render the appropriate color
Color getColorCode()
{
return _lightState.getColorCode();
}
// UI uses this to know when to signal the next light change (each color can have different duration)
int getDuration()
{
return _lightState.getDuration();
}
// assuming the UI has a timer that is set based on the current light's duration
void changeLight()
{
TrafficLightState nextState = _lightState.onChangeLight();
_lightState = nextState;
}
}
abstract class TrafficLightState
{
abstract Color getColorCode()
abstract TrafficLightState onChangeLight()
abstract int getDuration()
}
class RedLight : TrafficLightState
{
Color getColorCode()
{
return Color.Red;
}
TrafficLightState onChangeLight()
{
return new RedAmberLight();
}
int getDuration()
{
return 30;
}
}
class RedAmberLight : TrafficLightState
{
Color getColorCode()
{
return Color.Orange;
}
TrafficLightState onChangeLight()
{
return new GreenLight();
}
int getDuration()
{
return 10;
}
}
class GreenLight: TrafficLightState
{
Color getColorCode()
{
return Color.Green;
}
TrafficLightState onChangeLight()
{
return new AmberLight();
}
int getDuration()
{
return 25;
}
}
class AmberLight: TrafficLightState
{
Color getColorCode()
{
return Color.Yellow;
}
TrafficLightState onChangeLight()
{
return new RedLight();
}
int getDuration()
{
return 10;
}
}
State machines should not have an explicitly-exposed "change state" method that is used to transition in normal operations. Instead, think of them as having stimuli that allow the state machine to transition its own state. In this example, the stimuli was very simple but normally you'd have a bank of possible inputs that can cause a state transition. But with proper encapsulation, the caller need not be overly aware of the details.