Code Contracts: How to deal with inherited interfaces? - code-contracts

I'm using MS Code Contracts and have run into a snag with using interface inheritance and ContractClassFor attributes.
Given these interfaces and contract classes:
[ContractClass(typeof(IOneContract))]
interface IOne { }
[ContractClass(typeof(ITwoContract))]
interface ITwo : IOne { }
[ContractClassFor(typeof(IOne))]
abstract class IOneContract : IOne { }
[ContractClassFor(typeof(ITwo))]
abstract class ITwoContract : IOneContract, ITwo { }
Let's say that IOne and ITwo are substantial interfaces. So IOneContract would have a significant amount of code in it for the necessary checks.
I don't want to duplicate all of that in ITwoContract for the IOne interfaces. I only want to add new contracts for the ITwo interfaces. Inheriting one contract class from another seems the likely way to reuse that code. Yet I get the following error:
EXEC : warning CC1066: Class 'ITwoContract' is annotated as being the contract for the interface 'ITwo' and cannot have an explicit base class other than System.Object.
Is this a limitation in Code Contracts or am I doing it wrong? We have a lot of interface inheritance in our project and this feels like a deal breaker for Code Contracts if I can't figure out how to work around this issue.

Instead of:
[ContractClassFor(typeof(ITwo))]
abstract class ITwoContract : IOneContract, ITwo { }
Just inherit the contract:
[ContractClassFor(typeof(ITwo))]
abstract class ITwoContract : ITwo { }
You only need to provide contracts on the methods which are new in ITwo. The contracts from IOneContract will be inherited automatically, and you can declare all the inherited IOne methods as abstract — in fact, you cannot provide contracts for IOne on ITwoContract, or CC will complain :)
For example, if you have this:
[ContractClass(typeof (IOneContract))]
interface IOne
{
int Thing { get; }
}
[ContractClass(typeof (ITwoContract))]
interface ITwo : IOne
{
int Thing2 { get; }
}
[ContractClassFor(typeof (IOne))]
abstract class IOneContract : IOne
{
public int Thing
{
get
{
Contract.Ensures(Contract.Result<int>() > 0);
return 0;
}
}
}
[ContractClassFor(typeof (ITwo))]
abstract class ITwoContract : ITwo
{
public int Thing2
{
get
{
Contract.Ensures(Contract.Result<int>() > 0);
return 0;
}
}
public abstract int Thing { get; }
}
Then this implementation will say "unproven contract" on both methods, as expected:
class Two : ITwo
{
public int Thing
{
get { return 0; }
}
public int Thing2
{
get { return 0; }
}
}

Related

Map to specific derived type based on value on source using Automapper

I'm having trouble implementing Automapper conversion in a situation where the source is a class which should be mapped to one of two derived classes based on a value on the source.
Here's a simplification of my classes:
public class FooContainerDTO
{
public FooDTO Foo { get; set; }
}
public class FooDTO
{
public string Type { get; set; }
//some properties..
}
public class FooContainer
{
public FooBase Foo { get; set; }
}
public abastract class FooBase
{
//some properties..
}
public class FooDerived1 : FooBase
{
//some properties
}
public class FooDerived2 : FooBase
{
//some properties
}
I'm using non-static Automapper so I create a MapperConfiguration from several Profiles at boot and inject the IMapper instance into my DI-container.
I want Automapper to map FooDTO to FooDerived1 when its Type property is "der1" and to FooDerived2 when it is "der2".
I've seen examples on this using the static api, something like this:
Mapper.CreateMap<FooContainerDTO, FooContainer>();
//ForMember configurations etc.
Mapper.CreateMap<FooDTO, FooDerived1>();
//ForMember configurations etc.
Mapper.CreateMap<FooDTO, FooDerived2>();
//ForMember configurations etc.
Mapper.CreateMap<FooDTO, FooBase>()
.ConvertUsing(dto => dto.Type == "der1"
? (FooBase) Mapper.Map<FooDerived1>(dto)
: Mapper.Map<FooDerived2>(dto));
This would map the Foo property of FooContainer to the correct derived type of FooBase.
But how can I do this without the static API?
The IMapper instance is not yet created at the point of configuring the profile.
Is there a way to leverage the overload of ConvertUsing() which takes a Func< ResolutionContext,object >? Can the resolution context give me whatever IMapper is currently being used? I've been looking, but can't find anything usable.
One way to get access to the mapping engine is via your own TypeConverter
abstract class MyTypeConverter<TSource,TDestination> : ITypeConverter<TSource, TDestination>
{
protected ResolutionContext context;
public TDestination Convert(ResolutionContext context)
{
this.context = context;
return Convert((TSource)context.SourceValue);
}
public abstract TDestination Convert(TSource source);
}
You then create an actual implementation like:
class MyTypeMapper : MyTypeConverter<EnumType,EnumTypeView>
{
public override EnumTypeView Convert(EnumType source)
{
return context.Engine.Mapper.Map<EnumTypeID, EnumTypeView>(source.EnumBaseType);
}
}
Except instead of unwrapping an enum structure, you'd check the type and call Map with different types.

