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

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"!

Related

Kotlin - Here Maps - Get address out of callback function

I am attempting to get the address out of the callback function. I have been reading the documentation for CallBacks and some posts but still don't get why this is not working, as at the moment of returning the 'address' variable the callback has already finished.
private fun getAddressForCoordinates(geoCoordinates: GeoCoordinates):String {
address = "unchanged"
val maxItems = 1
val reverseGeocodingOptions = SearchOptions(LanguageCode.EN_GB, maxItems)
searchEngine.search(geoCoordinates, reverseGeocodingOptions, addressSearchCallback)
return address
}
private val addressSearchCallback =
SearchCallback { searchError, list ->
if (searchError != null) {
//showDialog("Reverse geocoding", "Error: $searchError")
Toast.makeText(context, "Error: $searchError", Toast.LENGTH_LONG).show()
return#SearchCallback
}
Toast.makeText(
context,
"Reverse geocoded address:" + list!![0].address.addressText,
Toast.LENGTH_LONG
).show()
address = list[0].address.addressText
}
From your code and comment I assume you are not familiar with the concept of asynchronous execution. That concept was well described here. I'll quote the main point:
When you execute something synchronously, you wait for it to finish
before moving on to another task. When you execute something
asynchronously, you can move on to another task before it finishes.
The fact that search() requires providing a callback and it doesn't simply return search results, is a good indication that it is most probably asynchronous. Invoking it is like saying: "Search for the data in the background and let me know when you have it. This is my email address - please send me my results there". Where email address is your callback. Invoking search() method does not block execution of your code, it does not wait for results - it only schedules searching and returns almost immediately.
Asynchronous processing is usually more tricky than a regular, synchronous code, but in many cases it is more efficient. In your case you can either try to "convert" original async API of the library to sync API that your code expects - but this is not recommended approach. Or you can redesign your code, so it will work asynchronously. For example, instead of doing this:
fun yourMethodThatNeedsAddress() {
val address = getAddressForCoordinates()
doSomethingWithAddress(address)
}
You need to do this:
fun yourMethodThatNeedsAddress() {
scheduleGetAddressForCoordinates() // renamed getAddressForCoordinates()
}
fun addressSearchCallback() {
...
doSomethingWithAddress(address)
}
So, whatever you planned to do with the acquired address, you can't do this straight after you started searching. You need to wait for a callback and then continue with processing of your address from there.
The SearchEngine from the 4.x HERE SDK needs an online connection as it is fetching results from a remote backend. This may take a few milliseconds, depending on your network connection. So, whenever you perform a search request, you need to wait until the callback is called:
searchEngine.search(geoCoordinates, reverseGeocodingOptions, addressSearchCallback)
When you call this, you pass addressSearchCallback as parameter. The implementation for addressSearchCallback can look like in your example. It will be called whenever the operation has finished. If the device is offline, then an error will be shown.
Note that the search() method is not returning any results immediately. These are passed to the callback, which happens asynchronously on a background thread. Thus, your application can continue to work without blocking any UI.
Once results are retrieved, the callback will be executed by the HERE SDK on the main thread.
So, if your code needs to do something with the address result, you have to do it inside the onSearchCompleted() method defined by the SearchCallback. If you write it in plain Java without lambda notation, it is more visible: You create a new SearchCallback object and pass it as parameter to the SearchEngine. The SearchEngine stores the object and executes the object's onSearchCompleted() whenever it thinks it's the right time:
private SearchCallback addressSearchCallback = new SearchCallback() {
#Override
public void onSearchCompleted(#Nullable SearchError searchError, #Nullable List<Place> list) {
if (searchError != null) {
showDialog("Reverse geocoding", "Error: " + searchError.toString());
return;
}
// If error is null, list is guaranteed to be not empty.
showDialog("Reverse geocoded address:", list.get(0).getAddress().addressText);
// Here is the place to do something more useful with the Address object ...!
}
};
I took this from this GitHub code snippet. Note that there is also an OfflineSearchEngine, that works without an internet connection, but for some reason it follows the same pattern and executes the task asynchronously.
private void getAddressForCoordinates(GeoCoordinates geoCoordinates) {
int maxItems = 1;
SearchOptions reverseGeocodingOptions = new SearchOptions(LanguageCode.EN_GB, maxItems);
searchEngine.search(geoCoordinates, reverseGeocodingOptions, new SearchCallback() {
#Override
public void onSearchCompleted(#Nullable SearchError searchError, #Nullable List<Place> list) {
if (searchError != null) {
showDialog("Reverse geocoding", "Error: " + searchError.toString());
return;
}
// If error is null, list is guaranteed to be not empty.
showDialog("Reverse geocoded address:", list.get(0).getAddress().addressText);
}
});
}
SearchEngine, a SearchOptions instance needs to be provided to set the desired LanguageCode. It determines the language of the resulting address. Then we can make a call to the engine's search()-method to search online for the address of the passed coordinates. In case of errors, such as when the device is offline, SearchError holds the error cause.
The reverse geocoding response contains either an error or a result: SearchError and the result list can never be null at the same time - or non-null at the same time.
The Address object contained inside each Place instance is a data class that contains multiple String fields describing the address of the raw location, such as country, city, street name, and many more. Consult the API Reference for more details. If you are only interested in receiving a readable address representation, you can access addressText, as shown in the above example. This is a String containing the most relevant address details, including the place's title.
Please refer to following link for detailed documentation on search() function and parameters associated with it.
https://developer.here.com/documentation/android-sdk-explore/4.4.0.2/dev_guide/topics/search.html

