What is the difference in my code as compared to the code I found on Google to check if my code is right? - kotlin

in short, the question is, I want to delete the last element of the DOUBLY LINKED LIST and I wrote this function...
fun deleteLast(){
if(isEmpty()){println("list is empty")}
if (head!=null && head?.nextNode == null){
head = null
}else {
tail = tail?.previousNode
tail?.nextNode = null
}
}
I went to the tail without traversing it and made its previous as new tail and new tail next(old tail) as null. And my result is desirable.
after writing this I pinged Google to check if this is right so, I found this...
void pop_back() {
if(this.head != null) {
//1. if head in not null and next of head
// is null, release the head
if(this.head.next == null) {
this.head = null;
} else {
//2. Else, traverse to the second last
// element of the list
Node temp = new Node();
temp = this.head;
while(temp.next.next != null)
temp = temp.next;
//3. Change the next of the second
// last node to null and delete the
// last node
Node lastNode = temp.next;
temp.next = null;
lastNode = null;
}
}
}
I want to ask If my code is right I just want you masters to review it. Thanks in advance!

The question only contains a snippet, not a minimal, reproducible example, so for the sake of argument (based on existing code and the comment) I'm going to assume that the full code looks something like this:
class Node<T>(var previousNode: Node<T>?, var nextNode: Node<T>?, var value: T)
class DoublyLinkedList<T>(var head: Node<T>?, var tail: Node<T>?) {
fun isEmpty() = head == null
// …other methods…
fun deleteLast(){
if(isEmpty()){println("list is empty")}
if (head!=null && head?.nextNode == null){
head = null
}else {
tail = tail?.previousNode
tail?.nextNode = null
}
}
}
Given this, it looks like your code is about right.  There are a few points that could be addressed*, e.g.:
Inside the second if I think it needs to set tail to null as well, for safety.
Inside the second and third branches, you might want to set to null the previousNode and nextNode references in the node you're removing, for the benefit of any other code that still has a reference to it.  (That might also give an extra hint to the garbage collector, though that shouldn't be needed.)
Instead of calling isEmpty(), it'd be simpler and more consistent to check whether head is null.
I'd add an else before the second if.  As it is, the code works for an empty list, but that may be just luck; it'd be much more robust if neither of the other branches could be called on an empty list.  (In some cases, this could let the compiler smart-cast head to non-nullable; but that doesn't happen here because it's mutable.)
In production code, you wouldn't print to stdout like that.  If it's allowed to call deleteLast() on an empty list, then there's no need to print anything; if not (which would be more usual), you'd throw an exception.  (And the method would have a doc comment explaining that.)
The formatting could be improved.
(* In my experience, any code can be improved — even code you've worked on many times before!)
However, you can't compare your code directly to the Google-sourced code, because it looks like that is for a singly-linked list.
A singly-linked list is a much simpler structure.  All it has is a reference to the head node; that has a reference to the next node (and, presumably to the data stored in the node); and so on.  So the only way to reach the end of the list is to traverse all the nodes, as the Google-sourced code does.  (This also means there's often no point in having a separate class to represent the list as a whole; a reference to the first node is all you need.  Many operations can be written concisely with recursive methods.  You can also make it immutable, which has many advantages; that's the primary data structure in some languages.)
Your list, though, has a direct reference to the last node, which of course avoids the need to traverse the entire list to find it.  As your code demonstrates, this means that some operations are much more efficient in double-linked lists.  There are corresponding disadvantages, though: each node takes more memory; there are more references to update when changing the list; it's easier for the list to get into an inconsistent state; and it's less suitable for an immutable list.)

Related

How to handle a forEach loop that returns early based on an enum except for one path in Kotlin

