How to prevent implicit conversion to bool in conditions? - typescript2.0

For example if I do this in Haxe:
var a=33;
if(a)
// do something
it won't let me do that, compilation will fail.
I'll have to convert it to bool explicitly:
var a=33;
if(a!=0)
// do something
It's a great thing for preventing tiny nasty bugs that are hard to find, like accidental assigning with = instead of ==. Is it possible to make TS work this way too? Thank you.

Related

Better style to use bitwise vs comparison in certain cases?

Just wondering if it's better style/more efficient to write code like this:
if (bitset[index] & 1)
{
//do something
}
vs:
if (bitset[index] == 1)
{
//do something
}
Thanks!
None of the above. From the comments, you are talking about something like C++'s std::bitset, whose operator[] returns bool. Normally, boolean values are only operated together with other boolean values, using boolean operations (&&, ||, !, etc). It seems strange to compare it with an object of another type (e.g. the integer 1), or to apply integer arithmetic operations like & | + - etc. The conversion rules of the language let you do it, but it doesn't make as much logical sense.
So the most idiomatic, and also most compact, version would be:
if (bitset[index]) {
// ...
}
If it makes more sense in context to think of the test as an equality comparison, then you can:
if (bitset[index] == true) {
// ...
}
but to most C++ programmers this would simply look redundant.
This is all irrelevant from the standpoint of optimization; any reasonable compiler will realize that they are all equivalent and optimize them all the same. In general, though, if you're doing something common, then you will usually get the best optimization by writing it in the most common and idiomatic way, as that is what the compiler is most likely to handle well.

Why is my "List<String>" being interpreted as "List<String>?"

class Example(private val childrenByParent: HashMap<String, List<String>>) {
private val parents: List<String> = childrenByParent.keys.toList()
fun getChildrenCount(parentPosition: Int): Int {
return childrenByParent[parents[parentPosition]].size
// error, recommends using "?." or "!!"
}
}
The compiler won't let me call size directly but I don't understand why. There are no nullable types in sight.
If I let the compiler infer the type by doing this:
val infer = childrenByParent[parents[parentPosition]]
I can see that it assumes it's a List<String>?
It seems that I'm quite confused about nullability still. Would appreciate some help. I have a feeling I'm doing something incredibly dumb, but after some searching and testing I failed at fixing this.
I would like for this function to not use ?. or even worse, !!. Is it possible? At least, using HashMap and List<String>.
HashMap.get(Object) returns null when there is no element matching the key you provided, so its return type is effectively nullable, regardless of whether the values are or not.
So unfortunately you have to account for the case in which the key doesn't exist, so your choices are either implementing a case where it doesn't, or just declaring it as non-null with !! if you are sure the key exists.
Otherwise you can use HashMap.containsKey(String) to ensure the key exists and then you can be confident that using !! on the value won't result in a NullPointerException.
However as #gidds pointed out, this is not naturally thread-safe without some more work, so it might be best to just handle the case of the key not being in the map. Also I cannot actually think of many cases where you could be sure that key exists, in which a Map is the most appropriate data structure to use.
Also, even though this is not the case here, remember that nullability is just a feature of Kotlin, so when using some classes originally written in Java, whether an element is nullable or not is unknown. The IDE will usually represent this as Type! where the single ! tells you it is a platform type.

What is the difference between not-null checks in Kotlin?

