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

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.

Related

Achilles Cassandra - Getting result of conditional update

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.

C# Store a generic list parameter as a instance scope variable

I have the following method:
public void SetList<T>(IList<T> listINeedToStore)
{
//Store the list in instance level scope
}
I would like to take the listINeedToStore parameter and store it in a private variable but I have failed to find a way. I tried to do something like private IList<object> _tempVariable; and then set _tempVariable to the listINeedToStore variable so I can use it later to remove or add items to it. I would set the list like _tempVariable = (IList<object>)listINeedToStore;. This does not work and will not compile. Something I should note is that T is a type of Enum.
I am sure there is a way to do this but I do not know it.
Thanks,
You can't do it in a generic way without making the type generic instead of the method, basically. You can store the reference, but it would have to be via a field of a non-generic type, e.g. IEnumerable or even just object. To really use the list, you'd have to fetch it again with a generic method, and cast. For example:
private object list;
public void SetList<T>(IList<T> list)
{
this.list = list;
}
public List<T> GetList<T>()
{
return (List<T>) list;
}
The fetch will fail at execution time if you specify the wrong type argument, of course.
I'd try to avoid this design if possible, but if you really need to do it, it will work. It just adds the burden of getting the type right to all the callers.
Note that if you change the parameter from IList<T> to List<T>, you could then store it in an IList (non-generic) which could be slightly more useful - but which would restrict the circumstances in which you could call the method, of course.

State Pattern and Domain Driven Design

We often use simple enumerations to represent a state on our entities. The problem comes when we introduce behaviour that largely depends on the state, or where state transitions must adhere to certain business rules.
Take the following example (that uses an enumeration to represent state):
public class Vacancy {
private VacancyState currentState;
public void Approve() {
if (CanBeApproved()) {
currentState.Approve();
}
}
public bool CanBeApproved() {
return currentState == VacancyState.Unapproved
|| currentState == VacancyState.Removed
}
private enum VacancyState {
Unapproved,
Approved,
Rejected,
Completed,
Removed
}
}
You can see that this class will soon become quite verbose as we add methods for Reject, Complete, Remove etc.
Instead we can introduce the State pattern, which allows us to encapsulate each state as an object:
public abstract class VacancyState {
protected Vacancy vacancy;
public VacancyState(Vacancy vacancy) {
this.vacancy = vacancy;
}
public abstract void Approve();
// public abstract void Unapprove();
// public abstract void Reject();
// etc.
public virtual bool CanApprove() {
return false;
}
}
public abstract class UnapprovedState : VacancyState {
public UnapprovedState(vacancy) : base(vacancy) { }
public override void Approve() {
vacancy.State = new ApprovedState(vacancy);
}
public override bool CanApprove() {
return true;
}
}
This makes it easy to transition between states, perform logic based on the current state or add new states if we need to:
// transition state
vacancy.State.Approve();
// conditional
model.ShowRejectButton = vacancy.State.CanReject();
This encapsulation seems cleaner but given enough states, these too can become very verbose. I read Greg Young's post on State Pattern Misuse which suggests using polymorphism instead (so I would have ApprovedVacancy, UnapprovedVacancy etc. classes), but can't see how this will help me.
Should I delegate such state transitions to a domain service or is my use of the State pattern in this situation correct?
To answer your question, you shouldn't delegate this to a domain service and your use of the State pattern is almost correct.
To elaborate, the responsibility for maintaining the state of an object belongs with that object, so relegating this to a domain service leads to anemic models. That isn't to say that the responsibility of state modification can't be delegated through the use of other patterns, but this should be transparent to the consumer of the object.
This leads me to your use of the State pattern. For the most part, you are using the pattern correctly. The one portion where you stray a bit is in your Law of Demeter violations. The consumer of your object shouldn't reach into your object and call methods on it's state (e.g. vacancy.State.CanReject()), but rather your object should be delegating this call to the State object (e.g. vacancy.CanReject() -> bool CanReject() { return _state.CanReject(); }). The consumer of your object shouldn't have to know that you are even using the State pattern.
To comment on the article you've referenced, the State pattern relies upon polymorphism as it's facilitating mechanism. The object encapsulating a State implementation is able to delegate a call to whichever implementation is currently assigned whether that be something that does nothing, throws an exception, or performs some action. Also, while it's certainly possible to cause a Liskov Substitution Principle violation by using the State pattern (or any other pattern), this isn't determined by the fact that the object may throw an exception or not, but by whether modifications to an object can be made in light of existing code (read this for further discussion).

Faking enums in Entity Framework 4.0

