is there a name for this conditional-checking technique? - terminology

so, theres a technique I use in a fair amount of programming languages and projects; and I'm wondering if it has a general, language-agnostic "official" term to describe it.
basically, I nicknamed it "trip switch checking." Its where if you need to check that several variables have specific values, possibly of different types, you first set a boolean to "false" and then in either a loop or several if statements, you check what you need to by setting the boolean to true if any of the other variables don't meet your requirements.
I call it trip-switching because the boolean remains false if the "switch" isn't "tripped," using an analogy from a common safety mechanism on industrial machinery where if something moves too far or gets too close or etc. a physical switch is actually bumped into and it shuts the whole thing down. the idea is not to switch it back off until the obstruction is cleared- the machine cant turn itself back on automatically.
pseudocode example, a function that returns true if the trip switch wasn't hit:
function tripswitchcheck()
{
boolean tripswitch = false
if(idontnwantthis == true)
{
tripswitch = true
}
if(iwantthis == false)
{
tripswitch = true
}
//...etc...basically do stuff to check stuff. if any values are undesired, true the tripswitch.
return !tripswitch
}
It may be bad practice depending on the language and nature of the project, but it works, and that's outside of the scope of this question.

First of all, why would you not just have a positive flag in that example:
function tripswitchcheck()
{
boolean success = true;
if(idontnwantthis == true)
{
success = false;
}
if(iwantthis == false)
{
success = false;
}
//...etc...basically do stuff to check stuff. if any values are undesired, falsify success
return success
}
Secondly, why check the conditions if you already know you have failure. Say that we don't have a forward goto in the language, or else, or early returns (or we don't want to return because something else is done based on the success flag before returning):
function tripswitchcheck()
{
boolean success = true;
if(idontnwantthis == true)
{
success = false;
}
if(success && iwantthis == false) // if success is false, fall through
{
success = false;
}
if(success && !othercondition()) // likewise
{
success = false;
}
//...etc...
return success
}
There are reasons not to use else if some of the conditions make use of earlier results.
Anyway, this just comes from basic logic and scientific reasoning: we have a hypothesis and look for reasons why it is not true.
The name for it is perhaps "single exit rule" and such: the function exits through a single return statement.

Related

Term for an if condition that is always true

What to call an if where the condition is always true, like below?
if (functionThatAlwaysReturnsTrue()) {
// Some code that always runs
}
This is for a commit message, explaining when and why this bit of code came to be.
In the world of logic, these are known as tautologies.
In logic, a tautology (from the Greek word ταυτολογία) is a formula that is true in every possible interpretation.
For example, the function...
function isHungry() {
return true;
}
Will always evaluate to true, and would be considered a tautological function.

ESLint warning ES6 consistent-return rule

I get an ESLint warning:
Expected to return a value art the end of arrow function ( consistent-return)
errors.details.forEach((error) => {
const errorExists = find(errObj, (item) => { // <== ESLint warning
if (item && item.field === error.path && item.location === location) {
item.messages.push(error.message);
item.types.push(error.type);
return item;
}
});
if (!errorExists) {
errObj.push({
field: error.path,
location: error.location,
messages: [error.message],
types: [error.type]
});
}
});
However if I insert a return
const errorExists = find(errObj, (item) => { // <== ESLint warning
if (item && item.field === error.path && item.location === location) {
item.messages.push(error.message);
item.types.push(error.type);
return item;
}
return; // <== inserted return
});
Then no more warning on this line , but then I get 2 warnings on the inserted return ...
Arrow function expected a return value (consistently-return)
Unnecessary return statement (no-useless-return)
I don't see how to solve correctly this issue ..
any feedback welcome
http://eslint.org/docs/rules/consistent-return says:
This rule requires return statements to either always or never specify values.
When your if-condition is not met, the arrow function will terminate without encountering a return statement, which violates this rule. Your second version violates this rule because your second return does not specify a value, contrary to the first return. The second warning tells you that your additional return statement is redundant.
To make the linter happy, you probably should think about what to properly return from the arrow-function if the condition is not met. I do not know what your find function does exactly, but if it behaves similar to Array.prototype.find you might want to return false at the end of the arrow function. If you need to return undefined in that case, this paragraph from the same page applies:
When Not To Use It
If you want to allow functions to have different return behavior depending on code branching, then it is safe to disable this rule.
EDIT: I previously wrote to have a look at the option treatUndefinedAsUnspecified, but looks like either setting will not help if you need to return undefined in just one of the branches.
the return is correctly inserted, however its value should be given ...
return false;
is the correct value

Windows Phone speech recognition - words that are not in grammar

