I know how to utilize the ConcurrentDictionary<TKey, TValue> class by using a GetOrAdd() method very nicely. Is there a similar class for a single object instead? I'd rather not create a dictionary for a single object just to get concurrency.
Right now, I'm doing the following:
return _singledict.GetOrAdd(_sync, CreateSingleItem);
It sounds like you want to have some means of accessing an existing object if it has already been constructed, and constructing a new one if it hasn't been, with the appropriate tools in place to prevent the construction of multiple objects.
This is exactly what Lazy<T> exists for.
Related
Lets say we have class SomeObject with many fields and storing instances in HashSet.
For HashSet comprison we need only one field: int ID, so we have overriden GetHashCode() and Equals() methods.
And now my question is: Can we somehow use hashSet.Contains(someIntVariable) instead of creating whole new object of type SomeObject?
I mean if only int field is important can we use Contains function with int argument given?
I need it to check if object already exists and don't want create whole sample object.
HashSet unfortunately does not have the ability to search with a different type of objects and get what's stored. This capability could theoretically exist and maybe you can find a collection library on the web that does this.
Best workaround:
Create a separate key struct (e.g. MyKey) and use a Dictionary<MyKey, MyValue>. That way you can create a key without creating an object.
Alternatively, you could create a wrapper struct that encapsulates either a key or a whole object. You can than cheaply instantiate that struct and pass it to the HashSet. I find that to be more complicated than the first idea.
how is a tuple different from a class? instead of the following code, we can make a class with 3 fields and make objects from it. How is this Tuple different from that? Is it only reducing the code we write or does it have something to do with speed as well, given the fact that you can't change the items in a tuple.
Tuple<int, string, bool> tuple = new Tuple<int, string, bool>(1, "cat", true);
It saves you from having to define a new class with custom properties.
It does define equality by the value of the three items, which is something that a bare-bones class would not do without custom coding. That plus the fact that it's immutable makes it a reasonable candidate for a hash key in a Dictionary.
One drawback is that the properties are vanilla Item1, Item2, etc., so they don't provide any context to the values within them, where properties like ID, Name, Age would.
Tuple is a class. One that holds any data you want (in terribly named properties like Item1).
You should be making classes instead so your code is more readable/maintainable. Its primary function is as a "quick fix" when you want to associate pieces of data without making a class to hold them.
Tuples are in my opinion an invitation to bad data modeling. Instead of creating a proper model you get a generic object that can hold n item properties. The naming is very generic too.. Item1..ItemN
You use Tuples as a mean to pass data between method call without having to define a new class. Typically use to return multiple pieces of data from a method rather than use "out" parameters.
Keep in mind that out parameter cannot be use with async/await methods, this is where Tuples come in handy.
You probably want to define a class for your data if you code a reusable class library though. However, tuple is great in presentation layer.
I have an array of different object types (about 15 different types) , they are coming from 3rd party system.
For every type I need to make different transformation.
My original thought is to make some interface with transform function and for every type make a class and run it's own implementation.
But like this I will need to make a really big if statement that checks the object type and make the mapping.
I am trying to learn something new here, so my question is there other ways to deal with this situation?
Have you considered the possibility of using a Visitor?
If you combine the visitor pattern with the use of dynamic, you could get a pretty simple implementation without any if or switch statements, or having to manually create a Type Dictionary with delegates, or similar alternatives.
Using dynamic you can avoid implementing the "accept" part of the design pattern, which I assume is useful to you since these are external types you have no control over.
Meaning, you create something like this:
public interface IVisitor
{
void Visit(OneType element);
void Visit(AnotherType element);
....
}
You implement that visitor, and can later call the implementation using:
visitor.Visit((dynamic)objectToTransform);
You would probably have to handle for exceptions regarding not having an appropriate overload for the Type.
That would solve the part of the problem related to executing a separate method for each type.
Now, depending on what you specifically need to do with each one, if you need automatic property mapping then AutoMapper could be very useful.
You can create a lookup of type and transformation, similar to Java Front Controller pattern.
I'm not sure if this is what you want, but have a look at AutoMapper (or aother mappers). It allows you to easily define rules to map types to other types.
The code looks like below:
namespace Test
{
public interface IMyClass
{
List<IMyClass> GetList();
}
public class MyClass : IMyClass
{
public List<IMyClass> GetList()
{
return new List<IMyClass>();
}
}
}
When I Run Code Analysis i get the following recommendation.
Warning 3 CA1002 : Microsoft.Design : Change 'List' in 'IMyClass.GetList()' to use Collection, ReadOnlyCollection or KeyedCollection
How should I fix this and what is good practice here?
To answer the "why" part of the question as to why not List<T>, The reasons are future-proofing and API simplicity.
Future-proofing
List<T> is not designed to be easily extensible by subclassing it; it is designed to be fast for internal implementations. You'll notice the methods on it are not virtual and so cannot be overridden, and there are no hooks into its Add/Insert/Remove operations.
This means that if you need to alter the behavior of the collection in the future (e.g. to reject null objects that people try to add, or to perform additional work when this happens such as updating your class state) then you need to change the type of collection you return to one you can subclass, which will be a breaking interface change (of course changing the semantics of things like not allowing null may also be an interface change, but things like updating your internal class state would not be).
So by returning either a class that can be easily subclassed such as Collection<T> or an interface such as IList<T>, ICollection<T> or IEnumerable<T> you can change your internal implementation to be a different collection type to meet your needs, without breaking the code of consumers because it can still be returned as the type they are expecting.
API Simplicity
List<T> contains a lot of useful operations such as BinarySearch, Sort and so on. However if this is a collection you are exposing then it is likely that you control the semantics of the list, and not the consumers. So while your class internally may need these operations it is very unlikely that consumers of your class would want to (or even should) call them.
As such, by offering a simpler collection class or interface, you reduce the number of members that users of your API see, and make it easier for them to use.
I would personally declare it to return an interface rather than a concrete collection. If you really want list access, use IList<T>. Otherwise, consider ICollection<T> and IEnumerable<T>.
I don't think anyone has answered the "why" part yet... so here goes. The reason "why" you "should" use a Collection<T> instead of a List<T> is because if you expose a List<T>, then anyone who gets access to your object can modify the items in the list. Whereas Collection<T> is supposed to indicate that you are making your own "Add", "Remove", etc methods.
You likely don't need to worry about it, because you're probably coding the interface for yourself only (or maybe a few collegues). Here's another example that might make sense.
If you have a public array, ex:
public int[] MyIntegers { get; }
You would think that because there is only a "get" accessor that no-one can mess with the values, but that's not true. Anyone can change the values inside there just like this:
someObject.MyIngegers[3] = 12345;
Personally, I would just use List<T> in most cases. But if you are designing a class library that you are going to give out to random developers, and you need to rely on the state of the objects... then you'll want to make your own Collection and lock it down from there :)
It's mostly about abstracting your own implementations away instead of exposing the List object to be manipulated directly.
It's not good practice to let other objects (or people) modify the state of your objects directly. Think property getters/setters.
Collection -> For normal collection
ReadOnlyCollection -> For collections that shouldn't be modified
KeyedCollection -> When you want dictionaries instead.
How to fix it depends on what you want your class to do and the purpose of the GetList() method. Can you elaborate?
In these kind of case I usually try to expose the least amount of implemententation that is needed. If the consumers do not need to know that you are actually using a list then you don't need to return a list. By returning as Microsoft suggests a Collection you hide the fact that you are using a list from the consumers of your class and isolate them against an internal change.
Something to add though it's been a long time since this was asked.
When your list type derives from List<T> instead of Collection<T>, you cannot implement the protected virtual methods that Collection<T> implements.
What this means is that you derived type cannot respond in case any modifications are made to the list. This is because List<T> assumes you are aware when you add or remove items. Being able to response to notifications is an overhead and hence List<T> doesn't offer it.
In cases when external code has access to your collection, you may not be in control of when an item is being added or removed. Therefore Collection<T> provides a way to know when your list was modified.
I don't see any problem with returning something like
this.InternalData.Filter(crteria).ToList();
If I returned a disconnected copy of internal data, or detached result of a data query - I can safely return List<TItem> without exposing any of implementation details, and allow to use the returned data in the convenient way.
But this depends on what type of consumer I expect - if this is a something like data grid I prefer to return IEnumerable<TItem> which will be the copied list of items anyway in most cases :)
Well the Collection class is really just a wrapper class around other collections to hide their implementation details and other features. I reckon this has something to do with the property hiding coding pattern in object-oriented languages.
I think you shouldn't worry about it, but if you really want to please the code analysis tool, just do the following:
//using System.Collections.ObjectModel;
Collection<MyClass> myCollection = new Collection<MyClass>(myList);
So I understand what a static method or field is, I am just wondering when to use them. That is, when writing code what design lends itself to using static methods and fields.
One common pattern is to use static methods as a static factory, but this could just as easily be done by overloading a constructor. Correct? For example:
var bmp = System.Drawing.Bitmap.LoadFromFile("Image01.jpg");
As for static fields, is creating singelton-objects their best use?
Static methods are usually useful for operations that don't require any data from an instance of the class (from this) and can perform their intended purpose solely using their arguments.
A simple example of this would be a method Point::distance(Point a, Point b); that calculates the distance between two points and don't require an instance.
Static fields are useful among others for constants that don't change all that often and are used by all the instances of a class.
It gives a better idea of the intent when you use a static factory -- it also lets you have different factories that take the same argument types but have a different meaning. For example, imagine if Bitmap had LoadFromResource(string) -- it would not be possible to have two constructors that both took string.
EDIT: From stevemegson in the comments
A static factory can also return null, and can more easily return an instance that it got from cache. Many of my classes have a static FromId(int) to get an instance from a primary key, returning an existing cached instance if we have one.
I would say use static methods whenever you have functions which are independent of the state of the instance, ie. doesn't depend on any instance fields.
The less non-local state that a method depends on, the easier it is to understand, so static is a helpful signal to the reader of the code.
I keep it clear by remembering that instance methods work on/inside individual objects while static methods do something for the Class.
In the case of LoadFromFile(), you want a static method because you want a null reference if the load fails - the instance doesn't exist yet. If you implemented it as a constructor, you'd have to throw an Exception on failure.
Other good uses for statics: Compare(obj a, obj b), Delete(obj a) for data objects (an object can't delete itself since its reference is still around), or static Classes for procedural code that honestly can't be modeled in an object.
Use a static method when the method does not belong to a specific object.
For example, if you look at the Math class in .NET framework, you will see
that all methods are static. Why? Because there is no reason to must create
an object to use the methods. Why would you want to create an object of the
Math class, when all you want is the absolute value of something? No, there
is no reason to do this, and therefore, the method is static.
So when you design a class, ask yourself:
Does this method belong to an object, or the class itself?
A method belongs to an object, if it modifies the state of the object. If
the method does not modify a specific object, it can most likely be static.
Another example, suppose that you want to know how many objects of a class
that is created (don't ask me why...). For this task, you could create a
static method GetNumberOfObjects() (and you obviously need a static field,
and some code in the constructor too). Why would i have it static, you might
ask. Well, answer the above question, and you will see. The method does not
belong to any specific object. Additionally, it does not modify any object.
I hope this makes sense.
You should use static methods whenever you have a function that does not depend on a particular object of that class.
There is no harm in adding the static keyword: it will not break any of the code that referred to it. So for example, the following code is valid whether or not you have the 'static' keyword:
class Foo
{
public Foo(){}
public static void bar(){} // valid with or without 'static'
public void nonStatic(){ bar(); }
}
...
Foo a = new Foo();
a.bar();
So you should add 'static' to whatever methods you can.
Here are some examples of when you might want to use static methods:
1) When the function doesn't make use of any member variables. You don't have to use a static method here, but it usually helps if you do.
2) When using factory methods to create objects. They are particularly necessary if you don't know the type to be created in advance: e.g.
class AbstractClass {
static createObject(int i) {
if (i==1) {
return new ConcreteClass1();
} else if (i==2) {
return new ConcreteClass2();
}
}
}
3) When you are controlling, or otherwise keeping track of, the number of instantiations of the class. The Singleton is the most used example of this.
4) When declaring constants.
5) Operations such as sorts or comparisons that operate on multiple objects of a class and are not tied to any particular instance.
6) When special handling has to be done before the first instantiation of an object.
You may use static methods when the client of the class do not have an instance of the class to work with. For instance the Singleton design pattern is used to ensure that only one instance of a class exist in the system. It requires that the constructors of the Singleton be private so that no instances can be created by the client.
So if you cannot create an instance how do you access the instance methods of the class? By calling a static method that returns the Singleton instance of the class.
This is of course just one scenario but there are many others.