I have a method DoCleanUp(), which will ask user to proceed and then clear current workspace. It will return if user choose to cancel this process.
My question is, which signature is best to indicate a "cancel"?
bool DoCleanUp(); // return false to indicate canceled.
bool DoCleanUp(); // return true to indicate this method should be canceled.
void DoCleanUp(bool& cancel); // check parameter 'cancel' to see if this method was canceled.
UPDATE: As for the language, it's C++\CLI or C#.
UPDATE2: Now suppose I have to save a file in the DoCleanUp method. I'll prompt a dialog ask user whether to save/not save/cancel the file. Based on the answers, here is what I came up:
void DoCleanUp();
DialogResult AskToSaveFile(); // return yes/no/cancel
void DoCleanUp( bool saveFile );
Usage:
void DoCleanUp()
{
DialogResult result = AskToSaveFile();
if( result == DialogResult::Cancel ) return;
bool saveFile = (result == DialogResult::Yes) ? true : false;
DoCleanUp( saveFile );
}
Then by calling DoCleanUp(), you know user will have the opportunity to cancel;
By calling DoCleanUp(bool saveFile), you can control whether to save file without asking user.
Is that looks better?
This is a classic single responsibility problem.
The reason that you are unsure about the signature is that the method is doing 2 things.
I would create 2 methods:
bool CheckIfTheUserWantsToCancel()
void DoCleanUp()
EDIT
Based on the comments and edits to the question I would create a 3rd method:
void SaveFile()
The DoCleanUp would then first call CheckIfTheUserWantsToCancel, and then if not cancelled would call SaveFile.
IMHO this is much better than trying to remember that DoCleanUp with parameter false will save the file without asking the user, or was it the other way around?
Without more details I would say answer 1 is the best IMHO. Third is rather ugly since it requires more code for calling.
But maybe consider rewriting code to this
void CleanUp() {
switch (AskUser()) {
case ButtonOk: CleanUpDesk(); break;
case ButtonNo: break;
default:
case ButtonCancel: CancelCleanUpDesk(); break;
}
}
This seems to in the spirit of single responsibility. My code somehow breaks your problem into two steps: asking user and performing action.
I would use your 1 version.
bool DoCleanUp(); // return false to indicate canceled.
The assumption is, that it returns true when the cleanup is done. Returning false would indicate a 'Error' state. It might even make sense to return an int. In this case the convention usually is that 0 represents success and everything else is an error code.
Regardless of what you decide, document what your return values mean!
The confusing bit is the calling it DoSomething(), when it might not do anything. How about
if (QueryCleanup()) // boolean
DoCleanup(); // void
More verbose but clearer, even without seeing the declaration.
You should not use a boolean for statuses (or status messages). Create an Enum:
public Enum CleanupStatus
{
Ok = 0,
Cancel
}
This way it is more clear what the return value is ... and if you need to add more statuses, you can.
(This is all from Code Complete 2, you should read it if you haven't yet.)
You have two requests basically. The outer request is to create a new workspace. The inner request is to save the current workspace. You want to return true if the outer request continues and false if the outer request is aborted. The action of the inner request is not important to the outer request and so should be some kind of delegate/functor/closure.
Make a class to genericize this:
class YesNoCancel {
string question; // question to ask the user about the inner state
delegate doit; // function to call to
delegate dontdoit;
public:
YesNoCancel(string question, delegate doit, delegate dontdoit = null) {...}
bool run() {
switch (AskUser(question)) {
case ANSWER_YES: doit(); return true;
case ANSWER_NO: return true;
case ANSWER_CANCEL: if (dontdoit) dontdoit(); return false;
};
//usage
void NewWorkspace() {
if (m_workspace) {
YesNoCancel ync("Save current workspace?", saveworkspace);
if (!ync.run()) return;
}
// new workspace code
}
void CloseApp() {
YesNoCancel ync("Save current workspace?", saveworkspace);
if (ync.run()) ExitApplication();
}
I believe option three gives the most clarity. When you have the bool as a return type it is not immediately clear what it is used for.
I usually go with
bool DoCleanUp(); // Returns true if cancel
but mostly it depends on whether the calling code looks like this:
if (DoCleanUp()) {
// Do cancel up code
}
or:
if (DoCleanUp()) {
// Do non-cancel post clean up code
}
Basically I try to make my tests not have to use a ! or language equivilent as I find it hard to see.
I definitely would not do number 3.
I prefer the third signature, only because by looking at it (without any extra documentation), I can tell more about what the method does. I would call the argument something more explicit, like processCancelled, though.
Related
Note for the readers: this question is specific for Codename One only.
I'm developing an app that needs some initial data from a server to run properly. The first shown Form doesn't need this data and there is also a splash screen on the first run, so if the Internet connection is good there is enought time to retrive the data... but the Internet connection can be slow or absent.
I have in the init a call to this method:
private void getStartData() {
Runnable getBootData = () -> {
if (serverAPI.getSomething() && serverAPI.getXXX() && ...) {
isAllDataFetched = true;
} else {
Log.p("Connection ERROR in fetching initial data");
}
};
EasyThread appInfo = EasyThread.start("APPINFO");
appInfo.run(getBootData);
}
Each serverAPI method in this example is a synchronous method that return true if success, false otherwise. My question is how to change this EasyThread to repeat again all the calls to (serverAPI.getSomething() && serverAPI.getXXX() && ...) after one second if the result is false, and again after another second and so on, until the result is true.
I don't want to shown an error or an alert to the user: I'll show an alert only if the static boolean isAllDataFetched is false when the requested data is strictly necessary.
I tried to read carefully the documentation of EasyThread and of Runnable, but I didn't understand how to handle this use case.
Since this is a thread you could easily use Thread.sleep(1000) or more simply Util.sleep(1000) which just swallows the InterruptedException. So something like this would work:
while(!isAllDataFetched) {
if (serverAPI.getSomething() && serverAPI.getXXX() && ...) {
isAllDataFetched = true;
} else {
Log.p("Connection ERROR in fetching initial data");
Util.sleep(1000);
}
}
How can I achieve a loop like this:
foobar.each(function (model, j) {
// asynchrounous call etc. {in here bool get set to true}
// outside all asynchronous calls
// wait till bool is true, without stopping anything else except the loop to the top of
the _.each
})
I asked a similar question yesterday. But it got marked as a duplicate when it wasn't the same case. Their solution did not achieve the same thing. Also generator functions were suggested which looked like it would work. But I can't use them with ecmascript 5
I've tried busy loops and set time out but they don't seem to work either
I've also tried this:
goto();
function goto() {
if (foo === true) {
//return true; /*I've tried with and without the return because the loops
doesn't need a return*/
} else {
goto();
}
}
What happens with the goto() method is it breaks. Giving me the right results for the first iterations then execution seems to stop altogether. 'foo' always gets set to true in normal execution though.
What you could do is implement a foreach yourself, where you execute your condition, and then on success callback go to the next item (but meanwhile the rest of the code will keep running.
var iteration = 0 //count the iteration of your asynchronous process
//start looping
loop(iteration)
function loop(iteration){
var model = foobar[iteration];
//exit your loop when all iterations have finished (assuming all foobar items are not undefined)
if (foobar[iteration] === undefined){
return;
}
//do what you want
//on success callback
iteration++;
loop(iteration);
//end success callback
}
Suppose that I have a telephony application. I have a feature that I want to try calling an array of users one by one and break the sequence whenever one of the users accepts call, or when the complete operation is cancelled.
I will try to simplify it like this in pseudocode:
for(user in users) {
result = callUserCommand(user);
if(result == "accepted" || result == "cancelled") {
break;
}
}
Here, the callUserCommand is a RACCommand that needs to be async. And it can actually have three return values: "accepted", "cancelled", "declined".
Accepted and Cancelled will break the sequence of operations and won't execute the rest.
Declined, should continue with the execution of the rest of the sequence.
I tried with something like the following, but really couldn't accomplish exactly the thing I described above.
RACSignal *signal = [RACSignal concat:[users.rac_sequence map:^(User * user) {
return [self.callUserCommand execute:user];
}]];
[signal subscribeNext:^(id x) {
} error:^(NSError *error) {
} completed:^{
}];
If I understood correctly you would like to execute the sequence one by one until one of the call gets accepted or cancelled.
Maybe you could give takeUntil or takeWhile a try. I would write this scenario with RAC like this:
NSArray* users = #[#"decline", #"decline", #"decline", #"accept", #"decline"];
[[[[[users.rac_sequence signal]
flattenMap:^RACStream *(NSString* userAction) {
NSLog(#"Calling user (who will %#):", userAction);
// return async call signal here
return [RACSignal return:userAction];
}]
takeWhileBlock:^BOOL(NSString* resultOfCall) {
return [resultOfCall isEqualToString:#"decline"];
}]
doCompleted:^{
NSLog(#"Terminated");
}]
subscribeNext:^(NSString* userAction) {
NSLog(#"User action: %#", userAction);
}];
In the sample code above the last user who would decline the call won't be called.
I have a method as follows
public class ClientClass {
public void clientMethod() {
while(true){
doSomethings.....
}
}
}
I am trying to test using mockito. I am able to make the call to clientMethod, but since there is a while(true) inside clientMethod, the call never returns and I never reach to my assert statements which (of course) occur after clientMethod() invocation.
Is there a way to stop the loop after one loop iteration from my test case?
Technicaly you can't break the infinite loop in test without throwing an exception from inside it. If there is something inside the loop you can mock, then it may produce an exception for you.
When you're finding yourself in situation like this, when awkward workarounds are necessary for testing, then it's time to stop and think about the design. Non-testable code is generaly ill-maintainable and not very self-explanatory. So my advice would be to get rid of infinite loop and introduce an appropriate loop condition. After all, no application will live forever.
If you're still convinced that endless loop is the best way to go here, then you can perform a slight decomposition to make things more testable:
public class ClientClass {
// call me in production code
public void clientMethod() {
while(true){
doSomethings();
}
}
// call me in tests
void doSomethings(){
// loop logic
}
}
This was a source of a little frustration to me... because I like to start off the most sophisticated of GUI apps with a console handler.
The language I'm using here is Groovy, which is a sort of marvellous extension of Java, and which can be sort of mixed in with plain old Java.
class ConsoleHandler {
def loopCount = 0
def maxLoopCount = 100000
void loop() {
while( ! endConditionMet() ){
// ... do something
}
}
boolean endConditionMet() {
loopCount++
loopCount > maxLoopCount // NB no "return" needed!
}
static void main( args ) {
new ConsoleHandler().loop()
}
}
... in a testing class (also in Groovy) you can then go
import org.junit.contrib.java.lang.system.SystemOutRule
import org.junit.contrib.java.lang.system.
TextFromStandardInputStream.emptyStandardInputStream
import static org.assertj.core.api.Assertions.assertThat
import org.junit.Rule
import static org.mockito.Mockito.*
class XXTests {
#Rule
public SystemOutRule systemOutRule = new SystemOutRule().enableLog()
#Rule
public TextFromStandardInputStream systemInMock = emptyStandardInputStream()
ConsoleHandler spyConsoleHandler = spy(new ConsoleHandler())
#Test
void readInShouldFollowedByAnother() {
spyConsoleHandler.setMaxLoopCount 10
systemInMock.provideLines( 'blah', 'boggle')
spyConsoleHandler.loop()
assertThat( systemOutRule.getLog() ).containsIgnoringCase( 'blah' )
assertThat( systemOutRule.getLog() ).containsIgnoringCase( 'boggle' )
The beautiful thing that's happening here is that simply by declaring maxLoopCount the language automatically creates two methods: getMaxLoopCount and setMaxLoopCount (and you don't even have to bother with brackets).
Of course the next test would be "loop must exit if a user enters Q" or whatever... but the point about TDD is that you want this to FAIL initially!
The above can be replicated using plain old Java, if you must: you have to create your own setXXX method of course.
I got stuck in this because I was calling same method from inside the method by mistake.
public OrderEntity createNewOrder(NewDepositRequest request, String userId) {
return createNewOrder(request, userId);
}
I have a property in my controller that I would like to test:
public List<SelectOption> exampleProperty {
get {
//Do something;
}
}
I am not sure how to cover this code in my test class. Any ideas?
There is direct way, just invoke the property from test method
List<SelectOption> temp = obj.method;
You may need to directly test your properties, especially if you use lazy initialization - a smart pattern for making code efficient and readable.
Here's a list example of this pattern:
Integer[] lotteryNumbers {
get {
if (lotteryNumbers == null) {
lotteryNumbers = new Integer[]{};
}
return lotteryNumbers;
}
set;
}
If you wanted full coverage of the pattern (which may be a good idea while you're getting used to it), you would need to do something like the following:
static testMethod void lotteryNumberFactoryText() {
// test the null case
System.assert(lotteryNumbers.size() == 0);
Integer[] luckyNumbers = new Integer[]{33,8};
lotteryNumbers.addAll(luckyNumbers);
// test the not null case
System.assert(lotteryNumbers == luckyNumbers);
}
First off, do you really want to have an attribute named "method"? Seems a helluva confusing. Anyway, to cover the code, just call
someObject.get(method);
But code coverage should be a side effect of writing good tests - not the goal. You should think about what the code is supposed to do, and write tests to check (i.e. assert) that it is working.