There are a lot of workarounds for the missing support of enumerations in the Entity Framework 4.0. From all of them I like this one at most:
http://blogs.msdn.com/b/alexj/archive/2009/06/05/tip-23-how-to-fake-enums-in-ef-4.aspx?PageIndex=2#comments
This workaround allows you to use enums in your LINQ queries which is what i exactly need. However, I have a problem with this workaround. I get for every complex type I'm using a new partial autogenerated class.Therefore the code does not compile any more because I already have a wrapper class with this name in the same namespace which converts betwen the backed integer in the database and the enum in my POCO classes. If I make my wrapper a partial class, the code still does not compile as it now contains two properties with the same name "Value". The only possibility is to remove the Value property by hand everytime I generate the POCO classes because the DB model changed (which during the development phase happens very often).
Do you know how to prevent a partial class to be generated out of complex property everytime the EF model changes?
Can you recommend me some other workarounds supporting enumerations in LINQ queries?
That workaround is based on the fact that you are writing your POCO classes yourselves = no autogeneration. If you want to use it with autogeneration you must heavily modify T4 template itself.
Other workaround is wrapping enum conversion to custom extension methods.
public static IQueryable<MyEntity> FilterByMyEnum(this IQueryable<MyEntity> query, MyEnum enumValue)
{
int val = (int)enumValue;
return query.Where(e => e.MyEnumValue == val);
}
You will then call just:
var data = context.MyEntitites.FilterByMyEnum(MyEnum.SomeValue).ToList();
I am using an approach based on the one described in your link without any modifications of the T4 templates. The contents of my partial wrapper classes are as follows:
public partial class PriorityWrapper
{
public Priority EnumValue
{
get
{
return (Priority)Value;
}
set
{
Value = (int)value;
}
}
public static implicit operator PriorityWrapper(Priority value)
{
return new PriorityWrapper { EnumValue = value };
}
public static implicit operator Priority(PriorityWrapper value)
{
if (value == null)
return Priority.High;
else
return value.EnumValue;
}
}
I've only changed that instead of a back store variable with enum value I am using the autogenerated int typed Value property. Consequently Value can be an auto-implemented property and EnumValue property needs to do the conversion in getter and setter methods.

How to adapt the Specification pattern to evaluate a combination of objects?

I know that the Specification pattern describes how to use a hierarchy of classes implementing ISpecification<T> to evaluate if a candidate object of type T matches a certain specification (= satisfies a business rule).
My problem : the business rule I want to implement needs to evaluate several objects (for example, a Customer and a Contract).
My double question :
Are there typical adaptations of the Specification patterns to achieve this ? I can only think of removing the implementation of ISpecification<T> by my specification class, and taking as many parameters as I want in the isSatisfiedBy() method. But by doing this, I lose the ability to combine this specification with others.
Does this problem reveal a flaw in my design ? (i.e. what I need to evaluate using a Customer and a Contract should be evaluated on another object, like a Subscription, which could contain all the necessary info) ?
In that case (depending on what the specification precisely should do, I would use one of the objects as specification subject and the other(s) as parameter.
Example:
public class ShouldCreateEmailAccountSpecification : ISpecification<Customer>
{
public ShouldCreateEmailAccountSpecification(Contract selectedContract)
{
SelectedContract = selectedContract;
}
public Contract SelectedContract { get; private set; }
public bool IsSatisfiedBy(Customer subject)
{
return false;
}
}
Your problem is that your specification interface is using a generic type parameter, which prevents it from being used for combining evaluation logic across different specializations (Customer,Contract) because ISpecification<Customer> is in fact a different interface than ISpecification<Contract>. You could use Jeff's approach above, which gets rid of the type parameter and passes everything in as a base type (Object). Depending on what language you are using, you may also be able to pull things up a level and combine specifications with boolean logic using delegates. C# Example (not particularly useful as written, but might give you some ideas for a framework):
ISpecification<Customer> cust_spec = /*...*/
ISpecification<Contract> contract_spec = /*... */
bool result = EvalWithAnd( () => cust_spec.IsSatisfiedBy(customer), () => contract_spec.IsSatisfiedBy( contract ) );
public void EvalWithAnd( params Func<bool>[] specs )
{
foreach( var spec in specs )
{
if ( !spec() )
return false; /* If any return false, we can short-circuit */
}
return true; /* all delegates returned true */
}
Paco's solution of treating one object as the subject and one as a parameter using constructor injection can work sometimes but if both objects are constructed after the specification object, it makes things quite difficult.
One solution to this problem is to use a parameter object as in this refactoring suggestion: http://sourcemaking.com/refactoring/introduce-parameter-object.
The basic idea is that if you feel that both Customer and Contract are parameters that represent a related concept, then you just create another parameter object that contains both of them.
public class ParameterObject
{
public Customer Customer { get; set; }
public Contract Contract { get; set; }
}
Then your generic specification becomes for that type:
public class SomeSpecification : ISpecification<ParameterObject>
{
public bool IsSatisfiedBy(ParameterObject candidate)
{
return false;
}
}
I don't know if I understood your question.
If you are using the same specification for both Customer and Contract, this means that you can send the same messages to both of them. This could be solved by making them both to implement an interface, and use this interface as the T type. I don't know if this makes sense in your domain.
Sorry if this is not an answer to your question.

Resources