I am trying to implement some graph searching algorithms in .NET for fun and personal education. For my implementation, I chose to start with a Node class that implemented the following interface:
public interface INode<T>
{
T Data { get; }
IDictionary<INode<T>, int> Neighbors { get; set; }
}
The node contains some Data of type T, as well as a dictionary of nodes that it shares an edge with along with their integer distance. I then thought that I could create an abstract Node class:
public abstract class Node<T> : INode<T>
{
public T Data { get; private set; }
public IDictionary<INode<T>, int> Neighbors { get; private set; }
public Node(T data, IDictionary<Node<T>, int> neighbors)
{
this.Data = data;
this.Neighbors = neighbors;
}
}
The above doesn't work, however, since neighbors doesn't match Neighbors. I would like whatever parameters are in Node's constructor to include an IDictionary of that specific type of Node and not just something that implements INode. For example, I might later create a concrete class called GraphNode, and I want to be sure that only GraphNodes are used in the constructor.
To solve this, I could simply take the IDictionary Neighbors out of INode and put it into the abstract Node class. This could limit my ability to test the class later on though using a framework like FakeItEasy, and I'm not sure what other implications it might have down the line.
I would appreciate some suggestions on how to generally approach this problem. If there is no best solution, then what are some pros and cons of various solutions?
Based on the given code, there are two things that you can do to make this compile.
First, the code also doesn't compile because INode<T> is not fully implemented. Your interface defines a set method for Neighbors, so your set will have to be public, or you will have to explicitly implement that property.
Second, presuming you really want to restrict your constructor to take neighbors as a dictionary keyed on the Node<T> class, and not the interface, the quickest thing you can do to load up this.Neighbors is change the line to
this.Neighbors = neighbors.ToDictionary(
neighborDistance => (INode<T>)neighborDistance.Key,
neighborDistance => neighborDistance.Value
);
Something like this must be done because generic IDictionary is not covariant.
Related
So I am trying to understand this sample code from Lynda.com without explanation.
IScore.cs
internal interface IScore
{
float Score { get; set; }
float MaximumScore { get; set; }
}
ScoreEntity.cs
internal class ScoreEntity : IScore
{
public float Score { get; set; }
public float MaximumScore { get;set;}
}
ScoreUtility.cs
internal class ScoreUtility
{
public static IScore BestOfTwo(IScore as1, IScore as2)
{
var score1 = as1.Score / as1.MaximumScore;
var score2 = as2.Score / as2.MaximumScore;
if (score1 > score2)
return as1;
else
return as2;
}
}
Calling code:
var ret = ScoreUtility.BestOfTwo(new ScoreEntity() { Score = 10, MaximumScore= 4},
new ScoreEntity() {Score = 10, MaximumScore = 6});
return;
My question is, in the ScoreUtility, what's really the benefit of using the interface type as return type in the method and argument type in the parameters, vs. just using ScoreEntity for the return and parameters, since the method itself returns a concrete object? Is this just to make the code looked 'smart'?
Any class that implements the IScore interface can be passed into the ScoreUtility method.
Perhaps there's a reason to implement another ScoreEntity class, like wanting to add a name seen in NamedScoreEntity :
internal class NamedScoreEntity: IScore
{
public string Name { get; set; }
public float Score { get; set; }
public float MaximumScore { get;set;}
}
If that's the case, then you can still use your utility methods on the new classes because of the contract the IScore interface enforces.
In this case, you could now compare the score between an un-named score object to a score object that also has a name.
Similarly, returning IScore allows the method to remain flexible enough to be used on multiple object types, and you can easily cast the returned type when you need to.
Given this declaration
public static IScore BestOfTwo(IScore as1, IScore as2)
The method does not know (or care) about the concrete types of as1 and as2. They may be ScoreEntity, or may be something entirely different. All it knows is that they implement IScore.
So if the method was to return a concrete type, then you have effectively limited the as1 and as2 parameters to being ScoreEntity, and have reduced its flexibility.
The only way you could guarantee that the method wouldn't fail would be to rewrite it as
public static ScoreEntity BestOfTwo(ScoreEntity as1, ScoreEntity as2)
In the posted code there is very little benefit, and I would argue that the interface should be removed. I would also argue that the comparison logic probably should be part of the object, or possibly an implementation of IComparer<T>.
Interfaces are most useful when there is a good reason for having multiple implementations. IComparer<T> is a great example, you might want to compare scores by the absolute score value, or the relative. So providing an abstraction is really useful.
Just applying interfaces to all classes is not a good idea, it will just make your code more complicated without any benefit. You might also discover that it can be difficult to provide a second implementation if the interface is not designed at the right abstraction level. This may result in adding properties or methods to objects that does not do anything or throws, just because they are required by a implemented interface. See for example IList<T> where many of the implementer throw exceptions for some of the methods.
In the specific case of IScore, it may be useful if you have some need for additional score-classes. But in many cases I would argue that composition might be more useful, i.e.
public class MyNamedScore{
public string Name {get;}
public ScoreEntity Score {get;}
}
I am looking for /tring to implement a type safe tree implementation in C#.
How can a type safe tree be implemented, without using interfaces (which force to reimplement the tree functionality all over the place) and without using casts?
I have the idea of using tree as common base class, but then type safety is gone. My current approach is usage generics. But I am missing some conversion back to the base type.
Below is a reduced/nonworking example.
The idea is that the returned Nodes support the tree functions, and at the same time they also support their base types behaviour.
I could use the below class without and inherit from Node, but then then I loose type safety on one hand, and also get problems with inheritance, as the Nodes have already parent classes.
I also toyed with class extensions, but I haven't got anything that is close to a possible solution.
I think i need one small hint on how to continue. Thank you in Advance.
public class Node<T> // .
{
public Node<T> parent;
public List<Node<T>> children;
protected Node()
{
children = new List<Node<T>>();
parent = null;
}
protected Node(Node<T> parent)
: this()
{
this.parent = parent;
parent.addChildren(this);
}
protected void addChildren(Node<T> child)
{
children.Add(child);
}
public Node<T> getRoot() // returns root node
public List<Node<T>> flatten() // return 1d-list of all nodes.
}
Here's a type-safe tree implementation:
public class Tree<T> : List<Tree<T>>
{
public T Value { get; set; }
}
Yes, that's it. Simple.
Of course, you could add a constructor or two, and make the Value property read-only to make it a little more OOP friendly. And you could easily add the Parent property.
I have the idea of using tree as common base class, but then type safety is gone. My current approach is usage generics. But I am missing some conversion back to the base type.
Then constraint the generic type to your base type:
public class Node<T> where T: BaseType { ... }
Now you can create any tree of the type Node<MyDerivedType> as long as MyDerivedType derives from BaseType.
On a side not, I'd consider modifying the following in your implementation:
Children should be a property, do not expose a field unless its readonly. Furthermore, you should not expose it as a List; that would let anyone add or remove nodes directly which can violate invariants assumed in your implementation. Return an IEnumerable<T> instead:
private readonly List<T> children;
public IEnumerable<T> Children => children.Select(c => c);
You could return children directly as its implicitly convertible to IEnumerable<T>; the problem is that anyone can simply cast it back to List<T> and modify it. Projecting it protects you from this conversion.
Same happens with Flatten (the first f should be capitalized btw). Consider returning an IEnumerable<T> too.
I have two data entities, which are almost similar, design is something like:
public Class Entity1 : Base
{
public int layerId;
public List<int> Groups;
}
Difference is Entity1 has an extra collection of integer Groups
public Class Entity2 : Base
{
public int layerId;
}
These entities are filled as an input from UI using Json, I need to pass them to a processing method, which gives the same Output entity. Method has a logic to handle if List<int> Groups is null, I need to create a method which is capable of handling each of the input in an elegant manner. I cannot just use only Entity1, since they are two different functional inputs for different business process, so using Entity1 as direct replacement would be a mis-representation
Instead of creating overload of the function, I can think of following options:
Use object type as input and typecast in the function internally
I think we can similarly use dynamic types, but solution will be similar as above, it will not be a clean solution in either case, along with the switch-case mess.
What I am currently doing is processing method is like this:
public OuputEntity ProcessMethod(Entity 1)
{
// Data Processing
}
I have created a constructor of Entity1, that takes Entity2 as Input.
Any suggestion to create an elegant solution, which can have multiple such entities. May be using generic, where we use a Func delegate to create a common type out of two or more entities, which is almost similar to what I have currently done. Something like:
Func<T,Entity1>
Thus use Entity1 output for further processing in the logic.
I need to create a method which is capable of handling each of the input in an elegant manner
Create an Interface, or a contract so to speak, where each entity adheres to the particular design. That way common functionality can be processed in a similar manner. Subsequently each difference is expressed in other interfaces and testing for that interface sis done and the differences handled as such.
May be using generic,
Generic types can be tested against interfaces and a clean method of operations hence follows suit.
For example say we have two entities that both have Name properties as string, but one has an Order property. So we define the common interface
public interface IName
{
string Name { get; set; }
string FullName { get; }
}
public interface IOrder
{
decimal Amount { get; set; }
}
So once we have our two entities of EntityName and EntityOrder we can add the interfaces to them, usually using the Partial class definition such as when EF creates them on the fly:
public partial class EntityName : IName
{
// Nothing to do EntityName already defines public string Name { get; set; }
public string FullName { get { return "Person: " + Name; }}
}
public partial class EntityOrder : IName, IOrder
{
// Nothing to do Entity Order already defines public string Name { get; set; }
// and Amount.
public string FullName { get { return "Order: " + Name; } }
}
Then we can process each of them together in the same method
public void Process(IName entity)
{
LogOperation( entity.FullName );
// If we have an order process it uniquely
var order = entity as IOrder;
if (order != null)
{
LogOperation( "Order: " + order.Amount.ToString() );
}
}
Generic methods can enforce an interface(s) such as:
public void Process<T>(T entity) where T : IName
{
// Same as before but we are ensured that only elements of IName
// are used as enforced by the compiler.
}
Just create generic method that will do this work for you:
List<OuputEntity> MyMethod<T>(T value) where T : Base
// adding this constraint ensures that T is of type that is derived from Base type
{
List<OutputEntity> result = new List<OutputEntity>();
// some processing logic here like ...
return result;
}
var resultForEntity1 = MyMethod<Entity1>();
var resultForEntity2 = MyMethod<Entity2>();
P.S. check my answer for this question as you may find it useful too:
map string to entity for using with generic method
You probably want to implement an interface or an abstract class.
From MSDN
If you anticipate creating multiple versions of your component, create
an abstract class. Abstract classes provide a simple and easy way to
version your components. By updating the base class, all inheriting
classes are automatically updated with the change. Interfaces, on the
other hand, cannot be changed once created. If a new version of an
interface is required, you must create a whole new interface.
If the functionality you are creating will be useful across a wide range of
disparate objects, use an interface. Abstract classes should be used
primarily for objects that are closely related, whereas interfaces are
best suited for providing common functionality to unrelated classes.
If you are designing small, concise bits of functionality, use
interfaces. If you are designing large functional units, use an
abstract class.
If you want to provide common, implemented
functionality among all implementations of your component, use an
abstract class. Abstract classes allow you to partially implement your
class, whereas interfaces contain no implementation for any members.
Abstract Class Example
Cat and Dog can both inherit from abstract class Animal, and this abstract base class will implement a method void Breathe() which all animals will thus do in exactly the same fashion. (You might make this method virtual so that you can override it for certain animals, like Fish, which does not breath the same as most animals).
Interface Example
All animals can be fed, so you'll create an interface called IFeedable and have Animal implement that. Only Dog and Horse are nice enough though to implement ILikeable - You'll not implement this on the base class, since this does not apply to Cat.
This is a problem which seems super basic but I still can't find a way to clear it. When I have a simple inheritance like B and C inheriting from A
A
|
|-----|
B C
Let's say these are interface like:
public interface A
{
List<A> Children { get; }
}
My issue: When I got through B.Children I have to cast it to B every time I want to use its specifics. Is there a way to have a list of children without having to declare the children in the leaves of the inheritance tree?
Precision: A child is always of the same type as its parent (or sub-type). And the tree can go deeper. As an example, think about a UI system with objects, containers, controls, labels where a class has as children only things of the same type or sub-types of itself.
Here is my code. I have the top level as
public interface ITerm
{
String text { get; }
}
Then, as offered by #Damien_The_Unbeliever
public interface ITerm<T> : ITerm where T : ITerm
{
List<T> Children { get; }
}
public interface ITermControl : ITerm<ITermControl> { ... }
public class TermControl : ITermControl { ... }
I am starting to think it is useless to have access to a List<ITerm> ITerm.Children as well as List<ITermControl> ITermControl.Children. That's what I was trying to explain.
Thanks
You might try doing this:
public interface A<T> where T: A<T> {
List<T> Children {get;}
}
Which Eric Lippert describes in his article Curiouser and Curiouser:
This is a C# variation on what's called the Curiously Recurring Template Pattern in C++, and I will leave it to my betters to explain its uses in that language. Essentially the pattern in C# is an attempt to enforce the usage of the CRTP.
And points out that it doesn't really enforce correct types throughout - so at best, it's a form of documentation rather than something that prevents bad things from happening.
excuse what seems like a real noobie question but how can I implement the following
public interface IViewModel {
void Map<T>();
}
public class CarViewModel : IViewModel
{
public string Color { get; private set; }
public int Tyres { get; private set; }
public CarViewModel(Car _car)
}
//this is where the problem is - there can be many differnt kind of object but I want them all to implement a Map function. I want to be able to assign the properties to incoming object. I also need to cater for IList of cars coming in that need to be populated. I suspect I am not using Generics properly
public void Map<T>(Car _car){
Color = _car.Color;
Tyres = _car.Tyres;
}
Do you mean this?
public interface IViewModel<T>
{
void Map(T domainObject);
}
public class CarViewModel : IViewModel<Car>
{
public Map(Car domainObject) { ... }
}
You say:
I suspect I am not using Generics properly
and you are correct. Additionally, you are not using polymorphism properly.
If you want to polymorphically accept several different types that all have something in common, then you need to create an interface that is the parent type of all of the types you will be using. You can do this without using any Generics at all.
What Generics (aka parametric polymorphism) gives you is a way to create one type that is parameterized by another type (and thus behaves like many different types). For example, IList<T> is parameterized by a type variable T -- then IList<string> and IList<int> are two separate types (with many possible subtypes each), but you only have to write the code once.
What are your actual requirements for this design? What are your ViewModel classes trying to accomplish?