Collection vs ICollection - asp.net

I have created a dummy projet for testing collection and ICollection.I have a user class and wanted to create a collection.Example -
ICollection<User> users = new Collection<User>();
Collection<User> users = new Collection<User>();
Both code are working fine whether I use Collection or I collection.Now can anyone tell me what is difference between above two line?
Thanks in advance.

The first line ICollection<User> users = new Collection<User>(); creates a reference to an object (Collection) that implements the ICollection interface whereas the second line Collection<User> users = new Collection<User>(); creates a reference to an object that is a concrete implementation of the class Collection where T = User.
In usage terms you would look to use the ICollection reference where your subsequent code needed to be agnostic about the type of collection it was dealing with, i.e. you could provide any object that implements ICollection and your code would still work. Great if your code is not tightly coupled (which we all want of course).
Using Collection as the reference tightly couples your processing code to Collection class, a specific implementation of ICollection and while you might still only use the methods defined in the interface, you might also use some specific features of the class and then you won't be able to easily replace the collection object with something different. There are good reasons for this but it's bit beyond the scope of an answer here, search for Dependency Injection and Inversion of Control here and I'm sure you'll find loads of background info.

Collection<T> is just an implementation of ICollection<T>. If someone creates another class that implements from ICollection<T>, you can easily use that one by replacing your first line with:
ICollection<User> users = new MyCustomCollectionCollection<User>();
Later on in the code, you don't have to fix anything since the same interface is still used.

ICollection is an Interface. Collection implements ICollection, so it works. ICollection is not a class, so this wont work:
ICollection<User> users = new ICollection<User>();
..because you can't instantiate an interface. An interface just describes what a class must implement.

because users is reference. in both samples it points to same object. behavior is defined by class of object and it is same.

Related

Method types within a Class in VB.NET 4.0

A friend asked me this and not sure how to understand. Prolly a simple answer.
He has the following
Public Class TestClass
Public Sub Setup()
MsgBox ("Hello")
End Sub
End Class
Based on that example, what type of member is Setup, in relation to the TestClass class?
I think it it might be an instance member. Because a class is just a collection of instances (methods, properties, etc) within the class.
Correct?
This would be an instance method as opposed to a class method (static methods).
When a field, method, property, event, indexer, constructor, or destructor declaration does not include a static modifier, it declares an instance member.
More information here.
Initially my answer said that a member is the same as a field. According to the MSDN link above this was not entirely correct so I adjusted it. You'll also notice that they use the term static member instead of instance member.
Terminology is a very tricky subject and you'll notice people use many different descriptions for the same subject. This is further amplified when you take other languages in consideration and the terminology there.
It is an instance method, but not because a class is a collection of instances.
It is an instance method because TestClass is not shared (static), and must be instantiated. That is, there must be a instance of TestClass available to use its method Setup(). Conversely, with a Shared class, you do not need an instance of TestClass to use Setup(), it would be a Shared method and not an instance method.
That is academic, however, since VB does not support static classes (Shared Classes), but does support shared methods, the effective difference is that declaring Setup() as Public makes it an instance method, or declaring it as Shared would make it a static method.

Class with PersistenceCapable annotation gets Attempt to store an instance of a non persistable type

Using ObjectDB
[ObjectDB 2.4.1] javax.jdo.JDOUserException
Attempt to store an instance of a non persistable type com.A
#PersistenceCapable
public abstract class B
{
...
#Embedded
protected com.A a = new A();
}
Unfortunately we have been using class A from a library for many years and don't have source available anymore and I cannot put PersistenceCapable annotation on com.A.java. What can I do?
Edit
I think the answer is to add package.jdo for class A. But I still don't understand why is JDO making me either add annotation or make an entry in .jdo file for every class that i want to persist. I wish this could somehow be driven by Serializable interface.
Serialization in ObjectDB is disabled by default, in order to encourage using JPA/JDO persistable types (entity classes, persistence capable classes, embeddable classes), which are more efficient, whenever possible.
However, when serialization is required you can enable it, as explained in the ObjectDB manual.
and then you should be able to store instances of serializable instances in your ObjectDB database.

Understanding the use of Interfaces and Base Classes