How to detect that a thread has started using javassist?

I have to instrument any given code (without directly changing given code ) at the beginning and end of every thread. Simply speaking , how can I print something at entry and exit points of any thread.
How can I do that using javassist ?
Short Answer
You can do this by creating an ExprEditor and use it to modify MethodCalls that match with start and join of thread objects.
(very) Long answer (with code)
Before we start just let me say that you shouldn't be intimidated by the long post, most of it is just code and once you break things down it's pretty easy to understand!
Let's get busy then...
Imagine you have the following dummy code:
public class GuineaPig {
public void test() throws InterruptedException {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < 10; i++)
System.out.println(i);
}
});
t.start();
System.out.println("Sleeping 10 seconds");
Thread.sleep(10 * 1000);
System.out.println("Done joining thread");
t.join();
}
}
When you run this code doing
new GuineaPig().test();
You get an output like (the sleeping system.out may show up in the middle of the count since it runs in the main thread):
Sleeping 10 seconds
0
1
2
3
4
5
6
7
8
9
Done joining thread
Our objective is to create a code injector that will make the output change for the following:
Detected thread starting with id: 10
Sleeping 10 seconds
0
1
2
3
4
5
6
7
8
9
Done joining thread
Detected thread joining with id: 10
We are a bit limited on what we can do, but we are able to inject code and access the thread reference. Hopefully this will be enough for you, if not we can still try to discuss that a bit more.
With all this ideas in mind we create the following injector:
ClassPool classPool = ClassPool.getDefault();
CtClass guineaPigCtClass = classPool.get(GuineaPig.class.getName());
guineaPigCtClass.instrument(new ExprEditor() {
#Override
public void edit(MethodCall m) throws CannotCompileException {
CtMethod method = null;
try {
method = m.getMethod();
} catch (NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String classname = method.getDeclaringClass().getName();
String methodName = method.getName();
if (classname.equals(Thread.class.getName())
&& methodName.equals("start")) {
m.replace("{ System.out.println(\"Detected thread starting with id: \" + ((Thread)$0).getId()); $proceed($$); } ");
} else if (classname.equals(Thread.class.getName())
&& methodName.equals("join")) {
m.replace("{ System.out.println(\"Detected thread joining with id: \" + ((Thread)$0).getId()); $proceed($$); } ");
}
}
});
guineaPigCtClass
.writeFile("<Your root directory with the class files>");
}
So what's happening in this small nifty piece of code? We use an ExprEdit to instrument our GuineaPig class (without doing any harm to it!) and intercept all method calls.
When we intercept a method call, we first check if the declaring class of the method is a Thread class, if that's the case it means we are invoking a method in a Thread object. We then proceed to check if it's one of the two particular methods start and join.
When one of those two cases happen, we use the javassist highlevel API to do a code replacement. The replacement is easy to spot in the code, the actual code provided is where it might be a bit tricky so let's split one of those lines, let's take for example the line that will detect a Thread starting:
{ System.out.println(\"Detected thread starting with id: \" + ((Thread)$0).getId()); $proceed($$); } "
First all the code is inside curly brackets, otherwise javassist won't accept it
Then you have a System.out that references a $0. $0 is a special parameter that can be used in javassist code manipulations and represents the target object of the method call, in this case we know for sure it will be a Thread.
$proceed($$) This probably is the trickiest instruction if you're not familiar with javassist since it's all javassist special sugar and no java at all. $proceed is the way you have to reference the actual method call you are processing and $$ references to the full argument list passed to the method call. In this particular case start and join both will have this list empty, nevertheless I think it's better to keep this information.
You can read more about this special operators in Javassist tutorial, section 4.2 Altering a Method Body (search for MethodCall subsection, sorry there's no anchor for that sub-section)
Finally after all this kung fu we write the bytecode of our ctClass into the class folder (so it overwrites the existing GuinePig.class file) and when we execute it... voila, the output is now what we wanted :-)
Just a final warning, keep in mind that this injector is pretty simple and does not check if the class has already been injected so you can end up with multiple injections.

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.

How would you avoid context/class explosion in this case with 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.

Is it a good idea to inject a TestSettings parameter to a method to make it (Unit or integration) Testable?

Is it a good practice to introduce a TestSettings class in order to provide flexible testing possibilities of a method that has many processes inside?
Maybe not a good example but can be simple: Suppose that I have this method and I want to test its sub-processes:
public void TheBigMethod(myMethodParameters parameter)
{
if(parameter.Condition1)
{
MethodForCondition1("BigMac");
}
if(parameter.Condition2)
{
MethodForCondition2("MilkShake");
}
if(parameter.Condition3)
{
MethodForCondition3("Coke");
}
SomeCommonMethod1('A');
SomeCommonMethod2('B');
SomeCommonMethod3('C');
}
And imagine that I have unit tests for all
void MethodForCondition1 (string s)
void MethodForCondition2 (string s)
void MethodForCondition3 (string s)
void SomeCommonMethod1 (char c)
void SomeCommonMethod2 (char c)
void SomeCommonMethod3 (char c)
And now i want to test the TheBigMethod itself by introducing such test methods with required Asserts in them:
TheBigMethod_MethodForCondition1_TestCaseX_DoesGood
TheBigMethod_MethodForCondition2_TestCaseY_DoesGood
TheBigMethod_MethodForCondition3_TestCaseZ_DoesGood
TheBigMethod_SomeCommonMethod1_TestCaseU_DoesGood
TheBigMethod_SomeCommonMethod2_TestCaseP_DoesGood
TheBigMethod_SomeCommonMethod3_TestCaseQ_DoesGood
So, I want TheBigMethod to be exit-able at some points if it is called by one of my integration tests above.
public void TheBigMethod(myMethodParameters parameter, TestSettings setting)
{
if(parameter.Condition1)
{
MethodForCondition1("BigMac");
if(setting.ExitAfter_MethodForCondition1)
return;
}
if(parameter.Condition2)
{
MethodForCondition2("MilkShake");
if(setting.ExitAfter_MethodForCondition2)
return;
}
if(parameter.Condition3)
{
MethodForCondition3("Coke");
if(setting.ExitAfter_MethodForCondition3)
return;
}
SomeCommonMethod1('A');
if(setting.ExitAfter_SomeCommonMethod1)
return;
SomeCommonMethod2('B');
if(setting.ExitAfter_SomeCommonMethod2)
return;
SomeCommonMethod3('C');
if(setting.ExitAfter_SomeCommonMethod3)
return;
}
Even though it looks it does what I need to introduce a TestSetting parameter can makee the code less readable and does not look nice to have testing logic and the main functionality combined to me.
Can you advise a better design for such cases so that it can replace a TestSetting parameter idea?
thanks
It would (IMO) be a very bad thing to add this TestSetting. An alternative would be to add an interface (or set of interfaces) for MethodForConditionX and SomeCommonMethodX. The test each of the MethodForConditionX & SomeCommonMethodX in isolation and pass in a stub for TheBigMethod which validates that MethodForConditionX is called with value Z.
Edit: You could also make the methods virtual if you don't want to use an interface.
A bit late to the game here, but I would concur that mixing test and production code is a big code smell to be avoided. Big methods in legacy code provide all sorts of issues. I would highly recommend reading Michael Feather's Working Effectively with Legacy Code. It's all about dealing with the myriad of problems encountered in legacy code and how to deal with them.