There are some ways to fulfill a null-checking in Kotlin:
1.
if(myVar != null) {
foo(myVar)
}
2.
myVar?.let {
foo(it)
}
3.
myVar?.run {
foo(this)
}
What are the difference between these ways?
Are there any reasons (performance, best practice, code style etc.) why I should prefer on way over the other?
!! is to tell the compiler that I am sure the value of the variable is not null, and if it is null throw a null pointer exception (NPE) where as ?. is to tell the compiler that I am not sure if the value of the variable is null or not, if it is null do not throw any null pointer.
Another way of using a nullable property is safe call operator ?.
This calls the method if the property is not null or returns null if that property is null without throwing an NPE (null pointer exception).
nullableVariable?.someMethodCall()
All three code are behave same null check in operation-wise.
?. is used for chain operations.
bob?.department?.head?.name // if any of the properties in it is null it returns null
To perform a chain operation only for non-null values, you can use the safe call operator together with let
myVar?.let {
foo(it)
}
the above code is good for code style and performance
more details refer Null Safety
The ways 2 and 3 are more idiomatic for Kotlin. Both functions are quite similar. There is little difference with argument passing.
For example, we have a nullable variable:
var canBeNull: String? = null
When you working with T.run you work with extension function calling and you pass this in the closure.
canBeNull?.run {
println(length) // `this` could be omitted
}
When you call T.let you can use it like lambda argument it.
canBeNull?.let {
myString -> println(myString.length) // You could convert `it` to some other name
}
A good article about Kotlin standard functions.
All three are roughly equivalent.
The if case is more like most other languages, and so many developers may find it easier to read.
However, one difference is that the if case will read the value of myVar twice: once for the check, and again when passing it to foo(). That makes a difference, because if myVar is a property (i.e. something that could potentially be changed by another thread), then the compiler will warn that it could have been set to null after the check. If that's a problem (e.g. because foo() expects a non-null parameter), then you'll need to use one of the other cases.
For that reason, the let case has become fairly common practice in Kotlin. (The run case does just about the same thing, but for some reason isn't as popular for this sort of thing. I don't know why.)
Another way around it is to assign myVar to a temporary value, test that, and then use that. That's also more like other languages, but it's more verbose; many people prefer the conciseness of the let case — especially when myVar is actually a complicated expression.
The examples in your question don't show the true reason to decide.
First of all, since you're not using the return value of foo, you should use neither let nor run. Your choice is between also and apply.
Second, since you already have the result you want to null-check in a variable, the difference fades. This is a better motivating example:
complexCall(calculateArg1(), calculateArg2())?.also {
results.add(it)
}
as opposed to
val result = complexCall(calculateArg1(), calculateArg2())
if (result != null) {
results.add(result)
}
The second example declares an identifier, result, which is now available to the rest of the lexical scope, even though you're done with it in just one line.
The first example, on the other hand, keeps everything self-contained and when you go on reading the rest of the code, you are 100% confident that you don't have to keep in mind the meaning of result.
Kotlin have new features with NullPoint-Exception as Compare to Java.
Basically When we do Coding in Java , then we have to Check with !! in every Flied.
But in Kotlin, it is Easy way to Implement First
as Like,
Suppose, in Kotlin
var response:Json?=Null
response:Json?.let {
this part will handle automatic if response is Not Null....then this Block start Executing }?.run {
This is Nullable But, where we Can put Warring } So, I am Suggest you Guys to Start Work in Kotlin with this Features Provided by Kotlin.
(Flied)?.let { Not Null Value Comes Under }?.run{ Null Value Code }
This will Handle to NullPoint Exception or Protect You App for Crash
What you want to achieve
What you want to achieve is that the Kotlin compiler does a smart cast on the variable you are working with.
In all of your three examples, the compiler can do that.
Example:
if(myVar != null) {
foo(myVar) // smart cast: the compiler knows, that myVar can never be null here
}
The choice
Which one of the options to use, is really a matter of style. What you should not do is mix it up to often. Use one and stick to it.
You don't need to worry about performance since let and run are inlined (see inline function). This means that their code (body) is copied to the call site at compile time so there is no runtime overhead.

Alternative to the try (?) operator suited to iterator mapping