I know there are a number of post out there on Interfaces and Base classes, but I'm having a hard time getting the correct design pattern understanding.
If I were to write a reporting class, my initial though would be to create an interface with the core properties, methods, etc. that all reports will implement.
For example:
Public Interface IReportSales
Property Sales() As List(Of Sales)
Property ItemTotalSales() As Decimal
End Interface
Public Interface IReportProducts
Property Productss() As List(Of Inventory)
Property ProductsTotal() As Decimal
End Interface
Then I assume I would have a class to implement the interface:
Public Class MyReport
Implements IReportSales
Public Property Sales() As System.Collections.Generic.List(Of Decimal) Implements IReportItem.Sales
Get
Return Sales
End Get
Set(ByVal value As System.Collections.Generic.List(Of Decimal))
Items = value
End Set
End Property
Public Function ItemTotalSales() As Decimal Implements IReport.ItemTotalSales
Dim total As Decimal = 0.0
For Each item In Me.Sales
total = total + item
Next
End Function
End Class
My thought was that it should be an interface because other reports may not use "Items", this way I can implement the objects that are used for a given report class.
Am I way off? should I have still have just created a base class? My logic behind not creating a base class was that not all report classes may use "Items" so I didn't want to define them where they are not being used.
To attempt to answer you question, abstract classes are used to provide a common ancestor for related classes. An example of this in the .Net API is TextWriter. This class provides a common ancestor all various classes whose purpose is to write text in some fashion.
Interfaces are more properly used to act as adapters for different objects that don't belong in the same "family" of objects but have similar capabilities. A good example of this can be seen with the various collections in the .Net API.
For example, the List and Dictionary classes provide the ability for you to manage a collection of objects. They do not share a common ancestor by inheritance, this wouldn't make sense. In order to allow easy interop between them though, they implement some of the same interfaces.
Both classes implement IEnumerable. This cleanly allows you use objects of either type List or Dictionary as an operand for anything that requires an IEnumerable. How wonderful!
So now in your case in designing new software you want to think about how this would fit into your problem space. If you give these classes a common ancestor via inheritance of an abstract class you have to be sure that all the items that inherit from it are truly of the base type. (A StreamWriter is a TextWriter, for example). Inappropriate use of class inheritance can make your API very difficult to build and modify in the future.
Let's say you make an abstract class, ReportBase, for your repots. It may contain a few very generic methods that all reports simply must have. Perhaps it simply specifies the method Run()
You then only have one type of report you want to make so you define a concrete Report class that inherits from ReportBase. Everything is great. Then you find out you need to add several more types of reports, XReport, YReport, and ZReport for sake of example. It doesn't really matter what they are, but they work differently and have different requirements. All of the reports generate pretty HTML output and everyone is happy.
Next week your client says they want XReport and YReport to be able to output PDF documents as well. Now there are many ways to solve this, but obviously adding an OutputPdf method to your abstract class is a poor idea, as some of those reports shouldn't or can't support this behavior!
Now this is where interfaces could be useful to you. Let's say you define a few interfaces IHtmlReport and IPdfReport. Now the report classes that are supposed to support these various output types can implement those interfaces. This will then let you create a function such as CreatePdfReports(IEnumerable<IPdfReport> reports) that can take all reports that implement IPdfReport and do whatever it needs to do with them without caring what the appropriate base type is.
Hopefully this helps, I was kind of shooting from the hip here as I'm not familiar with the problem you're trying to solve.
Yes, if you don't know how many reports are not going to use Items , you can go for Abastract class.
Another good thought follows:
You can also create both Interface and Abstract class
Define Sales in Interface , create two abstract classes , one for Reports that implement both and another for Report not implementing Sales. Implement interface for both
define both method (implement sales) in first and only implement sales in second.
Give appropriate names to both Abstract classes e.g. ReportWithItemsBase or ReportWithoutItemsBase.
This way you can also achieve self explaining named base classes on deriving Report classes as well.

ASP.NET EntityFramework 4 data context issues

