tslint: How to make sure that a variable is not undefined? - tslint

As per the following screenshot, the TsLint is claiming that a variable might be undefined which is not assignable to a function's parameter.
But I have already checked and make sure that it's not undefined above passing it as the function's parameter.
Why does TsLint is still claiming that the variable might be undefined?
I can dismiss that warning by changing the code to:
clearTimeout(saveDraftTimer.current as unknown as number)
but it looks ugly, any better suggestion?
const saveDraftTimer = useRef<number | undefined>(undefined);

Related

Recursive variable declaration

I have just seen this black magic in folly/ManualExecutor.h
TimePoint now_ = now_.min();
After I grep'ed the whole library source code, I haven't seen a definition of the variable now_ anywhere else than here. What's happening here? Is this effectively some sort recursive variable declaration?
That code is most likely equal to this:
TimePoint now_ = TimePoint::min();
That means, min() is a static method, and calling it using an instance is same as calling it like this, the instance is used just for determining the type. No black magic involved, that's just two syntaxes for doing the same thing.
As to why the code in question compiles: now_ is already declared by the left side of the line, so when it's used for initialization on the right side, compiler already knows its type and is able to call the static method. Trying to call non-static method should give an error (see comment of #BenVoigt below).
As demonstrated by the fact that you had to write this question, the syntax in the question is not the most clear. It may be tempting if type name long, and is perhaps justifiable in member variable declarations with initializer (which the question code is). In code inside functions, auto is better way to reduce repetition.
Digging into the code shows that TimePoint is an alias for chrono::steady_clock::time_point, where min() is indeed a static method that returns the minimum allowable duration:
http://en.cppreference.com/w/cpp/chrono/time_point/min

PasteboardPutItemFlavor Null passed to a callee that requires a non-null argument

I know there are plenty of questions asking about how to solve "Null passed to a callee that requires a non-null argument", but I really can't seem to find a solution for my problem.
I use a function called PasteboardPutItemFlavor in my code. It compiles alright if I set the deploy target to 10.12 built against macSDK10.12. After I set the deploy target to 10.8, but still compile it against macSDK10.12, I got an error on PasteboardPutItemFlavor call. The error message is "Null passed to a callee that requires a non-null argument". What does this error mean? kPasteboardFlavorNoFlags is defined as 0, changing to other constant value doesn't change anything.
How do I solve this error with 10.8 as deploy target and compile against 10.12?
PasteboardPutItemFlavor(
m_pboard,
nullptr,
flavorType,
dataRef,
kPasteboardFlavorNoFlags);
The function declaration is
OSStatus PasteboardPutItemFlavor(PasteboardRef inPasteboard, PasteboardItemID inItem, CFStringRef inFlavorType, CFDataRef inData, PasteboardFlavorFlags inFlags);
I looked into the header file from 10.12 SDK. The header file is warped with nonnull macro. So any pointer with that macro would be declared as nonnull. In my case is the nullptr parameter. I simply create a local variable and set to 0 then pass it in PasteboardPutItemFlavor. That solves the error.

"Expression Too Complex" error on simple property assignment

I'm getting (fairly reguarly) an "Error 16: Expression too complex" runtime error on a simple assigment to a property from a class.
public property PropertyName() as double
PropertyName = mvarPropertyName
end property
The debug window points to the crash being on the assignment line in the above code.
Some inital reading here and elsewhere suggested that it was related to the line calling the property. However, that now looks like this:
variableName = ObjectName.PropertyName
And all arithmetic is done with variableName.
Even more oddly, if I just hit debug, then resume/F5 immediatley, everything is fine.
Trying to use the error handling code to do this doesn't seem to have worked however.
Any ideas what is causing this error?
Stop using Not (Not MyArray) to test for uninitialized arrays. This uses a bug in the compiler that has a known side effect of destabilizing the run-time leading to "Expression too complex" on random places.
VB6 - Returning/Detecting Empty Arrays is fairly complete thread on different ways to test for empty and uninitialized arrays.
A string expression is too complicated. Strings not assigned to variables (such as those returned by functions) are assigned to temporary locations during string expression evaluation. Having a large number of these strings can cause this error. Try assigning these strings to variables and use the variables in the expression instead.

Why doesn't the Go compiler treat non-declared variable as error?

I've been writing a test program to assist in learning Go. While doing so, I've encountered a few instances where I thought the compiler should have detected an error. I've encountered another similar situation, so I thought I should ask why this situation is not treated as an error.
Example situation :
if oError = rwfile.WriteLines(asParams, sParamsFilename); oError != nil {
fmt.Printf("Error on write to file Params. Error = %s\n", oError)
} else {
println("Params file write OK")
}
In the example above, whether or not the variable "oError" is declared, the compiler does not indicate an error. It also works if the line contains the following when the variable is not declared (as expected):
if oError := rwfile.WriteLines(asParams, sParamsFilename); oError != nil {
If I declare the variable "oError", then ":=" does not work (as expected).
"rwfile" is a package that I have written, and the function in question starts as follows:
func WriteLines(asBuff []string, sFilename string) error { // write text file
If I create an error with the write of the file, and use "=" without declaring the variable "oError", the program works correctly and detects the non-nil "oError" variable.
So, why is use of "=" in the above not treated as an error when oError is not declared a variable?
The Go version is go1.1.2 Windows/386.
This means that you have an variable named oError elsewhere in the package. (Note that this variable need not be in the same file; it could be in a different file with the same package clause.) So, when you use oError = ..., you're assigning a value to that package variable, and when you use oError := ..., you're declaring a local variable that hides the package variable. (Per the specification, "An identifier declared in a block may be redeclared in an inner block. While the identifier of the inner declaration is in scope, it denotes the entity declared by the inner declaration." [link])
If you try a different identifier, a unique one, you should see that the compiler indeed complains.
It's unrelated to the actual question, but `go fmt` can really help with tracking errant stuff in a big program.
Also, following the style guidelines really helps: use terse code styles (no hungarian variable names! took me ages to get used to short names) and short files: a 2Kloc file is probably too big. It's massively worth taking a wander through the standard library source code to see what good Go code looks like

Best practice for validating Input variables in Boolean functions

At work we often use functions returning a BOOLEAN where the BOOLEAN represents a logical statement and not whether the operation of the function was successfully or not
e.g. BOOLEAN HaseThisValueBeCountedAlready (Value)
When validating the input in this function what would be the best way proceed if invalid input was detected. Some people think to just return FALSE but in my opinion that would just hide the fact that something is wrong and the Caller might proceed doing something with the value not knowing that the answer doesn't make sense.
The function might be globally accessible so it feels a bit weird assuming the caller will validate the input.
Any ideas?
In general, for invalid input that doesn't enable the functions to provide the service/answer, you need to raise an exception.
This way, the guy asking the "question" to the function knows he's not "formulating" it the right way.
if its a value that need to be read periodically , you can assign the output to a global variable ,if it valid or dont update global variable if the input is invalid , so the global variable stays with the previous valid value.
this way , each function need this value , use the global variable with 100% that is valid value.

Resources