In the process of learning Rust, I am getting acquainted with error propagation and the choice between unwrap and the ? operator. After writing some prototype code that only uses unwrap(), I would like to remove unwrap from reusable parts, where panicking on every error is inappropriate.
How would one avoid the use of unwrap in a closure, like in this example?
// todo is VecDeque<PathBuf>
let dir = fs::read_dir(&filename).unwrap();
todo.extend(dir.map(|dirent| dirent.unwrap().path()));
The first unwrap can be easily changed to ?, as long as the containing function returns Result<(), io::Error> or similar. However, the second unwrap, the one in dirent.unwrap().path(), cannot be changed to dirent?.path() because the closure must return a PathBuf, not a Result<PathBuf, io::Error>.
One option is to change extend to an explicit loop:
let dir = fs::read_dir(&filename)?;
for dirent in dir {
todo.push_back(dirent?.path());
}
But that feels wrong - the original extend was elegant and clearly reflected the intention of the code. (It might also have been more efficient than a sequence of push_backs.) How would an experienced Rust developer express error checking in such code?
How would one avoid the use of unwrap in a closure, like in this example?
Well, it really depends on what you wish to do upon failure.
should failure be reported to the user or be silent
if reported, should one failure be reported or all?
if a failure occur, should it interrupt processing?
For example, you could perfectly decide to silently ignore all failures and just skip the entries that fail. In this case, the Iterator::filter_map combined with Result::ok is exactly what you are asking for.
let dir = fs::read_dir(&filename)?;
let todos.extend(dir.filter_map(Result::ok));
The Iterator interface is full of goodies, it's definitely worth perusing when looking for tidier code.
Here is a solution based on filter_map suggested by Matthieu. It calls Result::map_err to ensure the error is "caught" and logged, sending it further to Result::ok and filter_map to remove it from iteration:
fn log_error(e: io::Error) {
eprintln!("{}", e);
}
(|| {
let dir = fs::read_dir(&filename)?;
todo.extend(dir
.filter_map(|res| res.map_err(log_error).ok()))
.map(|dirent| dirent.path()));
})().unwrap_or_else(log_error)

Is it good practice to create once-used variables?