I'm working on a site and there are two projects in the solution a business logic project and the website project. I understand that I want to keep the entity context out of the web project and only use the business objects the framework creates but I can't figure out how to save a modified object this way.
Let's say my entity model created this class:
public class Person //Person entity
{
Int32 Id {get;set;}
String Name {get;set;}
Address Address {get;set;} //Address entity
}
And I created this class to get a specific person:
public static class PersonController
{
public static Person GetById(int id)
{
using (Entities context = new Entities())
{
return context.Persons.FirstOrDefault(x => x.Id == id);
}
}
}
This allows me to get a person without a context by calling PersonController.GetById(1); and I can change the persons properties after I get them but I can't figure out how to save the modified information back to the database. Ideally I would like to partial class Person and add a .Save() method which would handle creating a context adding the person to it and saving the changes. But when I tried this a while ago there were all kinds of issues with it still being attached to the old context and even if I detatch it and attatch it to a new context it gets attached as EntityState.Unchanged, if I remember right, so when I call context.SaveChages() after attaching it nothing actually gets updated.
I guess I have two questions:
1) Am I going about this in a good way/is there a better way? If I'm doing this in a really terrible way I would appreciate some psudo-code to point me in the right direction; a link to a post explaining how to go about this type of thing would work just as well.
2) Can someone provide some psudo-code for a save method? The save method would also need to handle if an address was attached or removed.
There are many ways to handle Entity Framework as a persistence layer.
For one, it looks like you're not using pure POCOs. That is, you let EF generate the classes for your (in the EDMX.designer.cs file).
Nothing wrong with that, but it does inhibit a clean separation of concerns (especially when it comes to unit testing).
Have you considering implementing the Repository pattern to encapsulate your EF logic? This would be a good way to isolate the logic from your UI.
In terms of Save - this is where it gets difficult. You're right, most people use partial classes. Generally, you would have a base class which exposes a virtual "Save" method, which the partial classes can then override.
I personally don't like this pattern - i believe POCOs should not care about persistence, or the underlying infrastructure. Therefore I like to use pure POCOs (no code gen), Repository pattern and Unit of Work.
The Unit of Work handles the context opening/saving/closing for you.
This is how (my) Unit of Work does the magic. Consider this some code in your "Web" project:
var uOw = new UnitOfWork(); // this is class i created, implementing the UOW pattern
var person = repository.Find(10); // find's a "Person" entity (pure POCO), with id 10.
person.Name = "Scott";
uOw.Commit();
Or adding a new Person:
var uOw = new UnitOfWork();
var newPerson = new Person { Name = "Bob" };
repository.Add(newPerson);
uOw.Commit();
How nice is that? :)
Line 1 creates a new sql context for you.
Line 2 uses that same context to retrieve a single "Person" object, which is a hand-coded POCO (not generated by EF).
Line 3 changes the name of the Person (pure POCO setter).
Line 4 Saves the changes to the data context, and closes the context.
Now, there is a LOT more to these patterns than that, so I suggest you read up on these patterns to see if it suits you.
My repository is also implemented with Generics, so I can re-use this interface for all business entity persistence.
Also take a look at some of the other questions I have asked on Stack Overflow - and you can see how I've implemented these patterns.
Not sure if this is the "answer" you're looking for, but thought I'd give you some alternative options.

When should the factory pattern be used?

Just as the title asks, when should a trigger in your head go off signifying "Aha! I should use the factory pattern here!"? I find these moments will occur with many other design patterns, but never do I stop myself and think about this pattern.
Whenever you find yourself with code that looks something like this, you should probably be using a factory:
IFoo obj;
if ( someCondition ) {
obj = new RegularFoo();
} else if ( otherCondition ) {
obj = new SpecialFoo();
} else {
obj = new DefaultFoo();
}
The factory pattern is best employed in situations where you want to encapsulate the instantiation of a group of objects inside a method.
In other words, if you have a group of objects that all inherit from the same base class or all implement the same interface that would be an instance where you would want to use the factory pattern (that would be the "pattern" you would look for).
I can think of two specific cases that I think of the factory pattern:
When the constructor has logic in it.
When I don't want the application to worry about what type gets instantiated (eg, I have an abstract base class or interface that I am returning).
Quoted from GoF:
Use the Factory Method pattern when
a class can't anticipate the class of objects it must create
a class wants its subclasses to specify the object it creates
classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.
I highly recommend the GoF book. It has a section on the applicability of each of the 23 patterns it covers.
Are you talking about Factory Method or Abstract Factory?
The basic problem that both solve is letting clients specify the exact class that framework code constructs. For example, if you provide an interface, that clients can implement, and then in your code have something like:
IMyInterface x = new ConcreteClass();
There is no way for clients to change the exact class that was created without access to that code.
A Factory Method is a virtual method that constructs a concrete class of a specific interface. Clients to your code can provide an object that overrides that method to choose the class they want you to create. It might look like this in your code:
IMyInterface x = factory.Create();
factory was passed in by the client, and implements an interface that contains Create() -- they can decide the exact class.
Abstract Factory should be used if you have hierarchies of related objects and need to be able to write code that only talks to the base interfaces. Abstract Factory contains multiple Factory Methods that create a specific concrete object from each hierarchy.
In the Design Patterns book by the Gang of Four, they give an example of a maze with rooms, walls and doors. Client code might look like this:
IRoom r = mazeFactory.CreateRoom();
IWall nw = mazeFactory.CreateWall();
IWall sw = mazeFactory.CreateWall();
IWall ew = mazeFactory.CreateWall();
IWall ww = mazeFactory.CreateWall();
r.AddNorthWall(nw);
r.AddSouthWall(sw);
r.AddEastWall(ew);
r.AddWestWall(ww);
(and so on)
The exact concrete walls, rooms, doors can be decided by the implementor of mazeFactory, which would implement an interface that you provide (IMazeFactory).
So, if you are providing interfaces or abstract classes, that you expect other people to implement and provide -- then factories are a way for them to also provide a way for your code to construct their concrete classes when you need them.
Factories are used a lot in localisation, where you have a screen with different layouts, prompts, and look/feel for each market. You get the screen Factory to create a screen based on your language, and it creates the appropriate subclass based on its parameter.

Resources