consider a grammar like this ; speech.Recognizer.Grammars.AddGrammarFromList("answer",new string[] { "Go.","no" });
When I say something else that are not in grammar, she says "sorry didnt catch" and then tries to start it again. Same goes for null input.
What I want is that it should only recognize the words in grammar and for everything else it should just pass the recognition. I don't want to see anything like "sorry didnt catch" and second time recognotion. Any idea ? thanks.
Edit : with try-catch I can avoid from second time recognotion if the word is unknown but now it's waiting too long on "sorry didnt catch" part.
try
{
SpeechRecognizerUI speech = new SpeechRecognizerUI();
speech.Settings.ReadoutEnabled = false;
speech.Settings.ShowConfirmation = false;
speech.Recognizer.Settings.InitialSilenceTimeout = System.TimeSpan.FromSeconds(0.8);
speech.Recognizer.Grammars.AddGrammarFromList("answer", new string[] { "Go.", "no" });
SpeechRecognitionUIResult result = await speech.RecognizeWithUIAsync();
if (result.RecognitionResult.Text == "Go.") { .... }
}
catch
{
..... }
In my opinion, you must build your own UI to avoid this. So you should use SpeechRecognizer and then you can handle the input as you want.
In my case I even created two SpeechRecognizer, on with own Wordlist, the other one with default dictionary. It works like a charm, but I couldn't get it to work with SpeechRecognizerUI.

Checking whether a checkbox is checked

I have not found any inbuilt function for checking whether a checkbox is set true or false,
isChecked() is not available is apps-script (if i am right).
Any idea on how to find it or we shall have a value change handler to count the number of times the value changed and find if it is checked or not?
You should assign your checkbox a name so that you can retrieve its value in a handler function with e.parameter.checkboxname : this value is boolean.
var chkmode = app.createCheckBox("description").setName("chk1").setId("chk1")
with the ID you can modify its state from the handler function (or from any other) if necessary (getElementbyId())
note that the handler can be on the checkbox itself (a change handler) or on any other element in the UI, depending on your needs.
I might be wrong, however I believe there is a problem with the checkBox status, even though its status looks like boolean, it doesn't behave like boolean but like string
if you print in a spreadsheet e.parameter.myCheckBox you will get TRUE or FALSE
if you print in a spreadsheet e.parameter you will get the whole object and see myCheckBox=true or myCheckBox=false
however, if (e.parameter.myCheckBox) will always return True
the workaround I am using is: if (e.parameter.myCheckBox == "true") will return the actual myCheckBox status
Just in case, I am opening a new ticket in the issue tracker
I hope this would help you
ps. confirmed with Google, e.parameter.myCheckBox is a string, not a boolean
if you want to use it as boolean it would be like (e.parameter.myCheckBox == "true")
var handler = app.createServerClickHandler('tellStatus');
and then (as example showing it in a label)
function tellStatus(e){
var app = UiApp.getActiveApplication();
app.getElementById('yourStatusLabel').setText('Checkbox checked: ' + e.parameter.yourCheckbox)
return app;
}
You should use handler function look like below.
I found example from https://sites.google.com/site/scriptsexamples/learn-by-example/uiapp-examples-code-snippets/check-box
if(e.parameter['checkbox_isChecked_'] == 'true'){
itemsSelected+= e.parameter['checkbox_value_']+',';
}

Correctly handling custom messages using WTL

I've written a multi-threaded WTL util to stress test an in-house service.
Comms threads signal to the main thread that they've quit, so the main thread can delete their corresponding object.
They make the signal as so:
PostThreadMessage(m_dwParentThreadId, WM_THREADQUIT, 1, m_dwNetThreadId);
My problem is how to deal with the custom message I've defined .
WM_THREADQUIT is #define'd as WM_USER + 10
I wanted to use an entry in the message map to call a handler, e.g.:
BEGIN_MSG_MAP(CMainDlg)
MESSAGE_HANDLER( WM_INITDIALOG, OnInitDialog )
MESSAGE_HANDLER( WM_THREADQUIT, OnThreadQuit )
...
REFLECT_NOTIFICATIONS()
END_MSG_MAP()
However, OnThreadQuit is never called.
The only way I can handle it is by calling the handler explicitly in PreTranslateMessage:
virtual BOOL CMainDlg::PreTranslateMessage(MSG* pMsg)
{
if( pMsg->message == WM_THREADQUIT )
{
BOOL blHandled;
OnThreadQuit(pMsg->message, pMsg->wParam, pMsg->lParam, blHandled);
return TRUE;
}
return CWindow::IsDialogMessage(pMsg);
}
I'm sure this isn't the correct way to do it ...
I'd love to know the correct way- can someone help!?
As stated in the doc Messages sent by PostThreadMessage are not associated with a window. As a general rule, messages that are not associated with a window cannot be dispatched by the DispatchMessage function.
Set your HWND in pMsg->hwnd and ::DispatchMessage() will deliver it to your WndProc:
virtual BOOL CMainDlg::PreTranslateMessage(MSG* pMsg)
{
if (pMsg->message == WM_THREADQUIT)
{
pMsg->hwnd = m_hWnd;
return FALSE; // continue processing
}
return CWindow::IsDialogMessage(pMsg);
}