A colleague of mine refactored this code:
private void btnGeneral_Click(object sender, RoutedEventArgs e)
{
Button button = (Button)e.OriginalSource;
Type type = this.GetType();
Assembly assembly = type.Assembly;
string userControlFullName = String.Format("{0}.{1}", type.Namespace, button.Name);
UserControl userControl = (UserControl)assembly.CreateInstance(userControlFullName);
}
to this code:
private void btnGeneral_Click(object sender, RoutedEventArgs e)
{
Button button = (Button)e.OriginalSource;
Type type = this.GetType();
Assembly assembly = type.Assembly;
UserControl userControl = (UserControl)assembly.CreateInstance(String.Format("{0}.{1}", type.Namespace, button.Name));
}
saying that you don't need to create a variable if it is only going to be used once.
My response was that making once-used variables is good practice since it:
functions as and reduces comments (it is clear what "userControlFullName" is)
makes code easier to read, i.e. more of your code "reads like English"
avoids super-long statements by replacing parts of them with clear variable names
easier to debug since you can mouse over the variable name, and in the cases of e.g. PHP programming without debuggers, it is easier to echo out these variable names to get their values
The arguments against this way "more lines of code", "unnecessary variables" are arguments to make life easier for the compiler but with no significant speed or resource savings.
Can anyone think of any situations in which one should not create once-used variable names?
I'm with your opinion in this case. Readability is key. I'm sure that the compiler produces the same executable in both cases, with the compilers as intelligent as they are today.
But I wouldn't claim "always use once-used variables" either. Example:
String name = "John";
person.setName(name);
is unnecessary, because
person.setName("John");
reads equally well - if not even better. But, of course, not all cases are as clear cut. "Readability" is a subjective term, after all.
All your reasons seem valid to me.
There are occasions where you effectively have to avoid using intermediate variables, where you need a single expression (e.g. for member variable initialization in Java/C#) but introducing an extra variable for clarity is absolutely fine where it's applicable. Obviously don't do it for every argument to every method, but in moderation it can help a lot.
The debugging argument is particularly strong - it's also really nice to be able to step over the lines which "prepare" the arguments to a method, and step straight into the method itself, having seen the arguments easily in the debugger.
Your colleague doesn't seem to be consistent.
The consistent solution looks like this:
private void btnGeneral_Click(object sender, RoutedEventArgs e)
{
UserControl userControl = ((UserControl)type.Assembly).CreateInstance(String.Format("{0}.{1}", this.GetType().Namespace, ((Button)e.OriginalSource).Name));
}
I'm completely with you on this one.
I especially use this if a method takes a lot of booleans, ie
public void OpenDocument(string filename, bool asReadonly, bool copyLocal, bool somethingElse)
To me this is a lot more readable:
bool asReadonly = true;
bool copyLocal = false;
bool somethingElse = true;
OpenDocument("somefile.txt", asReadonly, copyLocal, somethingElse);
..than:
OpenDocument("somefile.txt", true, false, true);
Since the programming languages I use generally do not tell me what was null in an exception stacktrace I generally try to use variables so that no more than one item per line can be null. I actually find this to be the most significant limiter of how many statements I want to put on a single line.
If you get a nullpointerexception in this statement from your production logs you're really in trouble:
getCustomer().getOrders().iterator().next().getItems().iterator().next().getProduct().getName()
Although I agree with your thoughts, adding an extra variable can introduce an extra concept in the method and this concept may not always be relevant to the overall goal of the method. So excessive adding of variables can also increase method complexity and reduce legibility. Note the usage of excessive here.
I guess in some cases where it could have an effect on performance. In particular in this example:
for (int i1 = 0; i1 < BIG_NR; i1++)
{
for (int i2 = 0; i2 < BIG_NR; i2++)
{
for (int i3 = 0; i3 < BIG_NR; i3++)
{
for (int i4 = 0; i4 < BIG_NR; i4++)
{
int amount = a + b;
someVar[i1][i2][i3][i4] = amount;
}
}
}
}
... the extra assignment might have a too big impact on performance.
But in general, your arguments are 100% correct.
The both codes are exactly the same. Of course, yours is more readable, maintenable and debuggable, but, if that was the point of your colleague, his code is NOT memory less consumer.
I think it's a judgement call based on how tidy you want you code to be. I also think that both you and your colleague are correct.
In this instance I would side with you colleague based on the code you presented (for performance reasons), however as I said before it does depend on the context in which it will be used and I think your position is perfectly acceptable.
I would point out that creating variables for once used parameters can be pointless, unless they are const variables or things that you need to use in many places.
I would argue that declaring a once used variable could possible create more confusion when you are debugging if there are lots and lots of these, but one here and there is probably fine.
Creating a new variable means one more concept for the reader to keep track of. (Consider the extreme case: int b=a;c=b;) If a method is so complex - in such need of breaking up - that the extra concept is a price worth paying, then you ought to go the whole hog and split it into two methods. This way you get both the meaningful name and the smaller size. (Smaller for your original method: if it's like you say, then people won't typically need to read the auxiliary method.)
That's a generalisation, particularly in a language with a lot of boilerplate for adding new methods, but you're not going to disagree with the generalisation often enough to make it worth leaving out of your style guide.
I'm completely with your colleague in principle, but not in this case.
The problem with throwaway variables is that they introduce state, and more state means the code is harder to understand since you don't know what effects it could have on the program's flow. Functional programming has no variables at all, exactly for this reason. So the fewer variables there are, the better. Eliminating variables is good.
However, in this particular case, where the method ends right after the variable's only use, the disadvantages of having it are minimal, and the advantages you mention are probably more substantial.
Trying hard to come up with an argument against introducing new variables I'd say that when you read the code (for the first time, at least), you don't know if the variable is being used more than once. So immediately you will let your eyes scan down through the code to see if it is used in more places. The longer the function the more will you have to look to see if you can find it.
Thats's the best argument against that I can come up with! :-)
That's how I used to code. Nowadays I tried to minimize intermediate variables. The use of intermediate variables is perfectly fine if it's immutable.
I'm in agreement with the majority here, code readability is key.
It's a rare line count crusader that actually writes highly readable, highly maintainable code.
Additionally, it all gets compiled to MSIL anyway and the compiler will optimise a lot for you.
In the following example, the compiler will optimise the code anyway:
List<string> someStrings = new List<string>();
for (int i = 0; i < 1000; i++)
{
string localString = string.Format("prefix{0}", i);
someStrings.Add(localString);
}
Rather than:
List<string> someStrings = new List<string>();
string localString = string.Empty;
for (int i = 0; i < 1000; i++)
{
localString = string.Format("prefix{0}", i);
someStrings.Add(localString);
}
So there's really no performance reason not to go with it in many cases.
Agreed
"makes code easier to read, i.e. more of your code "reads like English"
I think this is the most important factor as there is no difference in performance or functionality on most moder managed languages
After all we all know code is harder to read than it is to write.
Karl