Inheritance Generic Invariance C#4

I've been searching why this generic contruction doesn't compile
I get:
Cannot implicitly convert type 'WpfApplication1.CowDao' to 'WpfApplication1.Dao'
public abstract class Animal { }
public class Dog : Animal { }
public class Cow : Animal { }
public abstract class Dao<T> where T : Animal
{
public void Insert(T t);
}
public class DogDao : Dao<Dog> { }
public class CowDao : Dao<Cow> { }
public class Main
{
public Main()
{
Dao<Animal> dao = null;
if (true) dao = new DogDao();
else dao = new CowDao();
}
}
I just want to get to my goal --> making a 'neutral' instance
I think that my construction has to change, but i don't know how
I'm using .NET Framework 4
Thanks
Generics from a derived does not inherit from Generic from a base class so you may not cast one to another. Instead, write an extension method ToGenericParent that converts like that:
public static Generic<Parent> ToGenericParent(this Generic<Derived> derived)
{
return new Generic<Parent>() { Value = derived.Value };
}
Change your Inheritance for your Dao layers as
public class DogDao : Dao<Animal> { }
public class CowDao : Dao<Animal> { }
Edit:
public abstract class Dao<T> where T : Animal
{
public virtual void Insert(T t)
{
}
protected void ExecuteQuery(string quer)
{
}
}
public class DogDao : Dao<Dog>
{
public override void Insert(Dog t)
{
string insert = "INSERT INTO DOG ...";
base.ExecuteQuery(insert);
}
}
public class CowDao : Dao<Cow>
{
public override void Insert(Cow t)
{
string insert = "INSERT INTO COW ...";
base.ExecuteQuery(insert);
}
}

Abstract factory bad design?

I have car factories that build cars of different sizes.
I have 2 factories: USA and Thailand that make car sizes Big, Middle, and Little.
But I have a problem: the Thailand factory does not make big cars.
Code:
public enum CarSize { Big, Middle, Little,}
public interface ICarFactory {
ICar CreateCar(CarSize carSize);
}
public class USACarFactory : ICarFactory {
public ICar CreateCar(CarSize carSize) {
ICar car = null;
switch (carSize) {
case CarSize.Little:
car = new USALittleCar();
break;
case CarSize.Middle:
car = new USAMiddleCar();
break;
case CarSize.Big:
car = new USABigCar();
break;
}
return car;
}
}
public class ThailandCarFactory : ICarFactory {
public ICar CreateCar(CarSize carSize){
ICar car = null;
switch (carSize) {
case CarSize.Little:
car = new ThailandLittleCar();
break;
case CarSize.Middle:
car = new ThailandMiddleCar();
break;
case CarSize.Big:
//no big cars in Thailand!!!!
break;
}
return car;
}
}
public interface ICar { }
public class USABigCar : ICar { }
public class USAMiddleCar : ICar { }
public class USALittleCar : ICar { }
public class ThailandMiddleCar : ICar { }
public class ThailandLittleCar : ICar { }
What should I do?
Is my Abstract Factory poorly designed?
#zzfima, picking up the idea from COM, how about querying the interface and find out it if supports creating car of a specified size and invoke suitably? The code definitely realizes the abstract factory pattern.
case CarSize.Big:
car = new ThailandBigCar();
break;
Try that. That should allow you to make big cars.
public interface ICar { }
public class USABigCar : ICar { }
public class USAMiddleCar : ICar { }
public class USALittleCar : ICar { }
public class ThailandMiddleCar : ICar { }
public class ThailandLittleCar : ICar { }
public class ThailandBigCar : ICar { }