We have an API service call that returns a bunch of validation messages. In each message there is a string that contains an error code.
Our implementation converts the validation string into an enum value and then we process the enumeration as there are some error code we just don't care about.
The question becomes, how to handle the loop of messages in a Kotlin way:
response.validationErrors?.forEach {
val mediaFailure = decodeValidationMessage(it.message)
if (mediaFailure != MediaFailure.Unknown) {
return when (mediaFailure) {
MediaFailure.Encrypted -> DomainResponse(ErrorReasonCode.ERR_DOCUMENT_ENCRYPTED)
MediaFailure.NotSupported -> Response.validationFailed()
MediaFailure.InternalError -> Response.serviceFailed()
else -> throw NotImplementedError()
}
}
}
Here we loop through all the messages, then once the message error is not "Unknown" it returns the necessary response to the caller.
However, IntelliJ wants the else path, even though the if prevents that from happening.
Is there a proper Kotlin way of implementing this kind of loop?
From what I understood, you want to return a response for the first mediaFailure which is not MediaFailure.Unknown and you don't want that throw NotImplementedError() part in your function.
One way to fix this is to remove the if condition and continue the forEach loop when MediaFailure.Unknown is found.
response.validationErrors?.forEach {
val mediaFailure = decodeValidationMessage(it.message)
return when (mediaFailure) {
MediaFailure.Encrypted -> DomainResponse(ErrorReasonCode.ERR_DOCUMENT_ENCRYPTED)
MediaFailure.NotSupported -> Response.validationFailed()
MediaFailure.InternalError -> Response.serviceFailed()
MediaFailure.Unknown -> return#forEach // continue the loop
}
}
I think this is one of the many cases when it pays to step back from the code a bit and try to look at the big picture. To ask “What's the ultimate goal here? What am I trying to achieve with this code?”
(In traditional, lower-level languages, almost anything you want to do with a list or array requires a loop, so you get into the habit of reaching for a for or while without thinking. But there are often alternative approaches in Kotlin that can be more concise, clearer, and harder to get wrong. They tend to be more about what you're trying to achieve, rather than how.)
In this case, it looks you want to find the first item which decodes to give a known type (i.e. not MediaFailure.Unknown), and return a value derived from that.
So here's an attempt to code that:
val message = response.validationErrors?.asSequence()
?.map{ decodeValidationMessage(it.message) }
?.firstOrNull{ it != MediaFailure.Unknown }
return when (message) {
MediaFailure.Encrypted -> DomainResponse(ErrorReasonCode.ERR_DOCUMENT_ENCRYPTED)
MediaFailure.NotSupported -> Response.validationFailed()
MediaFailure.InternalError, null -> Response.serviceFailed()
else -> throw NotImplementedError()
}
This is still fairly similar to your code, and it's about as efficient. (Thanks to the asSequence(), it doesn't decode any more messages than it needs to.) But the firstOrNull() makes clear what you're looking for; and it's obvious that you go on to process only that one message — a fact which is rather lost in the original version.
(If there are no valid messages, message will be null and so this will return serviceFailed(), as per comments.)
There are of course many ways to skin a cat, and I can think of several variations. (It's often a worthwhile exercise to come up with some — if nothing else, it gives you more confidence in the version you end up with!) Try to pick whichever seems clearest, simplest, and best matches the big picture of what you're doing; that tends to work out best in the long run.

Using Kotlin's scope functions in not exhaustive with / when

I'm pretty new with Kotlin and I'm trying to figure out Kotlin's scope functions.
My code looks like this:
with(something) {
when {
equals("test") -> var1 = "test123"
startsWith("test2") -> var2 = "test456"
contains("test3") -> myNullableVar?.let { it.var3 = "test789" }
}
}
So before I entered the third check with the .let function my with function does not need to be exhaustive (I'm not returning something, I'm only doing assignments). In my third check I'm using .let as a null-check ... but only for an assignment of it.var3 (if it is not null). I don't need to return anything while I know that Kotlin's .let function returns the result of the body by standard.
Nevertheless now my with/when needs to be exhaustive otherwise it won't compile anymore.
This got me thinking and trying out different things. I found these ways to solve this issue:
I can add an else to my with/when so it becomes exhaustive but actually I don't need an else and I don't want to use it in this case.
I can add another .let, so it looks like this: myNullableVar?.let { it.var3 = "test789" }.let{} .... but this looks kinda hacky to me. Is it supposed to work like this?
Use If(xy==null){...}else{...} stuff but I thought I can solve this with Kotlin differently
Because I'm new with Kotlin I'm not really sure how to handle this case properly. I would probably just go with my second idea because "it works". Or should I don't use .let for null-checks? Add another empty .let{}? Or did I not get the null-safety concept at all? I feel a little bit lost here. Thanks for any help.
This seems to be an unfortunate combination of features…
A when can be non-exhaustive only when it doesn't return a value.  The problem is that the with() function does return a value.  And since the when is at the bottom, its value is what gets returned, so in this case it must be exhaustive.
So why doesn't it insist on an else branch even if you omit the "test3" branch?  That's because assignments don't yield a value.  (They evaluate to Unit, which is Kotlin's special type for functions that don't return a useful value.)  If every branch gives Unit, then Kotlin seems* to be happy to infer a default branch also giving Unit.
But the "test3" branch returns something else — the type of myNullableVar.  So what type does the when infer?  The nearest common supertype of that type and Unit, which is the top type Any?.  And now it needs an explicit else branch!
So what to do?
You've found a few options, none of which is ideal.  So here are a few more, ditto!
You could return an explicit Unit from that branch:
contains("test3") -> { myNullableVar?.let { it.var3 = "test789" }; Unit }
You could return an explicit Unit from the with():
contains("test3") -> myNullableVar?.let { it.var3 = "test789" }
}
Unit
}
You could give an explicit type for the with(). (It has two type parameters, so you'd need to give both, starting with the type of its parameter):
with<String, Unit>("abc") {
I haven't found a single obvious best answer, I'm afraid…
And to answer your last question: yes, ?.let{ is perfectly idiomatic and common for null checks.  In this particular case, replacing it with an if happens to solve the type problem:
contains("test3") -> { if (myNullableVar != null) myNullableVar.var3 = "test789" }
But as well as being long-winded, if myNullableVar is a property and not a local variable, then it opens up a race condition (what if another thread sets it to null in between the test and the assignment?) so the compiler would complain — which is exactly why people use let instead!
(* I can't find a reference for this behaviour.  Is there an official word on it?)

Modifying an object during iteration [duplicate]

This question already has an answer here:
How to modify/partially remove a range from a BTreeMap?
(1 answer)
Closed 6 years ago.
I'm trying to translate some simple data structures I use in C++ over to Rust, starting with an interval tree, but I don't understand how to modify my underlying data structure (here an std::collections::BTreeSet) during iteration - essentially so I can merge overlapping entries as they appear.
If I use the standard idiom for iterating over a collection, I get the following message about it being immutable "cannot borrow self.storage as mutable because it is also borrowed as immutable", and there doesn't appear to be an option to get a mutable iterator that I can see ... what am I missing?
C++ code:
inline void Insert(const Interval& interval)
{
auto it = storage.insert(interval);
// check to see if we overlap the previous element,
// if we do, start our merge loop from there
if (it != begin()) {
const_iterator prev = std::prev(it);
if (prev->Overlaps(*it)) it = prev;
}
while (it != end()) {
const_iterator nx = std::next(it);
if (nx != end() && it->Overlaps(*nx)) {
const Interval u = it->Union(*nx);
it = storage.erase(it);
it = storage.erase(it);
it = storage.insert(it, u);
} else
break;
}
}
Rust code:
/// Add a new interval into the tree
pub fn insert(&mut self, other: Interval) -> () {
self.storage.insert(other);
for int in self.storage.iter() {
if other <= *int {
break
} else if other.overlaps(int) {
self.storage.remove(&other);
self.storage.remove(int);
self.storage.insert(other.union(int).unwrap());
}
}
}
You cannot mutate a BTreeSet while you're iterating on it – that would invalidate the iterator. Unfortunately, unlike C++, Rust doesn't have insert or remove methods that return updated iterators (and if it did, they would have to be methods on the iterator itself).
BTreeSet doesn't offer a mutable iterator, because the only additional operation you could do is obtain a mutable reference to the elements in the set. However, doing this could potentially screw up the set's ordering, so it's not available.
The most straightforward solution is to build a list of operations to perform during the iteration, then perform them once the iteration is complete. However, for this algorithm, this won't quite work, since you might need to merge an interval that is the result of a previous merge. So, once you've found a pair of intervals to merge, you need to keep track of the relevant values, break out of the iteration, perform the merge, then restart the iteration. BTreeSet provides a range method that lets you iterate over a subset of the set's values, so you might want to use that instead of iter, which always iterates over all the values. However, range is unstable as of Rust 1.8, so you'll need a nightly compiler to be able to use it.

Call method/function twice Vs. Saving into a variable and call once

I often come to this question when coding.
Which of the following examples is a better practice? I am aware that other factors will influence whether one or the other one is better. But in general, what are the advantages of one over the other.
if(object.getA().Value != null) {
return object.getA().Value;
}
return null;
Vs.
string x = string.null;
x = object.getA().Value;
return (x != null) ? x : null;
Here is another similar example:
var a = object.method(x).Value;
var b = object.method(x).Key;
Vs.
var y = object,method(x);
var a = y.Value;
var b = y.Key;
In other words my question is:
Is it better to call a method twice and have one less variable?
or
Is it better to save it into a variable and call the method twice?
Of course if the method results in a lot of processing it might be smart to call it once, but for general cases where the method is not too demanding and the space of the variable is not too big, which one is better and why? or which are the advantages of one or the other?
The difference between them might not make a big difference but I am trying to find better practices and will like to hear the input of some experienced programmers.
Many thanks
Caching the value in a variable is a basic optimization (related to memoizing).
When it becomes truly necessary is if the second call to the function is on the stack a significant percent of the time.
For example, if that second call is on the stack 10% or 20% of the time, then that's how much overall time you can save by caching the first result.
You can keep doing things like that, until the code is as fast as possible.
If I can give an example, ages ago I worked on an app that had code like this:
if (!Done()){
do some stuff
}
....
if (!Done()){
do some other stuff
}
Since Done() was such a short, clean, and simple function to call, it got called a lot.
Never mind that it did a lot including querying a ton of stuff from a DB and throwing most of it away.
Stackshots found the problem instantly.
It depends if you want to be thread safe and if the function could change between calls.
e.g. with
if(object.getA().Value != null) {
return object.getA().Value;
}
return null;
if the implementation of the property getter Value returned a null on the second call you would have a different answer. It could return null on the second call either by implementation of the method or if another thread casused an update between the if and the return statement that made the result of the property null.
This test is actually redundant because you are returning null if it is null. I'm guessing that you meant if (object.getA() != null). Then the previous paragraph still applies but to getA() instead of Value but the if body would throw an null reference exception if getA() returned null on the second call.
So its all down to whether you are worried about the values changing between calls.
General rule: Avoid extra variables (needlessly introduces states).
(Break the rule if calling the function twice adds too much overhead)

Do you usually set the default value before or set it in the else?

Which one of the following do you do:
var = true;
if (...) var = false;
Or
if (...) var = false;
else var = true;
Is there a reason you pick on or the other?
I'm working on the premise that nothing else is happening to var. The next line of code might be something like:
if (var) { ... }
How about var = { ... } directly since it's a boolean?
I prefer the second in Java, doing something like this:
int x;
if (cond) {
x = 1;
} else {
x = 5;
}
because if something is changed later (for example, I turn the else block into an else if), the compiler will tell me that the variable has failed to be initialized, which I might miss if I used your first strategy.
You could also use a ternary operator if your language supports it :)
I would generally only do the first one if there was a chance the IF could fail and the variable must have a default value if it does.
If you set the default, then you reset it again later to something else, although it's a very small amount, its still a waste of resources. So, most of the time, for most of the code, a balanced if/else or even a (?:) syntax, are clearer and more appropriate, except:
Sometimes, if what you doing is building fall-through code (or a decision function), where you start with a specific condition, and then test a whole bunch of other conditions to see if that changes, then you want to definitely set the default first:
int final = 27;
if ( some condition ) final = 86;
if ( another condition ) {
final = 98;
return final;
}
if ( some state ) {
final += 2;
}
return final;
Or something similar to that.
BTW: in your example, if you set 'var', then the next line just tests 'var', you don't really need 'var' do you? If the condition is so ugly that using 'var' helps make it readable, then your probably best to move the condition into it's own function, accepting that the extra function call is there to help readability. In general, you can waste resources, if and only if you get something significant, such as readability, in return.
Paul.
Depends on the context. I would use the second option when it is clear that 'var' needs to be true when IF fails.
I use the first type unless the value to set requires significant computation.
Always the first as many people have said. However it's worth emphasising why, and that's because it makes the program more resistant to future bugs caused by incorrect maintenance.
For example, it's quite common for some additional business condition to arise and a maintenance coder add some extra condition or two inside the if to include more business logic and incorrectly amend the code - for example
if (a==b) {
if (a==c) {
[new logic]
var=false
}
}
else {
var = false
}
On the face of it it looks unlikely, but it happens alarmingly often (in fairness often the situation arises after the original if has got a lot more complex). Putting the initialisation first prevents this.
Do you prefer code that is short and compact, or code that is easier to read?
If you prefer code that is short and compact use
var x = true;
if (...) x = false;
But this can even be "improved". Most languages give initial values, and usually for the boolean type the default is false. So, you could write
var x;
if (...) x = true;
If you prefer code that is easy to read use
if (...) var x = false;
else var x = true;
because it makes your intentions clear.
The performance of both is the same.
Depends on the language. In C++, I would highly recommend setting it to a default as quickly as possible otherwise you risk getting garbage results.
In most other languages, you can be a bit more flexible. In fact, I would argue that it's more readable to explicitly define the conditions than to set a default.
Since the variable is not written to later, for general values I would write the following in Java:
final Type var;
if (cond)
{
var = value1;
}
else
{
var = value2;
}
The Java compiler will catch the error that var is not assigned a value before it is used.
The final keyword expresses the fact that the variable is constant after the conditional.
In your exact case with booleans I would use
final boolean var = !cond;
Using a conditional in this case indicates you are afflicted by "booleanophobia".
In C I would initialize the variable at its declaration.
I generally set the "default" value and use if statements to modify it.
If no default exists then only the if statements.
int timeout = 100;
if (moreTime) timeout = 1000;
int searchOption = null;
if (sometest1) searchOption = 1;
if (sometest2) searchOption = 2;
// then later..
if (searchOption != null)
.....
If the initialization is complex enough that a direct expression can't be cleanly written, I sometimes find it useful to handle this case as
boolean isFoo = determineWhetherFoo(...);
where determineWhetherFoo takes whatever arguments are necessary to make the determination and returns the appropriate boolean result. This makes it very clear what the variable means and what it depends on. Initializing a variable to a possibly-wrong value, followed by a wad of code that may change its value, can sometimes obscure what's being expressed.
Wherever you write an if() also write the else - even if it's empty.
The compiler will optimise it away but it forces you (and any programmers after you) to think about when the if () isn't triggered, what are the consequences?