For a REST api, that has no dependencies between requests and is using ASP.NET Core DI.  I have heard conflicting arguments when choosing the most appropriate:   Prefer transient and then scoped and avoid singleton due to memory and multi-threading issues and also because singletons should not be injected with other lifetimes due to captive dependencies Prefer singletons to save time instantiating objects and prevent opening multiple connections   I understand they work differently but is there a 'go-to' lifetime? Should it start with 'transient' and move to others as required?  Are there any investigations proving the instantiation time saved by singleton is actually relevant?
35333
The  is a fully paid up member of the 's , but it lately seems rather orphaned by the developer world. I still use quite a lot of singletons, especially for , and while you have to be a bit careful about multithreading issues (like any class actually), I fail to see why they are so awful.  Stack Overflow especially seems to assume that everyone agrees that Singletons are evil. Why?  Please support your answers with "facts, references, or specific expertise"
105546
When modelling classes, what is the preferred way of initializing:   Constructors, or Factory Methods   And what would be the considerations for using either of them?  In certain situations, I prefer having a factory method which returns null if the object cannot be constructed. This makes the code neat. I can simply check if the returned value is not null before taking alternative action, in contrast with throwing an exception from the constructor. (I personally don't like exceptions)  Say, I have a constructor on a class which expects an id value. The constructor uses this value to populate the class from the database. In the case where a record with the specified id does not exist, the constructor throws a RecordNotFoundException. In this case I will have to enclose the construction of all such classes within a try..catch block.  In contrast to this I can have a static factory method on those classes which will return null if the record is not found.  Which approach is better in this case, constructor or factory method?
49579
I have the following C# singleton pattern, is there any way of improving it?       public class Singleton&lt;T&gt; where T : class, new()     {          private static object _syncobj = new object();         private static volatile T _instance = null;         public static T Instance         {             get             {                 if (_instance == null)                 {                     lock (_syncobj)                     {                         if (_instance == null)                         {                             _instance = new T();                         }                     }                 }                 return _instance;             }         }          public Singleton()         { }      }   Preferred usage example:   class Foo : Singleton&lt;Foo&gt;  { }    Related:
30114
I have a business logic as follows.   1. A web service class parses XML file containing case data and loads the case to SF. 2. Trigger that on update of case email field make a call to future method to generate attachment ,send email and update case owner field.  trigger CaseUpdate on Case (After update)  {  for(case c : trigger.old)  {     for(case ca : trigger.new)     {         if((c.Email__c != ca.Email__c) &amp;&amp; (c.CS_ID__c != null) &amp;&amp; (c.Count__c == 1))         {           UtilsClass.generateReport_Future(c.id);         }     }  } }    @Future(callout=true)  public static void generateReport_future(String caseId)  { String result = ''; result = generateReport(caseId); if(result == '')  {     result = emailReport(caseId); } UtilsClass.ChangeOwner(caseId);  }   The issue i am facing is,  System.LimitException: Too many future calls: 11, even though single case record is loaded.  Multiple records may be loaded at the same time, but they are sequential(One By One).  Are the records coming in a single batch even though they are being loaded individually..?
21564
In Java, what are the performance and resource implications of using  System.currentTimeMillis()    vs.   new Date()    vs.   Calendar.getInstance().getTime()   As I understand it, System.currentTimeMillis() is the most efficient. However, in most applications, that long value would need to be converted to a Date or some similar object to do anything meaningful to humans.
9571
I realize that it seems to be a duplicate of  but my question has a slight difference (from my point of view):  Once I know that   I will not use my class with "techniques that only works on properties" and  I will not use validation code in the getter/setter.   Is there any difference (except the style/future development ones), like some type of control in setting the property?  Is there any additional difference between:  public string MyString { get; set; }   and   public string myString;   (I am aware that, that the first version requires C# 3.0 or above and that the compiler does create the private fields.)
3879
So I was playing around a little more with attributes in .NET, and realized that every call to Type.GetCustomAttributes() creates a new instance of my attribute. Why is that? I would think that the attribute instance would basically be a singleton-per-MemberInfo, with 1 instance bound to the Type, PropertyInfo, etc...  Here is my test code:  using System;  namespace AttribTest { [AttributeUsage(AttributeTargets.Class)] class MyAttribAttribute : Attribute {     public string Value { get; set; }      public MyAttribAttribute()         : base()     {         Console.WriteLine("Created MyAttrib instance");     } }  [MyAttrib(Value = "SetOnClass")] class MyClass { }  class Program {     static void Main(string[] args)     {         Console.WriteLine("Getting attributes for MyClass.");         object[] a = typeof(MyClass).GetCustomAttributes(false);         ((MyAttribAttribute)a[0]).Value = "a1";          Console.WriteLine("Getting attributes for MyClass.");         a = typeof(MyClass).GetCustomAttributes(false);         Console.WriteLine(((MyAttribAttribute)a[0]).Value);          Console.ReadKey();     } } }   Now if I were to implement attributes, I would expect the output to be:  Created MyAttrib instance Getting attributes for MyClass. Getting attributes for MyClass. a1   Where the "class loader" (sorry, I have more of a Java background, not 100% sure how .net loads its types) would compile MyClass, and create an instance of MyAttribAttribute, and store them together somewhere. (probably the Perm Gen in the heap if this were Java) The 2 calls to GetCustomAttributes() would then just return the same earlier created instance.  But the actual output is:  Getting attributes for MyClass. Created MyAttrib instance Getting attributes for MyClass. Created MyAttrib instance SetOnClass   So... why? It seems like creating a new instance of all these objects for every call is a bit excessive, and not good for performance/memory management.  Is there any way to always get the same instance over and over?  Anyone have any ideas why it was designed this way?  The reason I care at all is because I made a custom attribute that internally holds some validation information, so in the Attribute I basically have a "private bool Validated" that I set to true. The validation stuff takes a while, so I don't want to run it every time. Now the problem is that since it creates a new instance of the attribute each time I get the attributes, Validated is always "false".
28304
If I have a unit that is filled with constants like...  unit AConsts; interface const    Const1 : WideString = 'Const1';    Const2 : WideString = 'Const2';    Const3 : WideString = 'Const3';    Const4 = 100;    Const5 = 100; implementation end.   and I want to use this unit from another unit, is there any difference between...  unit AUnit; interface uses    AConsts; Implementation end.   and   unit AUnit; interface implementation uses   AConsts; end.   ?  The question is not about scope, avoiding circular references etc. It is about differences in the compiled application.  If UnitA, UnitB and UnitC all use AConsts, would there be a difference in the compiled application (assuming no name clashes between the constants in the AConsts unit and other code) between App1 where these UnitA, UnitB and UnitC all have AConsts in the interface section and App2 where UnitA, UnitB and UnitC all have AConsts in the implementation section.
11
I've always been one to simply use:  List&lt;String&gt; names = new ArrayList&lt;&gt;();   I use the interface as the type name for portability, so that when I ask questions such as these I can rework my code.    When should  be used over  and vice-versa?
42437
I've been trying to optimize my code to make it a little more concise and readable and was hoping I wasn't causing poorer performance from doing it.  I think my changes might have slowed down my application, but it might just be in my head.  Is there any performance difference between:  Command.Parameters["@EMAIL"].Value = email ?? String.Empty;   and  Command.Parameters["@EMAIL"].Value = (email == null) ? String.Empty: email;   and  if (email == null) {     Command.Parameters["@EMAIL"].Value = String.Empty } else {     Command.Parameters["@EMAIL"].Value = email }   My preference for readability would be the null coalescing operator, I just didn't want it to affect performance.
114660
Is it better to have all the private members, then all the protected ones, then all the public ones?  Or the reverse?  Or should there be multiple private, protected and public labels so that the operations can be kept separate from the constructors and so on?  What issues should I take into account when making this decision?
94364
I'm trying to understand what single and multiple dispatch are, exactly.  I just read this:   And from that definition is seems to me that C# and VB.Net are multiple-dispatch, even though the choice of which overload to call is made at compile-time.  Am I correct here, or am I missing something? Thanks!
14396
For years, I've been using named blocks to limit the scope of temporary variables.  I've never seen this done anywhere else, which makes me wonder if this is a bad idea.  Especially since the Eclipse IDE flags these as warnings by default.  I've used this to good effect, I think, in my own code.  But since it is un-idiomatic to the point where good programmers will distrust it when they see it, I really have two ways to go from here:     avoid doing it, or  promote it, with the hope that it will become an idiom.   Example (within a larger method):  final Date nextTuesday; initNextTuesday: {     GregorianCalendar cal = new GregorianCalendar();     ... // About 5-10 lines of setting the calendar fields     nextTuesday = cal.getTime(); }   Here I'm using a GregorianCalendar just to initialize a date, and I want to make sure that I don't accidentally reuse it.  Some people have commented that you don't actually need to name the block.  While that's true, a raw block looks even more like a bug, as the intent is unclear.  Furthermore, naming something encourages you to think about the intention of the block.  The goal here is to identify distinct sections of code, not to give every temporary variable its own scope.  Many people have commented that it's best to go straight to small methods.  I agree that this should be your first instinct.  However, there may be several mitigating factors:   To even consider a named block, the code should be short, one-off code that will never be called elsewhere. A named block is a quick way to organize an oversized method without creating a one-off method with a dozen parameters.  This is especially true when a class is in flux, and the inputs are likely to change from version to version. Creating a new method encourages its reuse, which may be ill-advised if the use cases aren't well-established.  A named block is easier (psychologically, at least) to throw away. Especially for unit tests, you may need to define a dozen different objects for one-off assertions, and they are just different enough that you can't (yet) find a way to consolidate them into a small number of methods, nor can you think of a way to distinguish them with names that aren't a mile long.   Advantages of using the named scope:   Can't accidentally reuse temporary variables Limited scope gives garbage collector and JIT compiler more information about programmer intent Block name provides a comment on a block of code, which I find more readable than open-ended comments Makes it easier to refactor code out of a big method into little methods, or vice versa, since the named block is easier to separate than unstructured code.   Disadvantages:  Not idiomatic: programmers who haven't seen this use of named blocks (i.e. everyone but me) assume it's buggy, since they can't find references to the block name.  (Just like Eclipse does.)  And getting something to become idiomatic is an uphill battle.  It can be used as an excuse for bad programming habits, such as:   Making huge, monolithic methods where several small methods would be more legible. Layers of indentation too deep to read easily.   Note:  I've edited this question extensively, based on some thoughtful responses.  Thanks!
4146
I need to get execution time in milliseconds.  I originally asked this question back in 2008. The accepted answer then was to use  However, we can all agree now  that using the standard  API is more appropriate. I am therefore changing the accepted answer to this one.
112547
I have a class proposing translations utilities. The translations themselves should be reloaded every 30 minutes. I use Spring Timer support for that. Basically, my class looks like :  public interface Translator {     public void loadTranslations();     public String getTranslation(String key); }   loadTranslations() can be pretty long to run, so while it is running the old translations are still available. This is done by loading the translations in a local Map and just changing the reference when all translations are loaded.  My problem is : how do I make sure that when a thread is already loading translations, is a second one also tries to run, it detects that and returns immediately, without starting a second update.  A synchronized method will only queue the loads ... I'm still on Java 1.4, so no java.util.concurrent.  Thanks for your help !
26352
Whenever a question pops up on SO about Java synchronization, some people are very eager to point out that synchronized(this) should be avoided. Instead, they claim, a lock on a private reference is to be preferred.  Some of the given reasons are:    (very popular this one, also has an "accidentally" variant)     Other people, including me, argue that synchronized(this) is an idiom that is used a lot (also in Java libraries), is safe and well understood. It should not be avoided because you have a bug and you don't have a clue of what is going on in your multithreaded program. In other words: if it is applicable, then use it.  I am interested in seeing some real-world examples (no foobar stuff) where avoiding a lock on this is preferable when synchronized(this) would also do the job.  Therefore: should you always avoid synchronized(this) and replace it with a lock on a private reference?      Some further info (updated as answers are given):   we are talking about instance synchronization both implicit (synchronized methods) and explicit form of synchronized(this) are considered if you quote Bloch or other authorities on the subject, don't leave out the parts you don't like (e.g. Effective Java, item on Thread Safety: Typically it is the lock on the instance itself, but there are exceptions.) if you need granularity in your locking other than synchronized(this) provides, then synchronized(this) is not applicable so that's not the issue
11253
When you have code like the following:   static T GenericConstruct&lt;T&gt;() where T : new() {     return new T(); }   The C# compiler insists on emitting a call to Activator.CreateInstance, which is considerably slower than a native constructor.   I have the following workaround:  public static class ParameterlessConstructor&lt;T&gt;     where T : new() {     public static T Create()     {         return _func();     }      private static Func&lt;T&gt; CreateFunc()     {         return Expression.Lambda&lt;Func&lt;T&gt;&gt;( Expression.New( typeof( T ) ) ).Compile();     }      private static Func&lt;T&gt; _func = CreateFunc(); }  // Example: // Foo foo = ParameterlessConstructor&lt;Foo&gt;.Create();   But it doesn't make sense to me why this workaround should be necessary.