JML: \exists & JMLObjectSequence - object

im trying to prove if there exists a object with a particular status in my collection. My collection consists of objects with a method called getStatus(). Now i want to prove if there is a object with given status in this collection.
# requires (\exists int i; 0 <= i && i < sizeLimit; orders[i].getStatus().equals(Status.New));
public Order getFirstOrder(Status s)
The problem is that the orders[i] must be type of array nut it is type of JMLObjectSequence.Is there a way to cast this sequence to an array and how would the syntax look like?
Another way would be (using itemAt(i)):
# requires (\exists int i; 0 <= i && i < sizeLimit; orders.itemAt(i).getStatus().equals(Status.New));
BUT itemAt(i) returns an Object which is not type of Order - so the method getStatus() isnt found.
I would be very glad about some help. There arent much examples out there.

How about:
((Order)orders.itemAt(i)).getStatus()
Make sure getStatus() is notated as a pure method with the /#pure/ annotation where it is defined.
public /*#pure*/ Status getStatus(){ ...}
This should be valid.

Related

Why doesn't simple integer counterexample occur in Alloy?

I am trying to model a relationship between a numeric variable and a boolean variable, in which if the numeric variable is in a certain range then the boolean variable will change value. I'm new to Alloy, and am having trouble understanding how to constrain my scope sufficiently to yield the obvious counterexample. My code is as follows:
open util/boolean
one sig Object {
discrete : one Bool,
integer : one Int
}
fact { all o : Object | o.integer > 0 and o.integer < 10 }
fact { all o : Object | o.integer > 5 iff o.discrete = False }
assert discreteCondition { all o : Object | o.discrete = True }
check discreteCondition for 1000
Since o.integer is integer-values and ranges from 0 to 10, it could only be one of 10 different choices. And I specified that each Object should only have one integer and one discrete. So it seems reasonable to me that there are really only 10 cases to check here: one case for each value of integer. And yet even with 1000 cases, I get
No counterexample found.
If I remove the integer variable and related facts then it does find the counterexample almost immediately. I have also tried using other solvers and increasing various depth and memory values in the Options, but this did not help, so clearly my code is at fault.
How can I limit my scope to make Alloy find the counterexample (by iterating over possible values of the integer)? Thanks!
By default, the bitwidth used to represent integers is 4 so only integer in the range [-8,7] are considered during the instance generation, and so, due to integer overflows, your first fact is void (as 10 is outside this range).
To fix the problem, increase the bitwidth used to at least 5:
check discreteCondition for 10 but 5 Int.
Note that a scope of 1000 does not mean that you consider 1000 case in your analysis. The scope is the maximum number of atoms present in the generated instance, typed after a given signature. In your case you have only one signature with multiplicity one. So analyzing your model with a scope of 1 or 10000 doesn't change anything. There'll still be only one Object atom in the instance generated.
You might want to check this Q/A to learn more about scopes Specifying A Scope for Sig in Alloy

Can preconditions be expressed (for verification) as simple conditions?

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.

Purpose, use of and queries regarding the Objects.compare utility method

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.

moving objects in NSMutableArray without changing array size

I have a 'MutableArray' that I want to edit by moving different objects in it up and down the index via the method shown here: NSMutablearray move object from index to index.
My problem is that Xcode first takes care of the 'removeObjectAtIndex' method before the 'insertObject:atIndex:' so the array actually shrinks in size which makes certain transitions impossible. An example would be if my 'array' has 3 members and I change the third member's index from 2 to 2 so nothing should happen but actually the app crashes because after the removal the index bound is now [0,1].
Below is the code I am using to implement the move in array, I also get a Parse Issue: Expected identifier error from the compiler at the 'if' statement right behind the queue.count. Any help on both would be much appreciated.
-(void)makeRankChange:(NSMutableArray *)queue{
for (int queueCount =0; queueCount<queue.count; queueCount++) {
QueueMember *member = [queue objectAtIndex:queueCount];
if (member.rank != queueCount+1) {
if ([0<member.rank] && [member.rank < [queue.count(expected identifier here:Im not sure why)]]) {
[queue insertObject:member atIndex:member.rank-1];
[queue removeObjectAtIndex:queueCount];
}
}
}
}
How about replacing the value at the index:
[queue replaceObjectAtIndex:queueCount withObject:member];
The error is most likely from the '[' brackets in the if statement

Predicate syntax when partitioning a vector of pointers (C++)

I have a vector of pointers to objects. I'd like to remove objects from this vector according to an attribute that's reported by a member function.
I'm trying to follow a nice example I found on how to delete certain pointers (and their associated objects) from the vector. The basic idea is to partition the vector, delete the chosen objects, and then delete the pointers to those objects. Below is the example (from Dr. Dobbs):
vector<Object *> v ;
v.push_back( new Object( ... ) ) ;
...
vector<Object *>::iterator last =
partition( v.begin(), v.end(), not1(predicate()) ) ;
for( vector<Object *>::iterator i = last ; i != v.end() ; ++i )
{
delete *i ;
}
v.erase( last, v.end() ) ;
I'm stumped on the proper syntax for the predicate. My objects are of class Strain, and my vector is vector< Strain * > liveStrains. The predicate should be the Strain member function isExtinct(). The following doesn't work:
vector< Strain * >::iterator last = partition( liveStrains.begin(), liveStrains.end(), not1(std::mem_fun_ref(&Strain::isExtinct)) );
I can see that I am trying to invoke a member function on a pointer to the object rather than the object itself. To get around this, tried changing the & to * (I'm obviously a newbie), and I tried creating a member function for the class Simulation that does the liveStrains updating in a member function. I'm not sure it's worth going into the details of what didn't work. I'm severely confused by the syntactical options available, or if what I'm trying to do is even allowed.
Thanks in advance for any help.
The solution is to use std::mem_fun, which is made for pointers to objects, rather than std::mem_fun_ref.

Resources