Achilles Cassandra - Getting result of conditional update - cassandra

How to get response when performing a conditional update/delete from Achilles?
I tried using a custom ResultListener, but it doesn't always work correctly.
public class ResultListener implements LWTResultListener {
private boolean applied;
#Override
public void onSuccess() {
applied = true;
}
#Override
public void onError(LWTResult lwtResult) {
applied = false;
}
public boolean isApplied() {
return applied;
}
}
From my caller class, I call isApplied() but it seems that the onSuccess method is called asynchronously. The caller class doesn't see the updated value of applied field.

That's not the problem with Cassandra/Achilles itself, but general problem with async programming - callback could be called at any point of time...
For your code there are 2 things:
First, you need to understand if the callback was called or not - you may add another boolean variable that will be set by both onSuccess & onError to indicate that callback was called already. And your code need to check this variable before calling isApplied;
Second - you need to guarantee that the change is visible by other parts of the code. You can add the volatile keyword to the declaration of applied variable (and to the declaration of variable described above). This keyword will indicate that data could be changed by some other thread, and Java will enforce that data is always read from memory. Following article describes this in quite good details.

Related

Throw specific exception for a violation of a contract on an automatic property

I can specify a contract for an automatic property like this (example taken from the CC documentation):
public int MyProperty { get; set ; }
[ContractInvariantMethod]
private void ObjectInvariant () {
Contract. Invariant ( this .MyProperty >= 0 );
...
}
When runtime-checking is turned on, and an attempt is made to assign an invalid value to MyProperty, the setter throws System.Diagnostics.Contracts.__ContractsRuntime+ContractException.
Is there a way to make it throw a specific type of exception - typically, ArgumentNullException, ArgumentOutOfRangeException, or similar, without having to go back and implement the property manually using a backing field and Requires<> ?
No, there isn't.
But as long as your property setter is private, you don't have to worry about that. Any ArgumentException that would be thrown from your setter indicates a bug in the code calling that setter, and should be fixed there. The only code that can call your setter is your own.
If your property setter is protected or public, then you do need to specify which ArgumentException gets thrown for which values.
From the Code Contracts manual:
Object invariants are conditions that should hold true on each instance of a class whenever that object is visible to a client. They express conditions under which the object is in a "good" state.
There's a peculiar couple of sentences in the manual at the top of page 10:
Invariants are conditionally defined on the full-contract symbol [CONTRACT_FULL]. During runtime checking, invariants are checked at the end of each public method. If an invariant mentions a public method in the same class, then the invariant check that would normally happen at the end of that public method is disabled and checked only at the end of the outermost method call to that class. This also happens if the class is re-entered because of a call to a method on another class.
— text in brackets is mine; this is the compile time symbol the manual is referencing which is defined.
Since properties are really just syntactic sugar for T get_MyPropertyName() and void set_MyPropertyName(T), these sentences would seem to apply to properties, too. Looking in the manual, when they show an example of defining object invariants, thy show using private fields in the invariant contract conditions.
Also, invariants don't really communicate to consumers of your library what the pre-conditions or post-conditions for any particular property or method are. Invariants, again, only state to consumers of the library what conditions "hold true on each instance of a class whenever that object is visible to a client." That's all they do. In order to state that if an invalid value will result in throwing an exception, you must specify a pre-condition, which is demonstrated below.
Therefore, it would appear that in order to best achieve what you're looking for, it's as hvd says: it's best to have a private backing field and place the invariant on the backing field. Then you would also provide the contracts on the property getter/setter so that consumers of your library know what the pre-conditions and guaranteed post-conditions (if any) are.
int _myPropertyField = 0;
[ContractInvariantMethod]
private void ObjectInvariants()
{
Contract.Invariant(_myPropertyField >= 0);
}
public int MyProperty
{
get
{
Contract.Ensures(Contract.Result<int>() >= 0);
return _myPropertyField;
}
set
{
Contract.Requires<ArgumentOutOfRangeException>(value >= 0);
_myPropertyField = value;
}
}
Now, there is another way to throw a specific exception using "legacy" code contracts (e.g. if-then-throw contracts). You would use this method if you're trying to retrofit contracts into an existing codebase that was originally written without contracts. Here's how you can do this without using Contract.Requires<TException>(bool cond):
Basically, in Section 5: Usage Guidelines of the manual, you'll be referencing Usage Scenario 3, legacy contract checking (see page 20). This means you need to set the following options in the Code Contracts project properties dialog:
Ensure that the Assembly Mode is set to Custom Parameter Validation.
Use "if-then-throw" guard blocks and perform manual inheritance.private
Ensure Contract.EndContractBlock() follows these guard blocks.
Check Perform Runtime Contract Checking and select the level of checking you want, but only on Debug builds—not on Release builds.
Feel free to use Contract.Requires(bool cond) (non-generic form) on private API methods (e.g. methods not directly callable by a library consumer).
Then, you could write the following code:
private int _myPropertyField = 0;
[ContractInvariantMethod]
private void ObjectInvariants()
{
Contract.Invariant(_myPropertyField >= 0);
}
public int MyProperty
{
get
{
Contract.Ensures(Contract.Result<int>() >= 0);
return _myPropertyField;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException("value");
}
Contract.EndContractBlock();
_myPropertyField = value;
}
}
Now, you specifically stated that you didn't want to have to go back and create private backing fields for all of your properties. Unfortunately, if this is a public property than can be mutated, then there really is no way to good avoid this. One possible way to avoid this, though, is to make your setter private:
public int MyProperty { get; private set; }
[ContractInvariantMethod]
private void ObjectInvariants()
{
Contract.Invariant(MyProperty >= 0);
}
public SetMyProperty(int value)
{
// Using Code Contracts with Release and Debug contract checking semantics:
Contract.Requires<ArgumentOutOfRangeException>(value >= 0);
// Or, using Code Contracts with Debug-only contract checking semantics:
Contract.Requires(value >= 0);
// Using Legacy contracts for release contract checking without throwing
// a ContractException, but still throwing a ContractException for
// debug builds
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
Contract.EndContractBlock();
MyProperty = value;
}
However, I must admit, I'm not really sure what you're gaining at this point by implementing invariants in this manner. You might as well just bite the bullet and use one of the first two examples I demonstrated above.
Addendum, 2016-02-22
The OP notes in their comment that Section 2.3.1 of the manual mentions that defining object invariants on auto-properties results in the invariant essentially becoming a precondition on the setter and a postcondition on the getter. That's correct. However, the preconditions that are created use the non-generic Contract.Requires(bool condition) form. Why? So that when invariants are used by those who don't want runtime contract checking turned on for their Release builds, they can still use invariants. Therefore, even if you use invariants on properties, if you want a specific exception thrown on contract violations, you must use full properties with backing fields and the generic form of Requires, which also implies that you want to perform runtime contract checking on all builds, including Release builds.