How to define a constraint on class type if It has custom attribute?

there is any way to force a class to implement an interface , if It has an specific custom attribute?
I want to have a compile time error , if the class with specific attribute does not implement an specific interface.
[myAttrib]
public MyClass:IMyInterface
{
}
If myClass is not typeof(IMyInterface) , I will get an error in compile time.
thanks,
In case of properties, You could create an abstract class inheriting the interface and gets your final class drive from that abstract class.
Have a look at
public interface Test
{
string Name { get; set; }
}
public abstract class Test1 : Test
{
public abstract string Name { get; set; }
}
public class Test2 : Test1
{
}
For custom attribute you could do
public class Alias : System.Attribute
{
string[] _types;
public Alias(params string[] types)
{
this.Types = types;
}
public Alias()
{
this.Types = null;
}
public string[] Types
{
get { return _types; }
set { _types = value; }
}
}
public interface Test
{
Alias Attrib{ get;}
}
public abstract class Test1 : Test
{
public abstract Alias Attrib { get; }
}
public class Test2 : Test1
{
}
Hope I answer your question.

Optional component functionality vs SRP

I have a design issue that I encounter currently.
Let's say there is a hierarchy of components. Each of these component derives from an abstract Component type which looks something like this:
public abstract class Component
{
public abstract Component Parent { get; }
public abstract ComponentCollection Children { get; }
}
Now I want to add some optional functionality to those components, lets take being able to search within the component hierarchy and to select components within the hierarchy as examples.
Is it considered bad practice to provide those optional functionality in the base class like this:
public abstract class Component
{
// Other members
public abstract bool IsSearchable { get; }
public abstract bool Search(string searchTerm);
public abstract bool IsSelectable { get; }
public abstract bool Select();
}
While the "search-ability" and "select-ability" is managed in derived components by e.g. using strategy patterns?
Somehow this seems like violation of the SRP to me, but in my opinion the only alternative would be to have an interface for each optional functionality and only implement it on components that support this functionality.
In my opinion this would have the drawback that I have to write code like this everytime I want to check if a component provides specific functionality:
public bool Search(Component component, string searchTerm)
{
ISearchable searchable = component as ISearchable;
if(searchable != null)
{
searchable.Search(searchTerm);
}
}
Which strategy would you choose or do you have any better ideas?
Thanks in advance!
A possible option:
If the searchability/selectability implementation is provided through the strategy pattern (dependency injection), as you say, then I think interfaces for ISearchable and ISelectable are a better idea.
You can derive your strategy object from these interfaces, and implement getters for them in your base-Component class - GetSearchable(), GetSelectable() - where the default implementation in Component returns null (or a no-op implementation of the interface if you dislike null).
Why don't you use decorator?
Component c = new Component ();
var selectableAndSearchableOne = new SelectableComponent (new SearchableComponent (c));
Ok another one: this time you also know the component's extension points. with a visitor-like pattern
public interface IHasExtensions
{
List<Extension> Extensions { get; }
void Extend (Extension ext);
}
public class Component : IHasExtensions
{
List<Extension> exts = new List<Extension> ();
public List<Extension> Extensions
{
get { return exts; }
}
public void Extend (Extension ext)
{
exts.Add (ext);
}
void Draw() { }
}
public abstract class Extension
{
readonly protected Component _Component;
public Extension(Component component)
{
_Component = component;
}
}
public class SearchExtension : Extension
{
public SearchExtension (Component component) : base (component)
{
}
}
public class SelectionExtension : Extension
{
public SelectionExtension (Component component) : base (component)
{
}
}
public class test_fly
{
void start ()
{
Component c = new Component ();
c.Extend (new SearchExtension (c));
c.Extend (new SelectionExtension (c));
var exts = c.Extensions; // I Know the extensions now
}
}

Resources