Solved

Working with Generics -- IList<T>

Posted on 2008-06-24
9
1,715 Views
Last Modified: 2013-12-16
Good evening experts:

My team is currently implementing an application that will manage a list of drugs.   To accomplish this task, we have implemented several data transfer objects to maintain these data.  One data transfer object, MyDrugList contains a single attribute of type List<DrugDetailDto> drug.   In this case, drug allows us to manage a list of drug objects .. add, remove, find, etc; however, upon submitting for code review, our enterprise architect pointed out a flaw in the development process and indicated we need not expose our List<T> objects:  ( http://msdn2.microsoft.com/en-us/library/ms182142(VS.80).aspx)

As an alternative, he suggested that we implement the IList interface to transfer objects between our layers.   I somewhat understand his requirement, but now some of our methods are not wanting to cooperate, which I've included below ..  

1) Could someone explain why this is an issue?
2) Could someone assist with how we can implement our search methods using these IList implementations?

We are using 2.0 Framework .. C#

Thanks,
Here is an example of where we search a DrugDetailDTO object for specific product data:
 
 /// <summary>//
        /// Extracts product information attached to a drug for a specified formulary
        /// </summary> 
        private DrugProductDTO GetProductDetail(DrugDetailDTO drug, string formularyID)
        {
            return drug.Products.Find(
                delegate(DrugProductDTO product)
                {
                    return product.ProductID.ToString().Equals(formularyID);
                }
                );
        }
 
AND
 
        /// <summary>
        /// Extracts Drugs information that has generics equivalents available
        /// </summary>
        private List<DrugDetailDTO> ExtractGenericsFromDrugList(List<DrugDetailDTO> myDrugList)
        {
            return myDrugList.FindAll(
                                      (
                                          delegate(DrugDetailDTO drug)
                                          {
                                              return drug.IsConvertibleToGenerics.Equals(true);
 
                                          }
                                      )
                                     );
 
 
        }
 
However, the find, findall, exists methods are not available with the IList interface.

Open in new window

0
Comment
Question by:escheider
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
  • 2
  • +1
9 Comments
 
LVL 11

Expert Comment

by:William
ID: 21861760
Have you looked at:
http://blogs.msdn.com/fxcop/archive/2006/04/27/585476.aspx
?

Let me know if this helps


BillyDvd
0
 
LVL 55

Expert Comment

by:Jaime Olivares
ID: 21861784
So, why don´t return a Collection<> instead as suggested in the MSDN site?
Collection have the IList interface also.
What the article suggest is not to use List<> generic class.
0
 
LVL 6

Accepted Solution

by:
cottsak earned 250 total points
ID: 21861988
you shouldnt have a MyDrugList object that exposes a List<T>. this is just some sort of container that should need to exist.
simply pass the List<DrugDetailDto> instances from layer to layer.
if the generic list (List<T>) search/find methods are not sufficient, then create a factory class that does the searching for you. ie:
List<DrugDetailDto> filteredResults = (new DrugDetailFactory()).Find(query);
you're custom logic would live in the Find() method above and return only the items in the list of the DrugDetailDto type that matched your query.. be that a string or maybe more params.. whatever.

below i have included some code to do in-memory filtering of generic lists. each entity item in the list must be able to expose all it's data as a string... so we override the ToString() method. i've done this by having the entity classes inherit from a Super Class which all entity classes use. this means they all have this functionality. - Snip#1
Snip#2 is a generic Filter class that returns filtered results based on the query string (filterExpression).
Snip#3 shows how i use this in a factory class for getting users... note that the filtering and sorting is optional. ignore the LINQ code if u want. :D

hope this helps. if u need more info just ask.
// Snip#1
        /// <summary>
        /// uses reflection to list public property info
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            string output = base.ToString() + " [" + this.GetHashCode() + "]" + Environment.NewLine;
 
            foreach (PropertyInfo property in this.GetType().GetProperties())
            {
                output += property.Name + ": "
                    + (property.GetValue(this, null) == null ? "null" : property.GetValue(this, null))
                    + Environment.NewLine;
            }
 
            return output;
        }
 
 
 