Template methode in threaded contexts

Let's say we have a template method that looks like this
abstract class Worker
{
public void DoJob()
{
BeforJob()
DoRealJob();
AfterJob();
}
abstract void DoRealJob();
}
subclasses that inherit from the Wroker classe should implemente the DoRealJob() method,
when the implementation is running under the same thread everything is fine, the three part of the DoJob() method get executed in this order
BeforJob()
DoRealJob()
AfterJob()
but when DoRealJob() runs under another thread, AfterJob() may get executed before DoRealJob() is completed
my actual solution is to let the subclasses call AfterJob() but this doesn't prevent a subclass from forgetting to call it, and we loose the benefit of a template method.
are there other ways to get consistent call order despite the fact the DoRealJob() is blocking or not?
You can't get both the simple inheritance(signature and hooking) and support asynchronous operations in your code.
These two goals are mutually exclusive.
The inheritors must be aware about callback mechanisms in either direct (Tasks, async) or indirect (events, callback functions, Auto(Manual)ResetEvents or other synchronization constructs). Some of them new, some old. And it is difficult to say which one will be better for the concrete case of use.
Well, it may look like there is a simple way with multithreaded code, but what if your DoRealJob will actually run in another process or use some remote job queuing, so the real job will be executed even outside your app?
So:
If you really consider that your class will be used as the basis for some
async worker, then you should design it accordingly.
If not - do not overengineer. You can't consider any possible
scenario. Just document your class well enough and I doubt that
anyone will try to implement the DoRealJob asynchronously,
especially if you name it DoRealJobSynchronously. If someone tries to
do it then in that case your conscience can be pristinely clean.
EDIT:
Do you think it would be correct if I provide both versions, sync and
async, of DoRealJob and a flag IsAsynchronous so I can decide which
one to call
As I have already said I don't know your actual usage scenarios. And it is unrealistic to consider that the design will be able to effectively handle all of them.
Also there are two very important questions to consider that pertain to your overall Worker class and its DoJob method:
1) You have to determine whether you want the DoJob method to be synchronous or asynchronous, or do you want to have both the synchronous and asynchronous versions? It is not directly related to your question, but it is still very important design decision, because it will have great impact on your object model. This question could be rephrased as:
Do you want the DoJob method to block any actions after it is called until it does its job or do you want to call it as some StartJob method, that will just launch the real processing but it is up to other mechanisms to notify you when the job has ended(or to stop it manually):
//----------------Sync worker--------------------------
SyncWorker syncWorker = CreateSyncStringWriter("The job is done");
Console.WriteLine("SyncWorker will be called now");
syncWorker.DoJob(); // "The job is done" is written here
Console.WriteLine("SyncWorker call ended");
//----------------Async worker--------------------------
Int32 delay = 1000;
AsyncWorker asyncWorker = CreateAsyncStringWriter("The job is done", delay);
Console.WriteLine("AsyncWorker will be called now");
asyncWorker.StartDoJob(); // "The job is done" won't probably be written here
Console.WriteLine("AsyncWorker call ended");
// "The job is done" could be written somewhere here.
2) If you want DoJob to be async(or to have async version) you should consider whether you want to have some mechanisms that will notify when DoJob finishes the processing - Async Programming Patterns , or it is absolutely irrelevant for you when or whether at all it ends.
SO:
Do you have the answers to these two questions?
If yes - that is good.
If not - refine and consider your requirements.
If you are still unsure - stick with simple sync methods.
If you, however, think that you need some async based infrastructure, then, taking into account that it is C# 3.0, you should use Asynchronouse Programming Model.
Why this one and not the event based? Because IAsyncResult interface despite its cumbersomeness is quite generic and can be easily used in Task-based model, simplifying future transition to higher .NET versions.
It will be something like:
/// <summary>
/// Interface for both the sync and async job.
/// </summary>
public interface IWorker
{
void DoJob();
IAsyncResult BeginDoJob(AsyncCallback callback);
public void EndDoJob(IAsyncResult asyncResult);
}
/// <summary>
/// Base class that provides DoBefore and DoAfter methods
/// </summary>
public abstract class Worker : IWorker
{
protected abstract void DoBefore();
protected abstract void DoAfter();
public IAsyncResult BeginDoJob(AsyncCallback callback)
{
return new Action(((IWorker)this).DoJob)
.BeginInvoke(callback, null);
}
//...
}
public abstract class SyncWorker : Worker
{
abstract protected void DoRealJobSync();
public void DoJob()
{
DoBefore();
DoRealJobSync();
DoAfter();
}
}
public abstract class AsyncWorker : Worker
{
abstract protected IAsyncResult BeginDoRealJob(AsyncCallback callback);
abstract protected void EndDoRealJob(IAsyncResult asyncResult);
public void DoJob()
{
DoBefore();
IAsyncResult asyncResult = this.BeginDoRealJob(null);
this.EndDoRealJob(asyncResult);
DoAfter();
}
}
P.S.: This example is incomplete and not tested.
P.P.S: You may also consider to use delegates in place of abstract(virtual) methods to express your jobs:
public class ActionWorker : Worker
{
private Action doRealJob;
//...
public ActionWorker(Action doRealJob)
{
if (doRealJob == null)
throw new ArgumentNullException();
this.doRealJob = doRealJob;
}
public void DoJob()
{
this.DoBefore();
this.doRealJob();
this.DoAfter();
}
}
DoBefore and DoAfter can be expressed in a similar way.
P.P.P.S: Action delegate is a 3.5 construct, so you will probably have to define your own delegate that accepts zero parameters and returns void.
public delegate void MyAction()
Consider change the DoRealJob to DoRealJobAsync and give it a Task return value. So you can await the eventual asynchronous result.
So your code would look like
abstract class Worker
{
public void DoJob()
{
BeforJob()
await DoRealJobAsync();
AfterJob();
}
abstract Task DoRealJob();
}
If you don't have .net 4.0 and don't want to us the old 3.0 CTP of async you could use the normale task base style:
abstract class Worker
{
public void DoJob()
{
BeforJob()
var task = DoRealJobAsync();
.ContinueWith((prevTask) =>
{
AfterJob()
});
}
abstract Task DoRealJob();
}

