Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1091691
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T23:34:09+00:00 2026-05-16T23:34:09+00:00

The below code is a factory class that is delivers objects of type IGraph

  • 0

The below code is a factory class that is delivers objects of type IGraph that have the GraphTypeAttribute implemented. Inside the static constructor of the GraphFactory, a list is built by using Linq to collect the appropriate classes to be delivered by the Factory. Normally without Linq I had a buch of loops and if-then’s that could be wrapped easily with appropriate try-catch blocks. Since all is stuffed in one query now I am a bit confused on how to implement proper exceptionhandling here.

So my question(s) is/are

  • What is the best pattern to handle exceptions on the linq query.
  • Should I split it in different queries or not use linq at all?
  • Or am I mising something in the query that can eliminate non-existing elements, scanning wrong classes etc, querying duplicate values etc (optimizing the query ;).

The result of the query must be a list of all classes that the factory can deliver. E.g. decorated with the attribute and the interface implemented.

A “Factory” that creates objects for graphical representation of data:

    public sealed class GraphFactory 
    {
    static readonly GraphFactory _instance = new GraphFactory();
    static readonly IDictionary<string, Type> _items;
    static readonly Assembly _assembly = Assembly.GetExecutingAssembly();

    public static GraphFactory Instance { get { return _instance; } }
    GraphFactory() { }

    static GraphFactory() {
        try
        {
            _items = (from type in _assembly.GetTypes()
                      // filter from thatonly the classes with IGraph implemented
                      where type.GetInterface(typeof(IGraph).FullName) != null
                      // filter from thatonly the classes with GraphTypeAttribute imp.
                      from attribute in type.GetCustomAttributes(true)
                      where attribute is GraphTypeAttribute
                      select new { attribute, type })
                     // convert the result from anonymous to a dictionary
                      .ToDictionary(k => (k.attribute as GraphTypeAttribute).CustomType, 
                                          e => e.type);
        }
        /** EXH: non pokemon exception handling  * ........... * **/
    }

    public static IEnumerable<string> FriendlyNames  { get { return _items.Keys; } }

    public static IGraph CreateGraph(string friendlyName)
    {
        /** inspect argument, check it's a key 
            in the dictionary and throw exeptions if needed **/     

        IGraph result = null;
        try
        {
            result = _assembly.CreateInstance(_items[friendlyName].FullName) as IGraph;
        }
        /** non pokemon exception handling * ...........  * **/
        return result;
    }
}

the interface (members ommitted):

public interface IGraph { } 

attribute to decorate the appropriate classes for factory assigment

[AttributeUsage(AttributeTargets.Class, AllowMultiple=false,Inherited=true)]
public class GraphTypeAttribute : System.Attribute 
{ public GraphTypeAttribute(string friendlyName)  { } }

the classes decorated with the attribute

[GraphTypeAttribute("piechart")]
public class PieChart : IGraph{ }

[GraphTypeAttribute("map")]
public class WorldMap : IGraph { }

[GraphTypeAttribute("horizontalbar")]
public class Bar : IGraph { }

[GraphTypeAttribute("verticalbar")]
public class VerticalBar : Bar { }

sample usage:

  foreach (string friendlyName in GraphFactory.FriendlyNames)
  {
   IGraph auth = GraphFactory.CreateGraph(friendlyName);
  }

Any other comments or advise on the class is thankfully appreciated.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T23:34:10+00:00Added an answer on May 16, 2026 at 11:34 pm

    I think this is a good example of the dynamic factory pattern. I do this all the time. I understand your concern about exception handling but I think there is no need for this, simply because your unit tests will prevent this factory from ever throwing during production and a good unit test can explain as clearly the problem as an exception message.

    But if you really want to do error checking, your LINQ query will never throw an exception. It is the ToDictionary that will throw when there is a double key. What you can do is validate the results of the LINQ query and communicate the double keys:

    static GraphFactory()
    { 
        var items = (
            from type in _assembly.GetTypes()
            where type.GetInterface(typeof(IGraph).FullName) != null
            from attribute in type.GetCustomAttributes(true)
                .OfType<GraphTypeAttribute>
            select new { attribute, type }).ToArray();
    
        ValidateTypes(items);
    
        _item = items.ToDictionary(
            k => k.attribute.CustomType, e => e.type);
    }
    
    private static void ValidateTypes<T>(T[] items)
    {
        var firstDoubleCustomType = (
            from item in items
            group item by item.attribute.CustomType into g
            where g.Count() > 1
            select g.Key).FirstOrDefault();
    
        if (firstDoubleCustomType != null)
        {
            throw new InvalidProgramException(
               "Doube: " + firstDoubleCustomType.ToString());
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

below code is my databasehandler class i got it from a tutorial. Beside that
I have to implement a factory method pattern in C++. The class (C) that
I have this working java code that serve as the datasource: public final class
Below is the code that I am using: This is my app/models file: class
The below code is very simple. I have a jQuery autocomplete bound to an
I have an object factory that hands out instances of a few constant, immutable
I have what I thought was a simple .NET Remoting Client/Server (Code Below)... When
I have a class which needs a string as a parameter in its constructor
The code below consists of two classes : SmartForm (simple model class) SmartForms (plural
I'm trying to create an EJB factory class, which works like this: You have

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.