// Snip#2
    public class ListFilter<TEntity>
    {
        public List<TEntity> GetFilteredList(List<TEntity> list, string filterExpression)
        {
            List<TEntity> filteredResults = new List<TEntity>();
            int score = 0;
            string[] words = filterExpression.Trim().Split(' ');
 
            foreach (TEntity entity in list)
            {
                foreach (string word in words)
                    if (entity.ToString().ToLower().Contains(word.ToLower()))
                        score += 1;
 
                if (words.Length == score)
                    filteredResults.Add(entity);
 
                score = 0;
            }
 
            return filteredResults;
        }
    }
 
 
 
// Snip#3
    public class UserFactory : IRmsFactory<User, string>
    {
        public List<User> GetAll(string sortExpression, string filterExpression)
        {
            List<User> users = new List<User>();
            MembershipUserCollection allUsers = Membership.GetAllUsers();
 
            foreach (MembershipUser user in allUsers)
            {
                User u = new User();
                u.UserName = user.UserName;
                u.LastActivityDate = user.LastActivityDate;
                u.Roles = (new UserRoleFactory()).GetByUserName(user.UserName, String.Empty);
                users.Add(u);
            }
 
            // perform filtering before sort to reduce sort overhead if filter applied
            if (filterExpression != String.Empty && filterExpression != null)
                users = (new ListFilter<User>()).GetFilteredList(users, filterExpression);
 
            if (sortExpression != String.Empty && sortExpression != null)
                users.Sort(new EntityComparer<User>(sortExpression));
 
            return users;
        }

Open in new window

0
Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

 
LVL 6

Expert Comment

by:cottsak
ID: 21861996
EDIT (comment#21861988): there is no LINQ code there... that factory gets users from the Membership provider. other classes in that project used LINQ. sorry to confuse.
0
 
LVL 4

Author Comment

by:escheider
ID: 21862109
I can't pass the List<T> from layer to layer as we are using a controller and facade in the presentation layer that accesses the business and data layer located in web services [via a proxy], so the list of drugs must be serialized and returned to the controller for processing [display, navigation, etc].   Unfortunately, this strategy wouldn't pass our code review standards if I returned the List<T>
0
 
LVL 6

Expert Comment

by:cottsak
ID: 21863337
escheider,

sorry man. i'm not full-bottle enuf on using all those patterns togetha to suggest a solution that will comply with ur strict coding standards. perhaps your architect should suggest the solution.. thats his job right?
0
 
LVL 11

Assisted Solution

by:William
William earned 250 total points
ID: 21866075
The MSDN article:
The first reason is that List<T> is designed for speed and for use as an internal implementation detail, whereas Collection<T> is designed for extensibility.

I believe your architect is leaning this way for the extensibility of the Collection<T> model.
This will allow you much more flexibility in the future. Wich is always nice, although it is usually not apparent at first, maybe in 6mo or a yr or 2 when you need to go back in and 'add/mod' some code for new features ect...

It is more work up front but has way more payback later.

Just an idea if TIME is the issue...
Can you suggest an Interface for use (just for now) that has all your 'implementaion in upfront (even if it not coded yet [empty void and null returns/ throw new Not Implemented Exceptions from the class level)  ...  Just a thought

BillyDvd
0
 
LVL 4

Author Closing Comment

by:escheider
ID: 31470822
Thanks for clearing things up for me ..  we have decided to implement the Collection object, as it will be beneficial for us to determine when an object is added to the collection.   Thanks for all your assistance.
0
 
LVL 6

Expert Comment

by:cottsak
ID: 21871127
no sweat. it was learning for me too. ;)
0

Featured Post

Want Experts Exchange at your fingertips?

With Experts Exchange’s latest app release, you can now experience our most recent features, updates, and the same community interface while on-the-go. Download our latest app release at the Android or Apple stores today!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Update (December 2011): Since this article was published, the things have changed for good for Android native developers. The Sequoyah Project (http://www.eclipse.org/sequoyah/) automates most of the tasks discussed in this article. You can even fin…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
THe viewer will learn how to use NetBeans IDE 8.0 for Windows to perform CRUD operations on a MySql database.
The viewer will learn how to use and create keystrokes in Netbeans IDE 8.0 for Windows.

627 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question