non-static variable this cannot be referenced from a static context

I'm working with java me. I tried to switch to a displayable(form2) in Second.java from an okCommand in another displayble(form1) in First.java (see my previous question on that).
I got an error non-static method getForm2() cannot be referenced from a static context. I had to add the word static to form2 declaration and also at the getForm2 method in Second.java before it could work.
Problem now is that a backCommand in form2 can't switch back to form1 in First.java and it pops up the error non-static variable this cannot be referenced from a static context.
I paused and took some time to refresh myself on the language fundamentals on how the static keyword is used and I got to know that a static method is a class method and a non-static method is an instance method and that a non-static cannot call a static method unless an instance of the non-static method is created and also that a static method can't call a non-static method.
I'm really not understanding the implementation as I should, and I'd appreciate some clarification using my example above.
Here's the source below from Second.java the error is coming from form2.setCommandListener(this);
public static Form getForm2() {
if (form2 == null) {
form2 = new Form("form");
form2.addCommand(getBackCommand());
form2.setCommandListener(this);
}
return form2;
You have a static method, but are using this. But this doesn't exist. It would normally reference to an instance of the class, but you don't have one here.
If your method wasn't static and you instantiated an instance of this class then this would work.
e.g.
Second s = new Second();
Form f = s.getForm2(); // if this method wasn't static
Making that method static means little more than namespacing. There isn't an associated instance and no this.
There are couple options. First is to create a static instance of Second and use it in the getForm2:
//...
// static instance
private static Second instance = new Second(/* put constructor arguments here, if any */);
//...
public static Form getForm2() {
if (form2 == null) {
form2 = new Form("form");
form2.addCommand(getBackCommand());
form2.setCommandListener(instance); // --> replace "this" with "instance"
}
//...
From the issues you describe though, I would prefer another option - returning to design you had in previous question and use an instance of Second as an argument passed via constructor of First.
Your First.java would then have lines like:
//...
private final Second second; // instance needed for commandAction
//...
First(Second second) { // constructor with parameter
this.second = second; // save the parameter
//...
}
Then, commandAction method in First.java could use code like:
switchDisplayable(null, second.getSecondForm());
// instead of Second.getSecondForm()

Regarding String functionality

I was developing the below class..
public class Test1
{
public void method(Object o)
{
System.out.println("Object Verion");
}
public void method(String s)
{
System.out.println("String Version");
}
public static void main(String args[])
{
Test1 question = new Test1();
//question.method(question);
question.method(null);
}
}
Now upon executing it invokes string version as output So please advise here string is treated as null and what should we pass to invoke the object version.Thanks in advance
All other things being equal, the most-specific method will be called. From the JLS:
15.12.2.5. Choosing the Most Specific Method
If more than one member method is both accessible and applicable to a
method invocation, it is necessary to choose one to provide the
descriptor for the run-time method dispatch. The Java programming
language uses the rule that the most specific method is chosen.
The informal intuition is that one method is more specific than
another if any invocation handled by the first method could be passed
on to the other one without a compile-time type error.
question.method(null) could mean either the String or Object overload, but since String is more specific (narrower) than Object, the String overload is the method that is called.

How should I test null and/or empty string parameters in a method?

It is common to have classes with methods with string parameters that must be validated agains null or empty, such as this example:
public class MyClass {
public void MyMethod(string param){
if(string.IsNullOrEmpty(param)){
throw new ArgumentNullException(...);
}
//...
}
}
It's clear that the behavior of the method is the same for both (invalid) values. This is a very common situation, and when it comes to testing these methods, I always doubt about how to do it. I always create two separate tests for these cases:
[TestClass]
public class Tests {
[TestMethod]
public void MyMethod_should_fail_if_param_is_null(){
//...
myclass.MyMethod(null);
//...
}
[TestMethod]
public void MyMethod_should_fail_if_param_is_empty(){
//...
myclass.MyMethod("");
//...
}
}
But I see too much redundancy. Those tests are exactly the same, with the only difference being the parameter passed to the method. That bothers me very much, since I have to create two tests for each string parameter. A method with 3 parameters would have 6 tests only to test the parameters.
I think this is the right way of testing those parameters, but if I know that 99% of string parameters will be validated the same way, wouldn't it be better just test them for null (or empty) and assume that the behavior in the other case will be the same?
I would like to know what you think about this. I know what I'm asking is more a technical opinion than a technical question, but I think the testing community may have something interesting to say about this situation.
Thank you!
Personally I'd consider using a single test for all of the parameters. That doesn't follow the normal dogma of unit testing, but it increases the readability of the tests (by minimizing the amount of test code which is dedicated to a pretty repetitive case) and doesn't have much in the way of downsides. Yes, if the test fails you don't know whether all of the checks after the first failing one will also fail - but is that really a problem in practice?
The important point is to make sure that you've got a short cut for testing the case. For instance, you might write something like this (if your unit test framework doesn't have it already):
public static void ExpectException<T>(Action action) where T : Exception
{
try
{
action();
Assert.Fail("Expected exception " + typeof(T).Name);
}
catch (T exception)
{
// Expected
}
}
Then you can write:
[Test]
public void MyMethodFailsWithInvalidArguments()
{
ExpectException<ArgumentNullException>(() => myClass.MyMethod(null));
ExpectException<ArgumentException>(() => myClass.MyMethod(""));
}
Much more concise than doing each one with an individual try/catch block, or even using an ExpectedException attribute and multiple tests.
You might want overloads for cases where you also want to verify that in each case, no mocked objects have been touched (to check that side-effects are avoided) or possibly overloads for common exceptions like ArgumentNullException.
For single-parameter methods you could even write a method to encapsulate exactly what you need:
public void ExpectExceptionForNullAndEmptyStrings(Action<string> action)
{
ExpectException<ArgumentNullException>(() => action(null));
ExpectException<ArgumentException>(() => action(""));
}
then call it with:
[Test]
public void MyMethodFailsWithInvalidArguments()
{
// This *might* work without the
ExpectExceptionForNullAndEmptyStrings(myClass.MyMethod);
}
... and maybe another one for methods with a single parameter but a non-void return type.
That's possibly going a bit far though :)
If you use Java and JUnit you can use this syntax
#Test(expected = IllegalArgumentException.class)
public void ArgumentTest() {
myClass.MyMethod("");
myClass.MyMethod(null);
}

Resources