I suppose this:
public static string abc()
{
return "abc";
}
Is better to call this function in this way:
string call = abc();
Console.writeline(call);
Than this?
console.writeline(abc());
is there any reason to prefer one to the other?
Both are valid. However, out of experience I have concluded that the first option is more suitable for readability and ease of maintenance. I can't count how many times I have changed from the "compact" style to the first one as a help for a debugging session.
For example, this style makes it easy to check the correctness intermediate of an intermediate result:
string call = abc();
assert(!call.empty()); // Just an example.
Console.writeline(call);
Also, it helps to make the code more robust later, adding a conditional check before the subsequent action that checks call's value, for example if the design does not guarantee that the condition of the previous assert holds but you still need to check it.
string call = abc();
if (!call.empty())
{
Console.writeline(call);
}
Note also that with this style you will be able to easily inspect the value of call in your debugger.
Given your exact example (one parameter, value not used elsewhere, no side effects), it's just a matter of style. However, it gets more interesting if there are multiple parameters and the methods have side effects. For example:
int counter;
int Inc() { counter += 1; return counter }
void Foo(int a, int b) { Console.WriteLine(a + " " + b); }
void Bar()
{
Foo(Inc(), Inc());
}
What would you expect Foo to print here? Depending on the language there might not even be a predictable result. In this situation, assigning the values to a variable first should cause the compiler (depending on language) to evaluate the calls in a predictable order.
Actually I don't see a difference if you don't have any error checking.
This would make a difference
string call = abc();
# if call is not empty
{
Console.writeline(call);
}
The above method could avoid empty string being written.
Related
Thank you in advance for your time and help.
Exercise:
Write the code for sumDigitsInNumber(int number). The method takes a three-digit whole number. You need to calculate the sum of the digits of this number, and then return the result.
Consider this example:
The sumDigitsInNumber method is called with argument 546.
Example output:
15
CODE:
public class Solution {
public static void main(String[] args) {
System.out.println(sumDigitsInNumber(546));
}
public static int sumDigitsInNumber(int number) {
return number ==0? 0:number%10+sumDigitsInNumber(number/10);
}
}
This is a solution and the task has been passed. The problem is the solution had been implemented by someone (not by me) therefore I can't understand How this function does its job.
I tried to test the function parts separately, just to see what would happen, and here is the result:
number%10 = 546%10;
546/10 = 54;
output:
6+sumDigitsInNumber(546/10) - which is totally wrong.
I don't understand HOW sumDigitsInNumber is treated by the ternary operator in there and how this short line of code:
return number ==0? 0:number%10+sumDigitsInNumber(number/10);
makes such a complicated calculation?
Can anyone explain it to me in a way it would have explained to a Java-child?
TYVM in advance.
So, using the example number of 546, let's step through the code.
In the first run, it does indeed return 6+sumDigitsInNumber(546/10), that is all correct.
Because sumDigitsInNumber's parameter (number) is int, the decimal portion of the division is truncated, resulting in essentially a floor operation (forced round down). And we recursively call sumDigitsInNumber's, so we just keep "looping" that section of code. So for the second run, it is equivalent to sumDigitsInNumber(54), plus the additional 6 from the first run (6+sumDigitsInNumber(54)).
The second call returns 4+sumDigitsInNumber(54/10) by following the same logic as the first call. This is equivalent to 4+sumDigitsInNumber(5).
Then we run the whole process again, which returns 5+sumDigitsInNumber(5/10), equivalent to 5+sumDigitsInNumber(0).
The final call, sumDigitsInNumber(0), will return 0 because of the ternary operator in the return statement.
To expand this all out:
sumDigitsInNumber(546)
= 6+sumDigitsInNumber(546/10) = 6+sumDigitsInNumber(54)
= 6+(4+sumDigitsInNumber(54/10)) = 6+(4+sumDigitsInNumber(5))
= 6+(4+(5+sumDigitsInNumber(5/10))) = 6+(4+(5+sumDigitsInNumber(0)))
= 6+(4+(5+0))
= 6+(4+(5))
= 6+(9)
= 15
How can I know if I actually need to return an l-value when using FALLBACK?
I'm using return-rw but I'd like to only use return where possible. I want to track if I've actually modified %!attrs or have only just read the value when FALLBACK was called.
Or (alternate plan B) can I attach a callback or something similar to my %!attrs to monitor for changes?
class Foo {
has %.attrs;
submethod BUILD { %!attrs{'bar'} = 'bar' }
# multi method FALLBACK(Str:D $name, *#rest) {
# say 'read-only';
# return %!attrs{$name} if %!attrs«$name»:exists;
# }
multi method FALLBACK(Str:D $name, *#rest) {
say 'read-write';
return-rw %!attrs{$name} if %!attrs«$name»:exists;
}
}
my $foo = Foo.new;
say $foo.bar;
$foo.bar = 'baz';
say $foo.bar;
This feels a bit like a X-Y question, so let's simplify the example, and see if that answers helps in your decisions.
First of all: if you return the "value" of a non-existing key in a hash, you are in fact returning a container that will auto-vivify the key in the hash when assigned to:
my %hash;
sub get($key) { return-rw %hash{$key} }
get("foo") = 42;
dd %hash; # Hash %hash = {:foo(42)}
Please note that you need to use return-rw here to ensure the actual container is returned, rather than just the value in the container. Alternately, you can use the is raw trait, which allows you to just set the last value:
my %hash;
sub get($key) is raw { %hash{$key} }
get("foo") = 42;
dd %hash; # Hash %hash = {:foo(42)}
Note that you should not use return in that case, as that will still de-containerize again.
To get back to your question:
I want to track if I've actually modified %!attrs or have only just read the value when FALLBACK was called.
class Foo {
has %!attrs;
has %!unexpected;
method TWEAK() { %!attrs<bar> = 'bar' }
method FALLBACK(Str:D $name, *#rest) is raw {
if %!attrs{$name}:exists {
%!attrs{$name}
}
else {
%!unexpected{$name}++;
Any
}
}
}
This would either return the container found in the hash, or record the access to the unknown key and return an immutable Any.
Regarding plan B, recording changes: for that you could use a Proxy object for that.
Hope this helps in your quest.
Liz's answer is full of useful info and you've accepted it but I thought the following might still be of interest.
How to know if returning an l-value ... ?
Let's start by ignoring the FALLBACK clause.
You would have to test the value. To deal with Scalars, you must test the .VAR of the value. (For non-Scalar values the .VAR acts like a "no op".) I think (but don't quote me) that Scalar|Array|Hash covers all the l-value super-types:
my \value = 42; # Int is an l-value is False
my \l-value-one = $; # Scalar is an l-value is True
my \l-value-too = #; # Array is an l-value is True
say "{.VAR.^name} is an l-value is {.VAR ~~ Scalar|Array|Hash}"
for value, l-value-one, l-value-too
How to know if returning an l-value when using FALLBACK?
Adding "when using FALLBACK" makes no difference to the answer.
How can I know if I actually need to return an l-value ... ?
Again, let's start by ignoring the FALLBACK clause.
This is a completely different question than "How to know if returning an l-value ... ?". I think it's the core of your question.
Afaik, the answer is, you need to anticipate how the returned value will be used. If there's any chance it'll be used as an l-value, and you want that usage to work, then you need to return an l-value. The language/compiler can't (or at least doesn't) help you make that decision.
Consider some related scenarios:
my $baz := foo.bar;
... (100s of lines of code) ...
$baz = 42;
Unless the first line returns an l-value, the second line will fail.
But the situation is actually much more immediate than that:
routine-foo = 42;
routine-foo is evaluated first, in its entirety, before the lhs = rhs expression is evaluated.
Unless the compiler's resolution of the routine-foo call somehow incorporated the fact that the very next thing to happen would be that the lhs will be assigned to, then there would be no way for a singly or multiply dispatched routine-foo to know whether it can safely return an r-value or must return an l-value.
And the compiler's resolution does not incorporate that. Thus, for example:
multi term:<bar> is rw { ... }
multi term:<bar> { ... }
bar = 99; # Ambiguous call to 'term:<bar>(...)'
I can imagine this one day (N years from now) being solved by a combination of allowing = to be an overloadable operator, robust macros that allow overloading of = being available, and routine resolution being modified so the above ambiguous call could do something equivalent to resolving to the is rw multi. But I doubt it will actually come to pass even with N=10. Perhaps there is another way but I can't think of one at the moment.
How can I know if I actually need to return an l-value when using FALLBACK?
Again, adding "when using FALLBACK" makes no difference to the answer.
I want to track if I've actually modified %!attrs or have only just read the value when FALLBACK was called.
When FALLBACK is called it doesn't know what context it's being called in -- r-value or l-value. Any modification comes after it has already returned.
In other words, whatever solution you come up with will being nothing to do per se with FALLBACK (even if you have to use it to implement some other aspect of whatever it is you're trying to do).
(Even if it were, I suspect trying to solve it via FALLBACK itself would just make matters worse. One can imagine writing two FALLBACK multis, one with an is rw trait, but, as explained above, my imagination doesn't stretch to that making any difference any time soon, if ever, and could only happen if the above imaginary things happened (the macros etc.) and the compiler was also modified to pay attention to the two FALLBACK multi variants, and I'm not at all meaning to suggest that that even makes sense.)
Plan B
Or (alternate plan B) can I attach a callback or something similar to my %!attrs to monitor for changes?
As Lizmat notes, that's the realm of Proxys. And thus your next SO question... :)
I understand that a precondition, in context of Desing by contract/Liskov principle, is something that should be true before the code is called, e.g. the caller is responsible for that. Also, the author of the Eiffel language stated that most people do put another verification check into the called cade, simply as means of defensive programming.
Some time ago I read a question with a code similar to this:
void X(int value)
{
if (value > 100)
{do something...}
}
Some commenters argued that the if statement is not a precondition but I do not think that is right - if the contract states V must be 100, then this is verifying the precondition additionally and if a class is derived from this type and changes to v > 200, it would be strenghtening the precondition and thus violating the Liskov principle. Or isn't that the case?
As you said, a precondition is defined as a condition that must always be true before the proceeding code executes.
This means that anything that checks for a condition at the beginning of a function before other code is executed, then it is considered a precondition.
Example:
//We will do something cool here
//With an integer input
int doSomethingCool(final int input)
{
//Wait, what if input is null or less than 100?
if(null == input || input < 100)
{
//Return a -1 to signify an issue
return -1;
}
//The cool bit of multiplying by 50. So cool.
final int results = input * 50;
//Return the results;
return results;
}
In the example, the function, input is checked before anything else is executed. So long as the conditions are met, then the rest of the code will execute.
Bad Example:
//We will do something cool here
//With an integer input
int doSomethingCool(final int input)
{
//Want to make sure input is not null and larger than 100
if(null != input && input > 100)
{
//The cool bit of multiplying by 50. So cool.
final int results = input * 50;
//Return the results;
return results;
}
//Return a -1 to signify an issue because the
//preconditions were not met for some reason
return -1;
}
In the example, the precondition is to check that input is not null and larger than 100. This is a bad precondition because it could introduce unnecessary nesting of ifs and loops.
Preconditions should do checks and only return when the checks fail. There should be no work done in a precondition.
In keeping with the Liskov Substitution Principle, if type S is a subtype of type T, then type T can be replaced with type S. If type S overrides doSomethingCool and changes the precondition, then it is in violation, because type T is the base definition and defines the intended conditions that must be met.
Now for your answer
Yes, simple conditions still count as preconditions. As long as they are at the front of all other code that uses the variable, the condition is as what is needed by the program. Also, if the function is in a subtype and is overriding the parent class, then it should not change the precondition.
However, do not surround the code that you need to run within the precondition. That is bad practice. If value needs to be larger than 100, check value < 100 and set a return in the if check.
class ArgumentClass{
int var;
}
class ClassMocked{
int aMothod(ArgumentClass argumentClass){
return anInt;
}
}
class MyTest{
Mock and Stub here
}
In MyTest, I want to stub aMothod such that it returns the value basing on value of ArgumentClass.var. And I have to do it in one go.
In other words, I have a test case where a moehod is called three times by the app code and basing on a variable in an argument object, I need different return values. I need to stub accordingly. Please let me know if there is a way.
If I understand that correctly you can do it in two different way with mockito. If you declare ClassMocked as a mock you should be able to say this:
when(mock.aMothod(eq(specificArgument))).thenReturn(1);
when(mock.aMothod(eq(anotherSpecificArgument))).thenReturn(2);
If you want to do it that regardless of the argument passed you want to return values based on the number of invocation of the method you can say:
when(mock.aMothod(any())).thenReturn(1, 2);
This says that when aMothod is called regardless of the parameter passed (any()) it will return in the first call 1 and when called second time it will return 2.
Though you can have your mock return values in the right order, as in karruma's answer, you may also use an Answer to calculate the mocked value:
when(mock.aMothod(any())).thenAnswer(new Answer<Integer>() {
#Override public Integer answer(InvocationOnMock invocation) {
ArgumentClass argument = invocation.getArguments()[0];
return calculationBasedOn(argument);
}
});
Or in Java 8 and Mockito 2 beta (untested, may need boxing/unboxing casts):
when(mock.aMothod(any())).thenAnswer(invocation ->
calculatebasedOn(invocation.getArgumentAt(0, ArgumentClass.class)));
Though I have an anonymous inner class in the top sample, naturally, you can make a named Answer subclass and reuse it across your application.
I have a question about using the new Objects.compare(o1, o2, Comparator) method - from my own testing of it, if both o1 and o2 are null then it returns 0, however, if one of them is null then it still throws a null pointer exception. I have found a lot of material on Objects.equals and some of the other Objects utility methods but not much at all on Objects.compare and when we are expected to use it / replace old code with it.
So here I could do this:
String s1 = "hi";
String s2 = "hi";
int x = Objects.compare(s1, s2, Comparator.naturalOrder());
System.out.println("x = " + x);
That works fine, returns 0, now this:
String s1 = null;
String s2 = null;
Also works fine and returns 0. However, this:
String s1 = "hi";
Strng s2 = null;
Throws a NullPointerException. I'm guessing the benefit of Objects.compare(o1,o2,Comparator) vs o1.compareTo(o2) is that it at least handles circumstances where both objects are null and when one of them is null it allows you to design a Comparator to handle it. I'm supposing, e.g.
int x = Objects.compare(s1, s2, Comparator.nullsFirst(Comparator.naturalOrder()));
Whereas with x.compareTo(y) there's no way to handle null unless you do so beforehand? So do the Java library developers now intend us to replace all calls to compareTo with Objects.compare, when we're concerned about nulls? e.g. would we do this in our Comparable implementations?
Side query 1: With regards to using nullsFirst if you use it then pass in a Comparator, which is chained using comparing, thenComparing, etc, does it apply to all of the inner comparators? e.g.
Comparator.nullsFirst(Comparator.comparing(Song::getTitle)
.thenComparing(Song::getArtist)
.thenComparing(Song::getDuration)
)
Would that apply nullsFirst to everything inside or do you need to use nullsFirst individually on each of them? I think from testing that it only applies to the actual Song objects being null, not for the fields of title or artist being null, i.e. if they are null then a NullPointerException is still thrown. Anyway around that?
Side query 2: final question is that because I like the Comparator.comparing syntax, I'm proposing to start to write my compareTo implementions using it - I was struggling to think how to replace this traditional approach, e.g.
public int compareTo(Song other) {
int result = this.title.compareTo(other.title);
if (result == 0) {
result = this.artist.compareTo(other.artist);
if (result == 0) {
result = Integer.compare(this.duration, other.duration);
}
}
return result;
}
then I thought I could use Objects.compare(...) as follows:
public int compareTo(Song other) {
return Objects.compare(this, other, Comparator.nullsFirst(
Comparator.comparing(Song::getTitle)
.thenComparing(Song::getArtist)
.thenComparingInt(Song::getDuration)
));
}
I thought this version was more elegant - I am assuming it is working as I think it is, e.g. by passing this and other as the first 2 arguments then the comparator, it has the same effect as the traditional compareTo approach with if statements? Whilst I can see that the benefit of Objects.compare catching two nulls would never occur as if this was null then the compareTo method call would never be reached (either by handling the exception or it being thrown). But by using nullsFirst I suppose if the argument passed in, i.e. other, was null, then this would handle this safely?
Many thanks in advance for any help.
Objects.compare is not meant to provide a null safe comparison, since there is no default behavior that could be implemented. It just implements a shortcut of not invoking the Comparator’s method when both objects are identical. In other words, it does a==b? 0: c.compare(a, b), nothing more. So not breaking when both objects are null is just a side-effect. The encapsulated code might look trivial but the other methods in this class are of a similar category. Using small utility methods a lot might still result in a notable win.
By the way, it’s not a Java 8 method at all. It exists since Java 7.
Regarding your second question, Comparator.nullsFirst(…) decorates an existing Comparator and will enforce the rule for null values before delegating to the provided comparator as it is the purpose of this comparator to shield the existing one from ever seeing null values. It doesn’t matter whether the decorated comparator is a chained one or not. As long as it is what you called the “inner comparator”, as
you must not invoke thenComparing on the result of nullsFirst as that would imply calling the next comparator when both values are null.
Comparator.nullsFirst(Comparator.comparing(a).thenComparing(b)) // perfect
Comparator.nullsFirst(Comparator.comparing(a)).thenComparing(b) // ouch
Now to your third question, implementing a compareTo method using a nullsFirst comparator is violating the interface specification:
The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y. (This implies that x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception.)
This implies that passing null as argument should always result in a NullPointerException as swapping argument and receiver would throw as well, unconditionally.
Orders including a null policy should always be provided as separate Comparators.
Note that it would also be quite inefficient as you would create a new Comparator (multiple Comparators, to be precise) for every compareTo call. Now image sorting a rather large list of these objects…
What I normally do for your final question is to first create a static comparator reference within the class:
public static final Comparator<Song> COMP_DEFAULT
= nullsFirst(comparing(Song::getTitle, nullsFirst(naturalOrder()))
.thenComparing(Song::getArtist, nullsFirst(naturalOrder()))
.thenComparingInt(Song::getDuration));
And then refer to this comparator in compareTo
public int compareTo(Song other) {
return COMP_DEFAULT.compare(this, other);
}
This way you're not recreating your comparator for each compareTo call, null safety of Song is guaranteed as is the result of a.comparetTo(b) == b.compareTo(a).
We also ensure null safety of each property by using nullsFirst(naturalOrder()) for the passed in key comparator (second argument).
As the Comparator returned is immutable it can be made public which can be handy for bundling some alternate Comparators with the class that consumers may use.