Advertisement
Guest User

Untitled

a guest
Jul 8th, 2015
471
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 106.00 KB | None | 0 0
  1. Answer Content CreatedOn Answer Author Question Title Category Name
  2. According to the language specification, the language itself must consider string to be exactly the same as the BCL type System.String, nothing else. That is not ambiguous at all. Of course, you can implement your own compiler, using the C# grammar, and use all of the tokens found like that for something arbitrary, unrelated to what is defined in the C# language specification. However, the resulting language would only be a C# lookalike, it could not be considered C# 2012-01-23 07:37:21.000 AGreenman What's the difference between String and string? C#
  3. System.String is THE .net string class - in C# string is an alias for System.String - so in use they are the same.
  4.  
  5. As for guidelines I wouldn't get too bogged down and just use whichever you feel like - there are more important things in life and the code is going to be the same anyway.
  6.  
  7. If you find yourselves building systems where it is necessary to specify the size of the integers you are using and so tend to use Int16, Int32, UInt16, UInt32 etc. then it might look more natural to use String - and when moving around between different .net languages it might make things more understandable - otherwise I would use string and int. 2013-09-08 20:35:09.000 StefanG What's the difference between String and string? C#
  8. Lower case string is an alias for System.String. They are the same in C#.
  9.  
  10. There's a debate over whether you should use the System types (System.Int32, System.String, etc.) types or the C# aliases (int, string, etc). I personally believe you should use the C# aliases, but that's just my personal preference. 2014-07-29 07:53:31.000 HonzaBrabec What's the difference between String and string? C#
  11. I've seen a number of developers confused, not knowing whether to use string or String in their code. Because in C# the string (a keyword) maps exactly to System.String (an FCL type), there is no difference and either can be used.
  12. In C#, long maps to System.Int64, but in a different programming language, long could map to an Int16 or Int32. In fact, C++/CLI does in fact treat long as an Int32. Someone reading source code in one language could easily misinterpret the code's intention if he or she were used to programming in a different programming language. In fact, most languages won't even treat long as a keyword and won't compile code that uses it.
  13. The FCL has many methods that have type names as part of their method names. For example, the BinaryReader type offers methods such as ReadBoolean, ReadInt32, ReadSingle, and so on, and the System.Convert type offers methods such as ToBoolean, ToInt32, ToSingle, and so on. Although it's legal to write the following code, the line with float feels very unnatural to me, and it's not obvious that the line is correct: 2013-08-06 23:59:52.000 JonSkeet What's the difference between String and string? C#
  14. It's a matter of convention, really. "string" just looks more like C/C++ style. The general convention is to use whatever shortcuts your chosen language has provided (int/Int for Int32). This goes for "object" and "decimal" as well.
  15.  
  16. Theoretically this could help to port code into some future 64-bit standard in which "int" might mean Int64, but that's not the point, and I would expect any upgrade wizard to change any "int" references to "Int32" anyway just to be safe. 2014-01-14 07:03:44.000 Joiner What's the difference between String and string? C#
  17. Both are same. But from coding guidelines perspective it's better to use string instead of String. This is what generally developers use. e.g. instead of using Int32 we use int as int is alias to Int32 FYI “The keyword string is simply an alias for the predefined class System.String.” - C# Language Specification 4.2.3 http://msdn2.microsoft.com/En-US/library/aa691153.aspx 2011-02-22 09:38:10.000 micori What's the difference between String and string? C#
  18. Finally, when it comes to which to use: personally I use the aliases everywhere for the implementation, but the CLR type for any APIs. It really doesn't matter too much which you use in terms of implementation - consistency among your team is nice, but no-one else is going to care. On the other hand, it's genuinely important that if you refer to a type in an API, you do so in a language neutral way. A method called ReadInt32 is unambiguous, whereas a method called ReadInt requires interpretation. The caller could be using a language which defines an int alias for Int16, for example. The .NET framework designers have followed this pattern, good examples being in the BitConverter, BinaryReader and Convert classes. 2011-09-16 01:02:52.000 Lingfeng What's the difference between String and string? C#
  19. Another even-later-to-the-party thought: If you use the BCL type name (String), the compiler has to resolve it in the context of your using statements, to see whether you indeed meant System.String or perhaps AdvancedPhysics.String or RememberToBuyButter.TieAroundFinger.String. Lower-case string, on the other hand, is a keyword, and can only ever refer to System.String. Presumably this affects the compilation time, though I doubt the difference is observable. 2011-04-05 10:27:44.000 StefSan What's the difference between String and string? C#
  20. According to ECMA-334, section 9.4.3, "string" is a keyword. :-) I agree with you that "string" is a type if you focus on the semantics, but I'd say it's a keyword (i.e. a reserved word) if you focus on the syntax. The standard backs both points of view (perhaps too ambiguously!). To me, the OP is about syntax, so I tend to focus on syntax when I look at answers, but I see your point too. Furthermore, your answer, as it stands, may be interpreted as to mean that two different types exist: string and String, when that is not the case. One is a maping to the other. 2012-04-13 20:20:39.000 Chad What's the difference between String and string? C#
  21. The C# language specification states, “As a matter of style, use of the keyword is favored over use of the complete system type name.” I disagree with the language specification; I prefer to use the FCL type names and completely avoid the primitive type names. In fact, I wish that compilers didn’t even offer the primitive type names and forced developers to use the FCL type names instead. Here are my reasons: 2013-05-08 16:05:26.000 Ankit What's the difference between String and string? C#
  22. Coming late to the party: I use the CLR types 100% of the time (well, except if forced to use the C# type, but I don't remember when the last time that was).
  23.  
  24. I originally started doing this years ago, as per the CLR books by Ritchie. It made sense to me that all CLR languages ultimately have to be able to support the set of CLR types, so using the CLR types yourself provided clearer, and possibly more "reusable" code.
  25.  
  26. Now that I've been doing it for years, it's a habit and I like the coloration that VS shows for the CLR types.
  27.  
  28. The only real downer is that auto-complete uses the C# type, so I end up re-typing automatically generated types to specify the CLR type instead.
  29.  
  30. Also, now, when I see "int" or "string", it just looks really wrong to me, like I'm looking at 1970's C code. 2011-07-12 21:12:59.000 micori What's the difference between String and string? C#
  31. @Anthony: Yes. The compiler team refers to this as hoisting rather than lifting, since "lifting" already has a meaning for nullable arithmetic. But stop thinking about the stack altogether. The stack is an implementation detail subject to change. The compiler uses the stack -- or registers -- when doing so is convenient and correct. In this case it is neither, so the stack isn't used. 2013-03-08 14:32:22.000 Onorio Is there a reason for C#'s reuse of the variable in a foreach? C#
  32. Is there something you can do with foreach loops this way that you couldn't if they were compiled with an inner-scoped variable? or is this just an arbitrary choice that was made before anonymous methods and lambda expressions were available or common, and which hasn't been revised since then? 2012-08-17 09:18:09.000 ben Is there a reason for C#'s reuse of the variable in a foreach? C#
  33. The latter. The C# 1.0 specification actually did not say whether the loop variable was inside or outside the loop body, as it made no observable difference. When closure semantics were introduced in C# 2.0, the choice was made to put the loop variable outside the loop, consistent with the "for" loop.
  34.  
  35. I think it is fair to say that all regret that decision. This is one of the worst "gotchas" in C#, and we are going to take the breaking change to fix it. In C# 5 the foreach loop variable will be logically inside the body of the loop, and therefore closures will get a fresh copy every time.
  36.  
  37. The for loop will not be changed, and the change will not be "back ported" to previous versions of C#. You should therefore continue to be careful when using this idiom. 2012-05-21 17:04:00.000 MaryDefal Is there a reason for C#'s reuse of the variable in a foreach? C#
  38. We did in fact push back on this change in C# 3 and C# 4. When we designed C# 3 we did realize that the problem (which already existed in C# 2) was going to get worse because there would be so many lambdas (and query comprehensions, which are lambdas in disguise) in foreach loops thanks to LINQ. I regret that we waited for the problem to get sufficiently bad to warrant fixing it so late, rather than fixing it in C# 3. 2011-01-17 02:09:59.000 DanielB Is there a reason for C#'s reuse of the variable in a foreach? C#
  39. @Benjol: No, which is why we're willing to take it. Jon Skeet pointed out to me an important breaking change scenario though, which is that someone writes code in C# 5, tests it, and then shares it with people who are still using C# 4, who then naively believe it to be correct. Hopefully the number of people affected by such a scenario is small. 2014-12-03 06:34:52.000 StefanG Is there a reason for C#'s reuse of the variable in a foreach? C#
  40. this is a case where the forced consistency is more harmful than being inconsistent. It should "just work" as people expect, and clearly people expect something different when using foreach as opposed to a for loop, given the number of people that have hit problems before we knew about the access to modified closure issue (such as myself). 2012-03-24 18:24:03.000 Chad Is there a reason for C#'s reuse of the variable in a foreach? C#
  41. If v was declared outside of the while loop, it would be shared among all iterations, and its value after the for loop would be the final value, 13, which is what the invocation of f would print. Instead, because each iteration has its own variable v, the one captured by f in the first iteration will continue to hold the value 7, which is what will be printed. (Note: earlier versions of C# declared v outside of the while loop.) 2014-09-11 07:51:29.000 keveh Is there a reason for C#'s reuse of the variable in a foreach? C#
  42. Be sure to read Eric's answer: The C# 1.0 specification (in your link we are talking about VS 2003, i.e. C# 1.2) actually did not say whether the loop variable was inside or outside the loop body, as it make no observable difference. When closure semantics were introduced in C# 2.0, the choice was made to put the loop variable outside the loop, consistent with the "for" loop. 2013-08-16 15:57:24.000 casper Is there a reason for C#'s reuse of the variable in a foreach? C#
  43. They were definitive specifications. The problem is that we are talking about a feature (i.e. function closures) that was introduced later (with C# 2.0). When C# 2.0 came up they decided to put the loop variable outside the loop. And than they changed their mind again with C# 5.0 :) 2013-12-18 01:03:44.000 Lorraine Is there a reason for C#'s reuse of the variable in a foreach? C#
  44. That is the typical workaround Thanks for the contribution. Resharper is smart enough to recognize this pattern and bring it to your attention too, which is nice. I haven't been bit by this pattern in a while, but since it is, in Eric Lippert's words, "the single most common incorrect bug report we get," I was curious to know the why more than the how to avoid it. 2012-07-02 10:46:29.000 Qwerty Is there a reason for C#'s reuse of the variable in a foreach? C#
  45. this does not work very well in a medium to large development team where some level of code consistency is required. And as noted previously, if you don't understand the different layouts you may find edge cases that don't work as you expect. 2012-09-21 02:16:58.000 Onorio Should 'using' statements be inside or outside the namespace? C#
  46. It's also interesting to note what happens if Foo is in namespace Outer, rather than Outer.Inner. In that case, adding Outer.Math in File2 breaks File1 regardless of where the using goes. This implies that the compiler searches the innermost enclosing namespace before it looks at any using statements. 2012-03-05 18:29:03.000 ben Should 'using' statements be inside or outside the namespace? C#
  47. Now the compiler searches System before searching Outer, finds System.Math, and all is well.
  48.  
  49. Some would argue that Math might be a bad name for a user-defined class, since there's already one in System; the point here is just that there is a difference, and it affects the maintainability of your code. 2013-04-09 18:52:48.000 quirk Should 'using' statements be inside or outside the namespace? C#
  50. Great answer, but it seems to me that I'd only want to put non-framework using statements locally, and keep the framework using statements global. Anyone have further explanation why I should completely changed my preference? Also where did this come from, the templates in VS2008 put using outside the namespace? 2012-01-27 11:03:54.000 darkcat Should 'using' statements be inside or outside the namespace? C#
  51. This is imho a much better reason to put using statements locally than Mark's multiple-namespaces-in-one-file argument. Especially sine the compile can and will complain about the naming clash (see the StyleCop documentation for this rule (e.g. as posted by Jared)). 2011-11-01 06:31:31.000 Pravinsingh Should 'using' statements be inside or outside the namespace? C#
  52. Putting it inside the namespaces makes the declarations local to that namespace for the file (in case you have multiple namespaces in the file) but if you only have one namespace per file then it doesn't make a difference whether they go outside or inside the namespace. 2014-11-13 17:46:30.000 Rafael Should 'using' statements be inside or outside the namespace? C#
  53. Aye I didn't fully read the thread but bought in when the MVPs said it was right. A guy disproves it, explains it and shows his code further down... "The IL that the C# compiler generates is the same in either case. In fact the C# compiler generates precisely nothing corresponding to each using directive. Using directives are purely a C#ism, and they have no meaning to .NET itself. (Not true for using statements but those are something quite different.) 2013-03-08 05:26:41.000 HHendriks Should 'using' statements be inside or outside the namespace? C#
  54. The code creates an alias to the System.Guid type called Guid, and also creates its own type called Guid with a matching constructor interface. Later, the code creates an instance of the type Guid. To create this instance, the compiler must choose between the two different definitions of Guid. When the using-alias directive is placed outside of the namespace element, the compiler will choose the local definition of Guid defined within the local namespace, and completely ignore the using-alias directive defined outside of the namespace. This, unfortunately, is not obvious when reading the code. 2013-01-23 05:35:18.000 Sydney Should 'using' statements be inside or outside the namespace? C#
  55. When the using-alias directive is positioned within the namespace, however, the compiler has to choose between two different, conflicting Guid types both defined within the same namespace. Both of these types provide a matching constructor. The compiler is unable to make a decision, so it flags the compiler error. 2011-02-24 11:29:06.000 Rafael Should 'using' statements be inside or outside the namespace? C#
  56. Placing the using-alias directive outside of the namespace is a bad practice because it can lead to confusion in situations such as this, where it is not obvious which version of the type is actually being used. This can potentially lead to a bug which might be difficult to diagnose. 2012-08-11 16:43:03.000 Camacho Should 'using' statements be inside or outside the namespace? C#
  57. Placing multiple namespace elements within a single file is generally a bad idea, but if and when this is done, it is a good idea to place all using directives within each of the namespace elements, rather than globally at the top of the file. This will scope the namespaces tightly, and will also help to avoid the kind of behavior described above. 2011-05-20 14:27:18.000 Kaviraj Should 'using' statements be inside or outside the namespace? C#
  58. It is important to note that when code has been written with using directives placed outside of the namespace, care should be taken when moving these directives within the namespace, to ensure that this is not changing the semantics of the code. As explained above, placing using-alias directives within the namespace element allows the compiler to choose between conflicting types in ways that will not happen when the directives are placed outside of the namespace. 2011-05-06 17:09:50.000 Darshan Should 'using' statements be inside or outside the namespace? C#
  59. The rule for resolving which type is implied, can be loosely stated like this: First search the inner-most "scope" for a match, if nothing is found there go out one level to the next scope and search there, and so on, until a match is found. If at some level more than one match is found, if one of the types are from the current assembly, pick that one and issue a compiler warning. Otherwise, give up (compile-time error). 2012-07-18 13:51:15.000 HHendriks Should 'using' statements be inside or outside the namespace? C#
  60. In the above case, to find out what type Ambiguous is, the search goes in this order:
  61.  
  62. Nested types inside C (including inherited nested types)
  63. Types in the current namespace MyCorp.TheProduct.SomeModule.Utilities
  64. Types in namespace MyCorp.TheProduct.SomeModule
  65. Types in MyCorp.TheProduct
  66. Types in MyCorp
  67. Types in the null namespace (the global namespace)
  68. Types in System, System.Collections.Generic, System.Linq, MyCorp.TheProduct.OtherModule, MyCorp.TheProduct.OtherModule.Integration, and ThirdParty 2012-06-12 13:59:16.000 Pravinsingh Should 'using' statements be inside or outside the namespace? C#
  69. No matter if you put the usings inside or outside the namespace declaration, there's always the possibility that someone later adds a new type with identical name to one of the namespaces which have higher priority. 2011-07-12 12:10:24.000 HHendriks Should 'using' statements be inside or outside the namespace? C#
  70. Also, if a nested namespace has the same name as a type, it can cause problems.
  71.  
  72. It is always dangerous to move the usings from one location to another because the search hierarchy changes, and another type may be found. Therefore, choose one convention and stick to it, so that you won't have to ever move usings. 2014-05-21 08:49:53.000 keveh Should 'using' statements be inside or outside the namespace? C#
  73. Visual Studio's templates, by default, put the usings outside of the namespace (for example if you make VS generate a new class in a new file).
  74.  
  75. One (tiny) advantage of having usings outside is that you can then utilize the using directives for a global attribute, for example [assembly: ComVisible(false)] instead of [assembly: System.Runtime.InteropServices.ComVisible(false)]. 2011-07-04 07:30:07.000 Lorraine Should 'using' statements be inside or outside the namespace? C#
  76. It is a better practice if those default using i.e. "references" used in your source solution should be outside the namespaces and those that are "new added reference" is a good practice is you should put it inside the namespace. This is to distinguish what references are being added. 2014-11-29 03:36:15.000 Lingfeng Should 'using' statements be inside or outside the namespace? C#
  77. No, actually that is a bad idea. You should not base the location between locally scoped and globally scoped of using directives on the fact that they are newly added or not. Instead, it is good practice to alphabetize them, except for BCL references, which should go on top. 2012-04-26 08:17:38.000 buch Should 'using' statements be inside or outside the namespace? C#
  78. Interesting link; nice to see someone else noticed that a good framework should distinguish pointers which are used incorporate an object's identity from those which incorporate state. Personally, I think what's needed is a means of having a variety of storage location types associated with each heap object type (sharable reference to X, exclusively-held reference to X, ephemeral reference to X, etc.). If such types were usable as generic parameters (e.g. List<ExclusiveRef<X>>), I think 99% of cloning situations could be taken care of automatically. 2014-06-11 08:14:41.000 Ankit Deep cloning objects C#
  79. Whilst the standard practice is to implement the ICloneable interface (described here, so I won't regurgitate), here's a nice deep clone object copier I found on The Code Project a while ago and incorporated it in our stuff. 2014-01-13 15:15:42.000 AGreenman Deep cloning objects C#
  80. The idea is that it serializes your object and then deserializes it into a fresh object. The benefit is that you don't have to concern yourself about cloning everything when an object gets too complex.
  81.  
  82. And with the use of extension methods (also from the originally referenced source):
  83.  
  84. In case you prefer to use the new extension methods of C# 3.0, change the method to have the following signature:
  85.  
  86. public static T Clone<T>(this T source)
  87. {
  88. //...
  89. } 2014-08-19 20:38:20.000 StefSan Deep cloning objects C#
  90. David, granted, but if the objects are light, and the performance hit when using it is not too high for your requirements, then it is a useful tip. I haven't used it intensively with large amounts of data in a loop, I admit, but I have never seen a single performance concern. 2012-03-04 06:47:42.000 Chad Deep cloning objects C#
  91. In general, you implement the ICloneable interface and implement Clone yourself. C# objects have a built-in MemberwiseClone method that performs a shallow copy that can help you out for all the primitives.
  92.  
  93. For a deep copy, there is no way it can know how to automatically do it. 2013-07-20 14:55:58.000 MaryDefal Deep cloning objects C#
  94. Basically you need to implement IClonable interface and then realize object structure copying.
  95. If it's deep copy of all members, you need to insure (not relating on solution you choose) that all children are clonable as well.
  96. Sometimes you need to be aware of some restriction during this process, for example if you copying the ORM objects most of frameworks allow only one object attached to the session and you MUST NOT make clones of this object, or if it's possible you need to care about session attaching of these objects. 2014-04-08 12:20:26.000 LloudNe Deep cloning objects C#
  97. The short answer is you inherit from the ICloneable interface and then implement the .clone function. Clone should do a memberwise copy and perform a deep copy on any member that requires it, then return the resulting object. This is a recursive operation ( it requires that all members of the class you want to clone are either value types or implement ICloneable and that their members are either value types or implement ICloneable, and so on). 2011-10-15 22:54:54.000 DanielB Deep cloning objects C#
  98. The long answer is "it depends". As mentioned by others, ICloneable is not supported by generics, requires special considerations for circular class references, and is actually viewed by some as a "mistake" in the .NET Framework. The serialization method depends on your objects being serializable, which they may not be and you may have no control over. There is still much debate in the community over which is the "best" practice. In reality, none of the solutions are the one-size fits all best practice for all situations like ICloneable was originally interpreted to be. 2013-04-05 15:20:46.000 Brodie Deep cloning objects C#
  99. Yes, MemberwiseClone makes a shallow copy, but the opposite of MemberwiseClone isn't Clone; it would be, perhaps, DeepClone, which doesn't exist. When you use an object through its ICloneable interface, you can't know which kind of cloning the underlying object performs. (And XML comments won't make it clear, because you'll get the interface comments rather than the ones on the object's Clone method.) 2012-07-02 20:08:44.000 StefanG Deep cloning objects C#
  100. I'm not clear why ICloneable is considered vague. Given a type like Dictionary(Of T,U), I would expect that ICloneable.Clone should do whatever level of deep and shallow copying is necessary to make the new dictionary be an independent dictionary that contains the same T's and U's (struct contents, and/or object references) as the original. Where's the ambiguity? To be sure, a generic ICloneable(Of T), which inherited ISelf(Of T), which included a "Self" method, would be much better, but I don't see ambiguity on deep vs shallow cloning. 2013-08-12 22:51:26.000 RaviKumar Deep cloning objects C#
  101. Your example illustrates the problem. Suppose you have a Dictionary<string, Customer>. Should the cloned Dictionary have the same Customer objects as the original, or copies of those Customer objects? There are reasonable use cases for either one. But ICloneable doesn't make clear which one you'll get. That's why it's not useful. 2014-04-26 17:43:40.000 HonzaBrabec Deep cloning objects C#
  102. I've seen it implemented through reflection as well. Basically there was a method that would iterate through the members of an object and appropriately copy them to the new object. When it reached reference types or collections I think it did a recursive call on itself. Reflection is expensive, but it worked pretty well. 2014-08-17 19:23:12.000 JonSkeet Deep cloning objects C#
  103. If the two objects are of the same type, it would make more sense to make this a generic method with a single type parameter to enforce that. If they are not the same type, you'll have to handle the possibility that properties with the same name might have incompatible types. For example, S might have a property called "ID" of type int, while T's ID property might be a Guid. 2013-01-25 07:09:16.000 Joiner Deep cloning objects C#
  104. i think about using this method but with recursion. so if the value of a property is a reference, create a new object and call CopyTo again. i just see one problem, that all used classes must have a constructor without parameters. Anybody tried this already? i also wonder if this will actually work with properties containing .net classes like DataRow and DataTable? 2014-09-16 07:19:40.000 buch Deep cloning objects C#
  105. Define an ISelf<T> with a read-only Self property that returns T, and ICloneable<out T>, which derives from ISelf<T> and includes a method T Clone().
  106. Then define a CloneBase type which implements a protected virtual generic VirtualClone casting MemberwiseClone to the passed-in type.
  107. Each derived type should implement VirtualClone by calling the base clone method and then doing whatever needs to be done to properly clone those aspects of the derived type which the parent VirtualClone method hasn't yet handled. 2011-12-19 18:18:11.000 Onorio Deep cloning objects C#
  108. For maximum inheritance versatility, classes exposing public cloning functionality should be sealed, but derive from a base class which is otherwise identical except for the lack of cloning. Rather than passing variables of the explicit clonable type, take a parameter of type ICloneable<theNonCloneableType>. This will allow a routine that expects a cloneable derivative of Foo to work with a cloneable derivative of DerivedFoo, but also allow the creation of non-cloneable derivatives of Foo. 2013-05-25 13:24:28.000 ben Deep cloning objects C#
  109. After much much reading about many of the options linked here, and possible solutions for this issue, I believe all the options are summarized pretty well at Ian P's link (all other options are variations of those) and the best solution is provided by Pedro77's link on the question comments.
  110.  
  111. So I'll just copy relevant parts of those 2 references here. 2011-04-30 05:07:03.000 micori Deep cloning objects C#
  112. The best thing to do for cloning objects in c sharp!
  113.  
  114. First and foremost, those are all our options:
  115.  
  116. Manually with ICloneable, which is Shallow and not Type-Safe
  117. MemberwiseClone, which uses ICloneable
  118. Reflection by using Activator.CreateInstance
  119. Serialization, as pointed by johnc's preferred answer
  120. Intermediate Language, which I got no idea how works
  121. Extension Methods, such as this custom clone framework by Havard Straden 2012-12-18 19:59:49.000 Lingfeng Deep cloning objects C#
  122. All his article circles around an example that tries to be applicable for most cases, using 3 objects: Person, Brain and City. We want to clone a person, which will have its own brain but the same city. You can either picture all problems any of the other methods above can bring or read the article. 2013-04-05 01:35:23.000 Qwerty Deep cloning objects C#
  123. Copying an object by specifying New followed by the class name often leads to code that is not extensible. Using clone, the application of prototype pattern, is a better way to achieve this. However, using clone as it is provided in C# (and Java) can be quite problematic as well. It is better to provide a protected (non-public) copy constructor and invoke that from the clone method. This gives us the ability to delegate the task of creating an object to an instance of a class itself, thus providing extensibility and also, safely creating the objects using the protected copy constructor. 2011-06-05 02:20:28.000 Lorraine Deep cloning objects C#
  124. MS recommends not using ICloneable for public members. "Because callers of Clone cannot depend on the method performing a predictable cloning operation, we recommend that ICloneable not be implemented in public APIs." msdn.microsoft.com/en-us/library/… However, based on the explanation given by Venkat Subramaniam in your linked article, I think it makes sense to use in this situation as long as the creators of the ICloneable objects have a deep understanding of which properties should be deep vs. shallow copies (i.e. deep copy Brain, shallow copy City) 2013-09-03 06:04:59.000 casper Deep cloning objects C#
  125. First off, I'm far from an expert in this topic (public APIs). I think for once that MS remark makes a lot of sense. And I don't think it's safe to assume the users of that API will have such a deep understanding. So, it only makes sense implementing it on a public API if it really won't matter for whoever is going to use it. I guess having some kind of UML very explicitly making the distinction on each property could help. But I'd like to hear from someone with more experience. :P 2013-05-06 15:21:14.000 keveh Deep cloning objects C#
  126. I've just created CloneExtensions library project. It performs fast, deep clone using simple assignment operations generated by Expression Tree runtime code compilation.
  127.  
  128. How to use it?
  129.  
  130. Instead of writing your own Clone or Copy methods with a tone of assignments between fields and properties make the program do it for yourself, using Expression Tree. GetClone<T>() method marked as extension method allows you to simply call it on your instance: 2011-09-27 23:22:22.000 quirk Deep cloning objects C#
  131. What can be cloned?
  132.  
  133. Primitive (int, uint, byte, double, char, etc.), known immutable types (DateTime, TimeSpan, String) and delegates (including Action, Func, etc)
  134. Nullable
  135. T[] arrays
  136. Custom classes and structs, including generic classes and structs.
  137. Following class/struct members are cloned internally:
  138.  
  139. Values of public, not readonly fields
  140. Values of public properties with both get and set accessors
  141. Collection items for types implementing ICollection 2011-02-23 06:45:41.000 darkcat Deep cloning objects C#
  142. How fast it is?
  143.  
  144. The solution is faster then reflection, because members information has to be gathered only once, before GetClone<T> is used for the first time for given type T.
  145.  
  146. It's also faster than serialization-based solution when you clone more then couple instances of the same type T. 2012-11-02 21:22:32.000 Pravinsingh Deep cloning objects C#
  147. I have created a version of the accepted answer that works with both '[Serializable]' and '[DataContract]'. It has been a while since I wrote it, but if I remember correctly [DataContract] needed a different serializer.
  148.  
  149. Requires System, System.IO, System.Runtime.Serialization, System.Runtime.Serialization.Formatters.Binary, System.Xml; 2012-10-27 17:50:58.000 Rafael Deep cloning objects C#
  150. Bepenfriends- Since System.Guid does not throw AggregateException, it would be great if you (or someone) could post an answer showing how you would wrap it into an AggregateException etc. 2014-12-28 13:41:33.000 HHendriks Catch multiple Exceptions at once? C#
  151. If Microsoft introduced, say, StringTooLongException derived from FormatException then it is still a format exception, just a specific one. It depends whether you want the semantics of 'catch this exact exception type' or 'catch exceptions that mean the format of the string was wrong'. 2013-09-29 22:39:31.000 Sydney Catch multiple Exceptions at once? C#
  152. This code is extremely fragile - a library developer could expect to replace throw new FormatException(); with throw new NewlyDerivedFromFormatException(); without breaking code using the library, and it will hold true for all exception handling cases except where someone used == instead of is (or simply catch (FormatException)) 2014-05-24 18:24:28.000 Camacho Catch multiple Exceptions at once? C#
  153. Thank you for that link! I just learned one more important reason not to re-throw: throw e; destroys stacktrace and callstack, throw; destroys "only" callstack (rendering crash-dumps useless!) A very good reason to use neither if it can be avoided! 2012-12-28 20:02:57.000 Kaviraj Catch multiple Exceptions at once? C#
  154. The accepted answer seems acceptable, except that CodeAnalysis/FxCop will complain about the fact that it's catching a general exception type.
  155.  
  156. Also, it seems the "is" operator might degrade performance slightly. http://msdn.microsoft.com/en-us/library/ms182271.aspx says to "consider testing the result of the 'as' operator instead", but if you do that, you'll be writing more code than if you catch each exception separately. 2014-03-11 00:21:22.000 Darshan Catch multiple Exceptions at once? C#
  157. This pattern can be improved by storing the exception(please excuse the poor formatting -- I can't figure out how to put code in comments): Exception ex = null; try { // something } catch( FormatException e){ ex = e; } catch( OverflowException e){ ex = e; } if( ex != null ) { // something else and deal with ex } 2013-11-11 22:49:57.000 Joiner Catch multiple Exceptions at once? C#
  158. Abandoning all the perfectly sane and useful Exception .net provides (ArgumentException, InvalidOperationException etc.) for the sake of being able to catch "MyApplicationBaseException" seems to offer a bad cost/benefit relation. Also, it won't help me if I want to catch exceptions thrown by string.Format and other Framework methods. 2012-08-23 16:46:05.000 HonzaBrabec Catch multiple Exceptions at once? C#
  159. +1 on your comment above. But aren't you looking to abandon all the perfectly sane and useful exception handling syntax provided to elegantly catch multiple exceptions? That you want to execute an identical body of code as a result of differing conditions is pretty much the use-case for a method call. But we don't try to group-together (in potentially obscure if/then blocks) all the other pre-cursors to a particular method call in other parts of our program, so should we do it here? Not arguin', just philosophisin' (in fact I came here as I had the same question as you)! ;-) 2013-03-17 13:00:37.000 JonSkeet Catch multiple Exceptions at once? C#
  160. The .net exception hierarchy may be sane and useful from the standpoint of a human identifying things, but it seems pretty useless from the standpoint of deciding how far the stack needs to be unwound when a problem occurs. For example, if a user selects "Open..." and picks a file that can't be parsed, how should the outer application layer identify which exceptions should simply say "File cannot be opened", and which ones indicate the application as a whole is corrupt and needs to shut down? 2013-11-01 21:30:04.000 RaviKumar Catch multiple Exceptions at once? C#
  161. Precisely--concise, and you totally bypass the performance penalty of handling the exception, the bad form of intentionally using exceptions to control program flow, and the soft focus of having your conversion logic spread around, a little bit here and a little bit there. 2012-09-10 08:19:31.000 StefanG Catch multiple Exceptions at once? C#
  162. One possible advantage of this approach is that there's a semantic difference between catching and rethrowing an exception versus not catching it; in some cases, code should act upon an exception without catching it. Such a thing is possible in vb.net, but not in C# unless one uses a wrapper written in vb.net and called from C#. 2013-09-02 06:36:44.000 DanielB Catch multiple Exceptions at once? C#
  163. Cutting straight to the chase, this kind of duplicates an earlier answer, but if you really want to perform a common action for several exception types and keep the whole thing neat and tidy within the scope of the one method, why not just use a lambda/closure/inline function do something like the following? I mean, chances are pretty good that you'll end up realizing that you just want to make that closure a separate method that you can utilize all over the place. But then it will be super easy to do that without actually changing the rest of the code structurally. Right? 2012-09-18 04:39:53.000 LloudNe Catch multiple Exceptions at once? C#
  164. Because it certainly isn't automatically more readable.
  165.  
  166. Granted, I left the three identical instances of /* write to a log, whatever... */ return; out of the first example.
  167.  
  168. But that's sort of my point. Y'all have heard of functions/methods, right? Seriously. Write a common ErrorHandler function and, like, call it from each catch block. 2014-01-29 18:51:36.000 MaryDefal Catch multiple Exceptions at once? C#
  169. If you ask me, the second example (with the if and is keywords) is both significantly less readable, and simultaneously significantly more error-prone during the maintenance phase of your project. 2015-01-27 00:34:43.000 Chad Catch multiple Exceptions at once? C#
  170. The maintenance phase, for anyone who might be relatively new to programming, is going to comprise 98.7% or more of the overall lifetime of your project, and the poor schmuck doing the maintenance is almost certainly going to be someone other than you. And there is a very good chance they will spend 50% of their time on the job cursing your name. 2011-07-24 09:26:33.000 StefSan Catch multiple Exceptions at once? C#
  171. And of course FxCop barks at you and so you have to also add an attribute to your code that has precisely zip to do with the running program, and is only there to tell FxCop to ignore an issue that in 99.9% of cases it is totally correct in flagging. And, sorry, I might be mistaken, but doesn't that "ignore" attribute end up actually compiled into your app? 2012-09-06 23:06:29.000 AGreenman Catch multiple Exceptions at once? C#
  172. Would putting the entire if test on one line make it more readable? I don't think so. I mean, I did have another programmer vehemently argue once long ago that putting more code on one line would make it "run faster." But of course he was stark raving nuts. Trying to explain to him (with a straight face--which was challenging) how the interpreter or compiler would break that long line apart into discrete one-instruction-per-line statements--essentially identical to the result if he had gone ahead and just made the code readable instead of trying to out-clever the compiler--had no effect on him whatsoever. But I digress. 2013-06-11 09:28:12.000 Ankit Catch multiple Exceptions at once? C#
  173. How much less readable does this get when you add three more exception types, a month or two from now? (Answer: it gets a lot less readable).
  174.  
  175. One of the major points, really, is that most of the point of formatting the textual source code that we're all looking at every day is to make it really, really obvious to other human beings what is actually happening when the code runs. Because the compiler turns the source code into something totally different and couldn't care less about your code formatting style. So all-on-one-line totally sucks, too. 2011-11-27 05:32:54.000 buch Catch multiple Exceptions at once? C#
  176. When I first stumbled across this question I was all over the accepted answer. Cool I can just catch all Exceptions and the check the type. I thought it cleaned up the code, but something kept me coming back to the question and I actually read the other answers to the question. I chewed on it for a while, but I have to agree with you. It is more readable and maintainable to use a function to dry up your code than to catch everything, check the type comparing against a list, wrapping code, and throwing. Thanks for coming late and providing an alternative and sane (IMO) option. +1. 2013-06-04 20:29:22.000 Onorio Catch multiple Exceptions at once? C#
  177. This might be one of those cases where you need to ask yourself: Do I really want to make business with that guy? Another solution would be to press criminal charges against him. Incest is forbidden in most of the world, after all. Finally, your software is broken anyway, because you can (legally) have cycles in a family tree: cousins are allowed to marry in most (all?) western countries. 2011-12-08 15:05:55.000 Rafael Cycles in family tree software C++
  178. You shouldn't add assertions for unlikely things, only impossible things. Cycles are the obvious things that aren't possible in a family tree graph... no one can be his own ancestor via any method. These other assertions are just bogus and should be removed. 2013-12-12 21:32:22.000 HHendriks Cycles in family tree software C++
  179. Maybe next time you'll try a more abstract example. People here can't overlook the incest part and just close it, even if it is a valid question regarding the representation of tree like data. 2011-01-27 12:03:04.000 Sydney Cycles in family tree software C++
  180. It seems you (and/or your company) have a fundamental misunderstanding of what a family tree is supposed to be.
  181.  
  182. Let me clarify, I also work for a company that has (as one of its products) a family tree in its portfolio, and we have been struggling with similar problems. 2012-12-16 13:03:18.000 Camacho Cycles in family tree software C++
  183. The problem, in our case, and I assume your case as well, comes from the GEDCOM format that is extremely opinionated about what a family should be. However this format contains some severe misconceptions about what a family tree really looks like.
  184.  
  185. GEDCOM has many issues, such as incompatibility with same sex relations, incest, etc... Which in real life happens more often than you'd imagine (especially when going back in time to the 1700-1800). 2011-04-09 10:10:25.000 Kaviraj Cycles in family tree software C++
  186. This looks like the right approach, and it's easy enough to extend to detect more complex problems. You can work out a set of "A happened before B" relationships between events. For example, that a person was born before any other events involving them. This is a directed graph. You could then check that the graph contains no cycles. 2011-05-29 21:24:40.000 Joiner Cycles in family tree software C++
  187. If it where only that simple. In older records (even new ones) there are date inconsistencies. Baptism before birth, multiple birth records etc... So to an extent, in official records, there is time travel. We allow this inconsistent data. We allow users to indicate what the application should consider "the" birth record in case of duplicates. And we'll indicate broken timelines if found 2013-06-14 07:42:17.000 JonSkeet Cycles in family tree software C++
  188. GEDCOM is a format created by the The Church of Jesus Christ of Latter-day Saints. The specification clearly states that marriage (MARR) is to be between men and women. For same sex marriage or incest the ASSO tag should be used (ASSOCIATES), also used to indicate friendship or being neighbours. It is clear the same sex marriage is second class relation within this spec. A more neutral spec would not demand male female relations. 2012-01-23 20:18:00.000 HonzaBrabec Cycles in family tree software C++
  189. Potential legal implications aside, it certainly seems that you need to treat a 'node' on a family tree as a predecessor-person rather than assuming that the node can be the-one-and-only person.
  190.  
  191. Have the tree node include a person as well as the successors - and then you can have another node deeper down the tree that includes the same person with different successors. 2013-04-25 16:05:55.000 RaviKumar Cycles in family tree software C++
  192. Finding true cycles in a tree can be done in a few ways. The wrong way is to mark every ancestor from a given individual, and when traversing, if the person you're going to step to next is already marked, then cut the link. This will sever potentially accurate relationships. The correct way to do it is to start from each individual, and mark each ancestor with the path to that individual. If the new path contains the current path as a subpath, then it's a cycle, and should be broken. You can store paths as vector<bool> (MFMF, MFFFMF, etc.) which makes the comparison and storage very fast.
  193.  
  194. There are a few other ways to detect cycles, such as sending out two iterators and seeing if they ever collide with the subset test, but I ended up using the local storage method.
  195.  
  196. Also note that you don't need to actually sever the link, you can just change it from a normal link to a 'weak' link, which isn't followed by some of your algorithms. You will also want to take care when choosing which link to mark as weak; sometimes you can figure out where the cycle should be broken by looking at birthdate information, but often you can't figure out anything because so much data is missing. 2013-01-01 06:06:10.000 Brodie Cycles in family tree software C++
  197. Instead of removing all assertions, you should still check for things like a person being his/her own parent or other impossible situations and present an error. Maybe issue a warning if it is unlikely so the user can still detect common input errors, but it will work if everything is correct.
  198.  
  199. I would store the data in a vector with a permanent integer for each person and store the parents and children in person objects where the said int is the index of the vector. This would be pretty fast to go between generations (but slow for things like name searches). The objects would be in order of when they were created. 2013-11-23 10:46:04.000 DanielB Cycles in family tree software C++
  200. Alternately you could make a clearbits() function instead of &= ~. Why are you using an enum for this? I thought those were for creating a bunch of unique variables with hidden arbitrary value, but you're assigning a definite value to each one. So what's the benefit vs just defining them as variables? 2013-06-13 22:44:56.000 LloudNe How do you set, clear and toggle a single bit in C/C++? C++
  201. The use of enums for sets of related constants goes back a long way in c programing. I suspect that with modern compilers the only advantage over const short or whatever is that they are explicitly grouped together. And when you want them for something other than bitmasks you get the automatic numbering. In c++ of course, they also form distinct types which gives you a little extras static error checking. 2013-06-30 05:58:40.000 MaryDefal How do you set, clear and toggle a single bit in C/C++? C++
  202. I've always found using bitfields is a bad idea. You have no control over the order in which bits are allocated (from the top or the bottom), which makes it impossible to serialize the value in a stable/portable way except bit-at-a-time. It's also impossible to mix DIY bit arithmetic with bitfields, for example making a mask that tests for several bits at once. You can of course use && and hope the compiler will optimize it correctly... 2011-12-22 14:01:23.000 Chad How do you set, clear and toggle a single bit in C/C++? C++
  203. Bit fields are bad in so many ways, I could almost write a book about it. In fact I almost had to do that for a bit field program that needed MISRA-C compliance. MISRA-C enforces all implementation-defined behavior to be documented, so I ended up writing quite an essay about everything that can go wrong in bit fields. Bit order, endianess, padding bits, padding bytes, various other alignment issues, implicit and explicit type conversions to and from a bit field, UB if int isn't used and so on. Instead, use bitwise-operators for less bugs and portable code. Bit fields are completely redundant. 2013-02-14 23:26:59.000 StefSan How do you set, clear and toggle a single bit in C/C++? C++
  204. Like most language features, bit fields can be used correctly or they can be abused. If you need to pack several small values into a single int, bit fields can be very useful. On the other hand, if you start making assumptions about how the bit fields map to the actual containing int, you're just asking for trouble. 2012-11-06 19:28:01.000 AGreenman How do you set, clear and toggle a single bit in C/C++? C++
  205. The bottom line is that this is a general solution to an entire class of problems. It is, of course, possible and even appropriate to rewrite the equivalent of any of these macros with explicit mask values every time you need one, but why do it? Remember, the macro substitution occurs in the preprocessor and so the generated code will reflect the fact that the values are considered constant by the compiler - i.e. it's just as efficient to use the generalized macros as to "reinvent the wheel" every time you need to do bit manipulation. 2012-12-28 07:18:06.000 Ankit How do you set, clear and toggle a single bit in C/C++? C++
  206. What's the point with this? It only makes the code slower and harder to read? I can't see a single advantage with it. 1u << n is easier to read for C programmers, and can hopefully be translated into a single clock tick CPU instruction. Your division on the other hand, will be translated to something around 10 ticks, or even as bad as up to 100 ticks, depending on how poorly the specific architecture handles division. As for the bitmap feature, it would make more sense to have a lookup table translating each bit index to a byte index, to optimize for speed. 2011-01-16 20:42:23.000 buch How do you set, clear and toggle a single bit in C/C++? C++
  207. Your statements are excessively broad (thus useless to argue about). I am sure that I can find situations were they are true. This does not change my initial point. Both of these classes are perfectly fine for use in embedded systems (and I know for a fact that they are used). Your initial point about STL/Boost not being used on embedded systems is also wrong. I am sure there are systems that don't use them and even the systems that do use them they are used judiciously but saying they are not used is just not correct (because there are systems were they are used). 2014-06-17 21:27:35.000 Onorio How do you set, clear and toggle a single bit in C/C++? C++
  208. As this is tagged "embedded" I'll assume you're using a microcontroller. All of the above suggestions are valid & work (read-modify-write, unions, structs, etc.).
  209.  
  210. However, during a bout of oscilloscope-based debugging I was amazed to find that these methods have a considerable overhead in CPU cycles compared to writing a value directly to the micro's PORTnSET / PORTnCLEAR registers which makes a real difference where there are tight loops / high-frequency ISR's toggling pins.
  211.  
  212. For those unfamiliar: In my example, the micro has a general pin-state register PORTn which reflects the output pins, so doing PORTn |= BIT_TO_SET results in a read-modify-write to that register. However, the PORTnSET / PORTnCLEAR registers take a '1' to mean "please make this bit 1" (SET) or "please make this bit zero" (CLEAR) and a '0' to mean "leave the pin alone". so, you end up with two port addresses depending whether you're setting or clearing the bit (not always convenient) but a much faster reaction and smaller assembled code. 2013-06-13 20:39:06.000 ben How do you set, clear and toggle a single bit in C/C++? C++
  213. Note there is nothing "special" about this code. It treats a bit like an integer - which technically, it is. A 1 bit integer that can hold 2 values, and 2 values only.
  214.  
  215. I once used this approach to find duplicate loan records, where loan_number was the ISAM key, using the 6-digit loan number as an index into the bit array. Savagely fast, and after 8 months, proved that the mainframe system we were getting the data from was in fact malfunctioning. The simplicity of bit arrays makes confidence in their correctness very high - vs a searching approach for example. 2011-06-13 20:52:58.000 micori How do you set, clear and toggle a single bit in C/C++? C++
  216. You may have multiple performance problems of different sizes. If you clean out any one of them, the remaining ones will take a larger percentage, and be easier to spot, on subsequent passes. 2012-10-13 22:49:14.000 Lingfeng What can I use to profile C++ code in Linux? C++
  217. Caveat: programmers tend to be skeptical of this technique unless they've used it themselves. They will say that profilers give you this information, but that is only true if they sample the entire call stack, and then let you examine a random set of samples. (The summaries are where the insight is lost.) Call graphs don't give you the same information, because 1) they don't summarize at the instruction level, and 2) they give confusing summaries in the presence of recursion. They will also say it only works on toy programs, when actually it works on any program, and it seems to work better on bigger programs, because they tend to have more problems to find. They will say it sometimes finds things that aren't problems, but that is only true if you see something once. If you see a problem on more than one sample, it is real. 2012-04-18 16:40:15.000 Qwerty What can I use to profile C++ code in Linux? C++
  218. P.S. This can also be done on multi-thread programs if there is a way to collect call-stack samples of the thread pool at a point in time, as there is in Java.
  219.  
  220. P.P.S As a rough generality, the more layers of abstraction you have in your software, the more likely you are to find that that is the cause of performance problems (and the opportunity to get speedup). 2015-01-07 05:43:37.000 Lorraine What can I use to profile C++ code in Linux? C++
  221. Added: It might not be obvious, but the stack sampling technique works equally well in the presence of recursion. The reason is that the time that would be saved by removal of an instruction is approximated by the fraction of samples containing it, regardless of the number of times it may occur within a sample. 2012-09-07 12:02:28.000 casper What can I use to profile C++ code in Linux? C++
  222. Another objection I often hear is: "It will stop someplace random, and it will miss the real problem". This comes from having a prior concept of what the real problem is. A key property of performance problems is that they defy expectations. Sampling tells you something is a problem, and your first reaction is disbelief. That is natural, but you can be sure if it finds a problem it is real, and vice-versa. 2015-02-12 15:34:08.000 keveh What can I use to profile C++ code in Linux? C++
  223. ADDED: Let me make a Bayesian explanation of how it works. Suppose there is some instruction I (call or otherwise) which is on the call stack some fraction f of the time (and thus costs that much). For simplicity, suppose we don't know what f is, but assume it is either 0.1, 0.2, 0.3, ... 0.9, 1.0, and the prior probability of each of these possibilities is 0.1, so all of these costs are equally likely a-priori. 2014-03-19 11:20:46.000 ziba What can I use to profile C++ code in Linux? C++
  224. Now it says P(f >= 0.5) is 26%, up from the prior assumption of 0.6%. So Bayes allows us to update our estimate of the probable cost of I. If the amount of data is small, it doesn't tell us accurately what the cost is, only that it is big enough to be worth fixing. 2011-01-18 19:35:35.000 quirk What can I use to profile C++ code in Linux? C++
  225. Yet another way to look at it is called the Rule Of Succession. If you flip a coin 2 times, and it comes up heads both times, what does that tell you about the probable weighting of the coin? The respected way to answer is to say that it's a Beta distribution, with average value (number of hits + 1) / (number of tries + 2) = (2+1)/(2+2) = 75%. 2014-06-25 19:53:14.000 darkcat What can I use to profile C++ code in Linux? C++
  226. (The key is that we see I more than once. If we only see it once, that doesn't tell us much except that f > 0.)
  227.  
  228. So, even a very small number of samples can tell us a lot about the cost of instructions that it sees. (And it will see them with a frequency, on average, proportional to their cost. If n samples are taken, and f is the cost, then I will appear on nf+/-sqrt(nf(1-f)) samples. Example, n=10, f=0.3, that is 3+/-1.4 samples.) 2012-05-20 22:59:04.000 Pravinsingh What can I use to profile C++ code in Linux? C++
  229. I won't debate the "poor man" part :-) It's true that statistical measurement precision requires many samples, but there are two conflicting goals - measurement and problem location. I'm focussing on the latter, for which you need precision of location, not precision of measure. So for example, there can be, mid-stack, a single function call A(); that accounts for 50% of time, but it can be in another large function B, along with many other calls to A() that are not costly. Precise summaries of function times can be a clue, but every other stack sample will pinpoint the problem. 2012-07-28 10:18:34.000 Rafael What can I use to profile C++ code in Linux? C++
  230. I've had very good luck with Rational Quantify (expensive but very good) and oprofile. Be aware when using oprofile that its a statistical profiler, not a full-on tracing profiler like Quantify. oprofile uses a kernel module to poke into the call stack of every running process on every interval so certain behaviors may not be caught. Using multiple profilers is good, especially since different profilers tend to give you different data all of which is useful.
  231.  
  232. As for using gprof, its ok. I would get one of the graphical front-ends, since the data can be rather difficult to get through just on the command line. I would avoid valgrind, until you require memory checking. 2011-05-22 22:11:53.000 HHendriks What can I use to profile C++ code in Linux? C++
  233. Valgrind is in essence a virtual machine using just-in-time (JIT) compilation techniques, including dynamic recompilation. Nothing from the original program ever gets run directly on the host processor. Instead, Valgrind first translates the program into a temporary, simpler form called Intermediate Representation (IR), which is a processor-neutral, SSA-based form. After the conversion, a tool (see below) is free to do whatever transformations it would like on the IR, before Valgrind translates the IR back into machine code and lets the host processor run it. 2012-05-05 16:11:00.000 Sydney What can I use to profile C++ code in Linux? C++
  234. Callgrind is a profiler build upon that. Main benefit is that you don't have to run your aplication for hours to get reliable result. Even one second run is sufficient to get rock-solid, reliable results, because Callgrind is a non-probing profiler.
  235.  
  236. Another tool build upon Valgrind is Massif. I use it to profile heap memory usage. It works great. What it does is that it gives you snapshots of memory usage -- detailed information WHAT holds WHAT percentage of memory, and WHO had put it there. Such information is available at different points of time of application run. 2012-11-26 18:01:22.000 Camacho What can I use to profile C++ code in Linux? C++
  237. The call graph gets confused by function pointers. Example : I have a function called multithread() which enables me to multi-thread a specified function over a specified array (both passed as arguments). Gprof however, views all calls to multithread() as equivalent for the purposes of computing time spent in children. Since some functions I pass to multithread() take much longer than others my call graphs are mostly useless. (to those wondering if threading is the issue here : no, multithread() can optionally, and did in this case, run everything sequentially on the calling thread only). 2014-04-21 15:27:41.000 Kaviraj What can I use to profile C++ code in Linux? C++
  238. It says here that "... the number-of-calls figures are derived by counting, not sampling. They are completely accurate...". Yet I find my call graph giving me 5345859132+784984078 as call stats to my most called function, where the first number is supposed to be direct calls, and the second recursive calls (which are all from itself). Since this implied I had a bug, I put in long (64bit) counters into the code and did the same run again. My counts : 5345859132 direct, and 78094395406 self-recursive calls. There's a lot of digits there, so I'll point out the recursive calls I measure are 78bn, versus 784m from gprof : a factor of 100 different. Both runs were single threaded and unoptimised code, one compiled -g and the other -pg. 2012-06-26 10:48:34.000 Darshan What can I use to profile C++ code in Linux? C++
  239. Apart from syntactic sugar, a reference is a const pointer (not pointer to const thing, a const pointer). You must establish what it refers to when you declare the reference variable, an you cannot change it later. 2011-04-11 10:45:04.000 Kaviraj What are the differences between a pointer variable and a reference variable in C++? C++
  240. A pointer has its own memory address and size on the stack (4 bytes on x86), whereas a reference shares the same memory address (with the original variable) but also takes up some space on the stack. Since a reference has the same address as the original variable itself, it is safe to think of a reference as another name for the same variable. Note: What a pointer points to can be on the stack or heap. Ditto a reference. My claim in this statement is not that a pointer must point to the stack. A pointer is just a variable that holds a memory address. This variable is on the stack. Since a reference has its own space on the stack, and since the address is the same as the variable it references. More on stack vs heap. This implies that there is a real address of a reference that the compiler will not tell you. 2014-07-06 05:17:01.000 Camacho What are the differences between a pointer variable and a reference variable in C++? C++
  241. While the standard might not require space allocated for the reference, in many cases the compiler will be forced to reserve space. Consider a reference within a class, surely each instance of the class can refer to different external objects, and to which object they refer must be held somehow --in most implementations as an automatically dereferenced pointer (I cannot really think of any other possible implementation that fits all use cases, but then again, I am no expert) 2013-05-05 18:34:23.000 Sydney What are the differences between a pointer variable and a reference variable in C++? C++
  242. See Mark Ransom's answer for a counter-example. This is the most often asserted myth about references, but it is a myth. The only guarantee that you have by the standard is, that you immediately have UB when you have a NULL reference. But that is akin to saying "This car is safe, it can never get off the road. (We don't take any responsibility for what may happen if you steer it off the road anyway. It might just explode.) 2014-06-26 08:41:11.000 HHendriks What are the differences between a pointer variable and a reference variable in C++? C++
  243. Yes, valid programs stay on the road. But there is no traffic barrier to enforce that your program actually does. Large parts of the road are actually missing markings. So it's extremely easy to get off the road at night. And it is crucial for debugging such bugs that you know this can happen: the null reference can propagate before it crashes your program, just like a null pointer can. And when it does you have code like void Foo::bar() { virtual_baz(); } that segfaults. If you are not aware that references may be null, you can't trace the null back to its origin. 2013-07-15 23:55:51.000 Rafael What are the differences between a pointer variable and a reference variable in C++? C++
  244. The actual error is in the dereferencing of the NULL pointer, prior to the assignment to a reference. But I'm not aware of any compilers that will generate any errors on that condition - the error propagates to a point further along in the code. That's what makes this problem so insidious. Most of the time, if you dereference a NULL pointer, you crash right at that spot and it doesn't take much debugging to figure it out. 2011-02-17 08:17:04.000 Pravinsingh What are the differences between a pointer variable and a reference variable in C++? C++
  245. I want to reiterate that the only way to get a null reference is through malformed code, and once you have it you're getting undefined behavior. It never makes sense to check for a null reference; for example you can try if(&bar==NULL)... but the compiler might optimize the statement out of existence! A valid reference can never be NULL so from the compiler's view the comparison is always false - this is the essence of undefined behavior. 2014-04-02 02:41:56.000 darkcat What are the differences between a pointer variable and a reference variable in C++? C++
  246. Schwartz, if I were talking about the way things had to work according to the standard, you'd be correct. But that's not what I'm talking about - I'm talking about actual observed behavior with a very popular compiler, and extrapolating based on my knowledge of typical compilers and CPU architectures to what will probably happen. If you believe references to be superior to pointers because they're safer and don't consider that references can be bad, you'll be stumped by a simple problem someday just as I was. 2012-07-24 05:15:48.000 quirk What are the differences between a pointer variable and a reference variable in C++? C++
  247. Quoting myself: "A reference on the stack doesn't take up any space at all. Or rather, it doesn't matter how much space it takes up since you can't actually see any side effect of whatever space it would take up." In other words, it may have an impact, but you can only observe it through side effects of execution. It doesn't even have a different size from the underlying type. This is different from embedding a reference in another type. 2013-10-30 22:57:23.000 ziba What are the differences between a pointer variable and a reference variable in C++? C++
  248. SQLite doesn't support any kind of 'attach' trigger that I'm aware of, only delete, insert, and update.
  249.  
  250. What you want to do is probably best done by your program, not inside SQLite itself. You should be able to manually drop and re-create the view (necessary since views can't be modified) in your own code anytime you do an attach. Of course this would require a lock (making the table unusable as you said), but that would probably be necessary even if SQLite was doing the work for you.
  251.  
  252. Either way, the view creation is extremely fast, so it shouldn't affect your program's performance. 2011-03-31 18:36:19.000 ben Can I create a SQLite view UNIONING all databases? Databases
  253. The word "subjective" in that context is referring to questions that are entirely a matter of opinion. "What do you think of Joe Celko's book?" - that's a subjective question. This question is soliciting objective information, it just so happens that there is no single "right" answer. I think it's important to take a step back and ask, "is this just idle banter, or is it useful for some developers?" My two cents anyway - it's not like I'm earning rep points for this. :-) 2011-07-31 19:33:03.000 micori What should every developer know about databases? Databases
  254. Personally, I hate these questions. They almost always amount to piles of personal opinions, light on usable information and heavy on subjective declarations. But I'm not willing to close it for that reason alone; it could be half-way decent, Aaron, if you set some guidelines for responses: single-topic answers (what should you know and why should you know it), no duplicates, up-vote what you agree with... and most importantly, move your own opinions into answers that demonstrate this. As it stands, this reads like a blog post, or forum discussion, neither of which have any business on SO. 2014-03-14 11:03:37.000 Lingfeng What should every developer know about databases? Databases
  255. I find this rather interesting: "It's a Community Wiki and therefore appropriate." How on earth can a CW make it appropriate? Either a question is appropriate or not, and I think this question is way to subjective to be helpful if someone is looking for an answer. It might be interesting, but that's not the only characteristic a question must have. 2011-03-15 07:03:20.000 Qwerty What should every developer know about databases? Databases
  256. I will vote to reopen if it gets closed... I would also like to see a list of those things that DBAs should (but do not) know about OOP and application/Systems Software design.. 2012-06-02 12:50:04.000 Lorraine What should every developer know about databases? Databases
  257. Every developer should know that this is false: "Profiling a database operation is completely different from profiling code." 2013-05-24 16:23:31.000 casper What should every developer know about databases? Databases
  258. There is a clear Big-O in the traditional sense. When you do an EXPLAIN PLAN (or the equivalent) you're seeing the algorithm. Some algorithms involve nested loops and are O( n ^ 2 ). Other algorithms involve B-tree lookups and are O( n log n ). 2014-06-27 01:15:47.000 keveh What should every developer know about databases? Databases
  259. This is very, very serious. It's central to understanding why indexes matter. It's central to understanding the speed-normalization-denormalization tradeoffs. It's central to understanding why a data warehouse uses a star-schema which is not normalized for transactional updates. 2013-10-17 12:41:27.000 ziba What should every developer know about databases? Databases
  260. Good question. The following are some thoughts in no particular order:
  261.  
  262. Normalization, to at least the second normal form, is essential.
  263.  
  264. Referential integrity is also essential, with proper cascading delete and update considerations.
  265.  
  266. Good and proper use of check constraints. Let the database do as much work as possible.
  267.  
  268. Don't scatter business logic in both the database and middle tier code. Pick one or the other, preferably in middle tier code.
  269.  
  270. Decide on a consistent approach for primary keys and clustered keys.
  271.  
  272. Don't over index. Choose your indexes wisely.
  273.  
  274. Consistent table and column naming. Pick a standard and stick to it.
  275.  
  276. Limit the number of columns in the database that will accept null values.
  277.  
  278. Don't get carried away with triggers. They have their use but can complicate things in a hurry.
  279.  
  280. Be careful with UDFs. They are great but can cause performance problems when you're not aware how often they might get called in a query.
  281.  
  282. Get Celko's book on database design. The man is arrogant but knows his stuff. 2012-11-25 06:24:09.000 darkcat What should every developer know about databases? Databases
  283. I've always preferred to put it in both places. That way you're protected against bugs as well as user error. There's no reason to make every column nullable, or to allow values outside the range 1-12 to be inserted into a Month column. Complex business rules are, of course, another story. 2013-11-22 21:15:57.000 Pravinsingh What should every developer know about databases? Databases
  284. If it's an absolute certainty that database modifications will only occur in applications then you might be right. However, this is probably pretty rare. Since users will likely enter data directly into the database, it's good practice to put validation in the database as well. Besides, some types of validation are simply more efficiently done in the database. 2012-01-11 00:02:01.000 Rafael What should every developer know about databases? Databases
  285. Most of our applications at work were done well before solid programming processes were put into place. Therefore, we've got business logic scattered everywhere. Some of it's in the UI, some in the middle tier and some in the database. It's a mess. IMO, business logic belongs in the middle tier. 2011-09-17 17:33:25.000 HHendriks What should every developer know about databases? Databases
  286. I would like everyone, both DBAs and developer/designer/architects, to better understand how to properly model a business domain, and how to map/translate that business domain model into both a normalized database logical model, an optimized physical model, and an appropriate object oriented class model, each one of which is (can be) different, for various reasons, and understand when, why, and how they are (or should be) different from one another. 2012-06-11 18:29:28.000 Sydney What should every developer know about databases? Databases
  287. I would say strong basic SQL skills. I've seen a lot of developers so far who know a little about databases but are always asking for tips about how to formulate a quite simple query. Queries are not always that easy and simple. You do have to use multiple joins (inner, left, etc.) when querying a well normalized database. 2011-12-12 19:42:09.000 Camacho What should every developer know about databases? Databases
  288. Every C++ geek wrote a string class in college. Every graphics geek wrote a raytracer in college. Every web geek wrote interactive websites (usually before we had "web frameworks") in college. Every hardware nerd (and even software nerds) built a CPU in college. Every physician dissected an entire cadaver in college, even if she's only going to take my blood pressure and tell me my cholesterol is too high today. Why would databases be any different? 2014-08-31 03:10:03.000 Kaviraj What should every developer know about databases? Databases
  289. It's virtually impossible to get the same level of understanding from just reading about them, or even working your way down from the top. But if you start at the bottom and understand each piece, then it's relatively easy to figure out the specifics for your database. Even things that lots of database geeks can't seem to grok, like when to use a non-relational database. 2013-04-04 12:13:05.000 Darshan What should every developer know about databases? Databases
  290. Maybe that's a bit strict, especially if you didn't study computer science in college. I'll tone it down some: You could write one today, completely, from scratch. I don't care if you know the specifics of how the PostgreSQL query optimizer works, but if you know enough to write one yourself, it probably won't be too different from what they did. And you know, it's really not that hard to write a basic one. 2011-08-16 02:48:28.000 Joiner What should every developer know about databases? Databases
  291. Year after year, researchers come up with new ways of managing data to satisfy special requirements: either requirements to handle data relationships that don't fit into the relational model, or else requirements of high-scale volume or speed that demand data processing be done on distributed collections of servers, instead of central database servers. 2011-02-16 17:22:17.000 JonSkeet The Next-gen Databases Databases
  292. Even though these advanced technologies do great things to solve the specialized problem they were designed for, relational databases are still a good general-purpose solution for most business needs. SQL isn't going away. 2011-10-06 20:33:14.000 HonzaBrabec The Next-gen Databases Databases
  293. Not to be pedantic, but I would like to point out that at least CouchDB isn't SQL-based. And I would hope that the next-gen SQL would make SQL a lot less... fugly and non-intuitive. 2011-06-04 14:23:11.000 RaviKumar The Next-gen Databases Databases
  294. There are special databases for XML like MarkLogic and Berkeley XMLDB. They can index xml-docs and one can query them with XQuery. I expect JSON databases, maybe they already exist. Did some googling but couldn't find one. 2012-07-01 18:19:03.000 StefanG The Next-gen Databases Databases
  295. I'm missing graph databases in the answers so far. A graph or network of objects is common in programming and can be useful in databases as well. It can handle semi-structured and interconnected information in an efficient way. Among the areas where graph databases have gained a lot of interest are semantic web and bioinformatics. RDF was mentioned, and it is in fact a language that represents a graph. Here's some pointers to what's happening in the graph database area: 2013-04-12 07:16:55.000 Brodie The Next-gen Databases Databases
  296. Object databases (OODB) are different from graph databases. Simply put a graphdb won't tie your data directly to your object model. In a graphdb relationships are first class citizens, while you'd have to implement that on your own in an OODB. In a graphdb you can have different object types represent different views on the same data. Graphdbs typically support things like finding shortest paths and the like. 2011-09-15 05:04:56.000 DanielB The Next-gen Databases Databases
  297. In regard to the SQL language as a proper implementation of the relational model, I quote from wikipedia, "SQL, initially pushed as the standard language for relational databases, deviates from the relational model in several places. The current ISO SQL standard doesn't mention the relational model or use relational terms or concepts. However, it is possible to create a database conforming to the relational model using SQL if one does not use certain SQL features." 2014-05-18 03:30:46.000 LloudNe The Next-gen Databases Databases
  298. Thumbs up for "EXEC sp_databases". The reason for this is that "sysdatabases" does not actually exist in SQL 2005 and 2008. It is renamed to "sys.databases". Cheers. 2014-06-11 23:51:53.000 MaryDefal Get list of databases from SQL Server Databases
  299. EXEC sp_databases was slow to execute for me; 40 seconds on an instance with 36 databases. Selecting from sysdatabases was instant. 2011-07-18 20:55:30.000 Chad Get list of databases from SQL Server Databases
  300. System databases with ID 5 and 6 will be ReportServer and ReportServerTempDB if you have SQL Server Reporting Services installed. 2012-06-29 17:57:40.000 StefSan Get list of databases from SQL Server Databases
  301. Only if you were (silly AND installed Reporting Services using the SQL installer (rather than not accepting defaults and configuring using the manager later)) OR (awesome AND installed SQL server using a pre-configured INF file) 2013-10-01 15:59:04.000 AGreenman Get list of databases from SQL Server Databases
  302. I use the following SQL Server Management Objects code to get a list of databases that aren't system databases and aren't snapshots.
  303.  
  304. using Microsoft.SqlServer.Management.Smo;
  305.  
  306. public static string[] GetDatabaseNames( string serverName )
  307. {
  308. var server = new Server( serverName );
  309. return ( from Database database in server.Databases
  310. where !database.IsSystemObject && !database.IsDatabaseSnapshot
  311. select database.Name
  312. ).ToArray();
  313. } 2012-10-14 05:54:40.000 Ankit Get list of databases from SQL Server Databases
  314. This question concern Microsoft SQL Server not a MySQL Server, do not mix them - they might be "sql" server but they are so different in syntax like day and night... MySQL have many useful "commands" but they are not standard SQL, either syntax is very non-standard.. 2014-08-07 20:13:52.000 buch Get list of databases from SQL Server Databases
  315. Not sure if this will omit the Report server databases since I am not running one, but from what I have seen, I can omit system user owned databases with this SQL:
  316.  
  317. SELECT db.[name] as dbname
  318. FROM [master].[sys].[databases] db
  319. LEFT OUTER JOIN [master].[sys].[sysusers] su on su.sid = db.owner_sid
  320. WHERE su.sid is null
  321. order by db.[name] 2013-06-12 00:22:59.000 Onorio Get list of databases from SQL Server Databases
  322. To be blunt, it's a matter of brute force. Simply, it reads through each candidate record in the database and matches the expression to the fields. So, if you have "select * from table where name = 'fred'", it literally runs through each record, grabs the "name" field, and compares it to 'fred'. 2014-05-23 11:41:35.000 ben How do databases work internally? Databases
  323. Now, if the "table.name" field is indexed, then the database will (likely, but not necessarily) use the index first to locate the candidate records to apply the actual filter to.
  324.  
  325. This reduces the number of candidate records to apply the expression to, otherwise it will just do what we call a "table scan", i.e. read every row. 2014-07-25 11:21:59.000 micori How do databases work internally? Databases
  326. Well, a join is used to make a new "pseudo table", upon which the filter is applied. So, you have the filter criteria and the join criteria. The join criteria is used to build this "pseudo table" and then the filter is applied against that. Now, when interpreting the join, it's again the same issue as the filter -- brute force comparisons and index reads to build the subset for the "pseudo table". 2012-07-29 23:14:38.000 Lingfeng How do databases work internally? Databases
  327. One of the keys to good database is how it manages its I/O buffers. But it basically matches RAM blocks to disk blocks. With the modern virtual memory managers, a simpler database can almost rely on the VM as its memory buffer manager. The high end DB'S do all this themselves. 2014-05-30 18:08:29.000 Qwerty How do databases work internally? Databases
  328. B+Trees typically, you should look it up. It's a straight forward technique that has been around for years. It's benefit is shared with most any balanced tree: consistent access to the nodes, plus all the leaf nodes are linked so you can easily traverse from node to node in key order. So, with an index, the rows can be considered "sorted" for specific fields in the database, and the database can leverage that information to it benefit for optimizations. This is distinct from, say, using a hash table for an index, which only lets you get to a specific record quickly. In a B-Tree you can quickly get not just to a specific record, but to a point within a sorted list. 2014-09-11 22:04:43.000 Lorraine How do databases work internally? Databases
  329. The actual mechanics of storing and indexing rows in the database are really pretty straight forward and well understood. The game is managing buffers, and converting SQL in to efficient query paths to leverage these basic storage idioms. 2014-03-12 11:21:07.000 casper How do databases work internally? Databases
  330. Saif, excellent link. A bird's eye overview that manages to cover most topics, and provide details on specific vendor implementations.
  331.  
  332. I made three tries at writing an explanation, but this is really too big a topic. Check out the Hellerstein article (the one on the berkeley server that Saif linked to), and then ask about specifics. 2011-07-29 07:12:53.000 keveh How do databases work internally? Databases
  333. It's worth noting that only a subset of "known good ideas" is implemented in any given DBMS. For example, SQLite doesn't even do hash joins, it only does nested loops (ack!!). But then, it's an easily embeddable dbms, and it does its work very well, so there's something to be said for the lack of complexity. 2011-10-18 07:57:50.000 ziba How do databases work internally? Databases
  334. Learning about how a DBMS gathers statistics and how it uses them to construct query plans, as well as learning how to read the query plans in the first place, is an invaluable skill -- if you have to choose one "database internals" topic to learn, learn this. It will make a world of difference (and you will never accidentally write a Cartesian product again... ;-)). 2014-07-12 08:02:59.000 quirk How do databases work internally? Databases
  335. In addition to reading, it can be instructive to use the DB tools to examine the execution plan that the database uses on your queries. In addition to getting insight into how it is working, you can experiment with techniques to optimize the queries with a better feedback loop. 2013-12-31 14:33:25.000 darkcat How do databases work internally? Databases
  336. If you want to know more in detail, I'd recommend getting the sqlite sources and having a look at how it does it. It's complete, albeit not at the scale of the larger open source and commercial databases. If you want to know more in detail I recommend The Definitive Guide to SQLite which is not only a great explanation of sqlite, but also one of the most readable technical books I know. On the MySQL side, you could learn from MySQL Performance Blog as well as on the book front the O'Reilly High Performance MySQL (V2) of which the blog is one of the authors. 2012-02-10 20:07:09.000 Pravinsingh How do databases work internally? Databases
  337. What architecture did you run on? Did you compile with good optimization settings? I just tried your code, with and without the sort (the C++ variant) and did not find any runtime difference. Having a look at the assembler output (gcc.godbolt.org is handy for that) I could also see that there is no branch done on the if, but a cmovge is being used. When using -O2 I see a difference in speed only, but not with -O3... – PlasmaHH 2011-04-29 21:20:36.000 JonSkeet Why is processing a sorted array faster than an unsorted array? Java
  338. String stands for System.String and it is a .NET Framework type. string is an alias in the C# language for System.String. Both of them are compiled to System.String in IL (Intermediate Language), so there is no difference. Choose what you like and use that. If you code in C#, I'd prefer string as it's a C# type alias and well-known by C# programmers. 2014-02-03 08:06:55.000 ben Java += operator Java
  339. I wanted a cloner for very simple objects of mostly primitives and lists. If your object is out of the box JSON serializable then this method will do the trick. This requires no modification or implementation of interfaces on the cloned class, just a JSON serializer like JSON.NET. 2012-02-19 08:51:32.000 ziba Java += operator Java
  340. I know what you meant, but of course Guid.TryParse never returns Guid.Empty. If the string is in an incorrect format, it sets the result output parameter to Guid.Empty, but it returns false. I'm mentioning it because I've seen code that does things in the style of Guid.TryParse(s, out guid); if (guid == Guid.Empty) { /* handle invalid s */ }, which is usually wrong if s could be the string representation of Guid.Empty 2012-02-06 12:05:05.000 Brodie Java += operator Java
  341. Also, the corollary: More Indexes are Not Better.
  342.  
  343. Sometimes an index focused on one operation will slow other operations down. Depending on the ratio of the two operations, adding an index may have good effects, no overall impact, or be detrimental to overall performance. 2012-02-05 16:53:27.000 quirk Java += operator Java
  344. We have modeled our family tree to what happens in the real world: Events (for example, births, weddings, engagement, unions, deaths, adoptions, etc.). We do not put any restrictions on these, except for logically impossible ones (for example, one can't be one's own parent, relations need two individuals, etc...)
  345.  
  346. The lack of validations gives us a more "real world", simpler and more flexible solution.
  347.  
  348. As for this specific case, I would suggest removing the assertions as they do not hold universally.
  349.  
  350. For displaying issues (that will arise) I would suggest drawing the same node as many times as needed, hinting at the duplication by lighting up all the copies on selecting one of them. 2013-02-17 23:09:27.000 Darshan Java += operator Java
  351. This is one of the reasons why languages like "Go" do not have assertions. They are used to handle cases that you probably didn't think about, all too often. You should only assert the impossible, not simply the unlikely. Doing the latter is what gives assertions a bad reputation. Every time you type assert(, walk away for ten minutes and really think about it.
  352.  
  353. In your particularly disturbing case, it is both conceivable and appalling that such an assertion would be bogus under rare but possible circumstances. Hence, handle it in your app, if only to say "This software was not designed to handle the scenario that you presented".
  354.  
  355. Asserting that your great, great, great grandfather being your father as impossible is a reasonable thing to do.
  356.  
  357. If I was working for a testing company that was hired to test your software, of course I would have presented that scenario. Why? Every juvenile yet intelligent 'user' is going to do the exact same thing and relish in the resulting 'bug report'. 2011-02-21 08:59:39.000 StefanG Java += operator Java
  358. When calling a function, the compiler usually generates memory spaces for the arguments to be copied to. The function signature defines the spaces that should be created and gives the name that should be used for these spaces. Declaring a parameter as a reference just tells the compiler to use the input variable memory space instead of allocating a new memory space during the method call. It may seem strange to say that your function will be directly manipulating a variable declared in the calling scope but remember that when executing a compiled code, there is no more scope, there is just plain flat memory and your function code could manipulate any variables. 2015-02-22 21:31:48.000 keveh Java += operator Java
  359. If you have 5 to 10 minutes, I generally recommend people to read this Integration with Apache Camel by Jonathan Anstey. It's a well written piece which gives a brief introduction to and overview of some of Camel's concepts, and it implements a use case with code samples. In it, Jonathan writes:
  360.  
  361. "Apache Camel is an open source Java framework that focuses on making integration easier and more accessible to developers. It does this by providing:
  362.  
  363. concrete implementations of all the widely used EIPs
  364. connectivity to a great variety of transports and APIs
  365. easy to use Domain Specific Languages (DSLs) to wire EIPs and transports together"
  366. There is also a free chapter of Camel in Action which introduces Camel in the first chapter. Jonathan is a co-author on that book with me. 2013-06-26 15:19:07.000 LloudNe What exactly is Apache Camel? Java
  367. One of the things you need to understand, before you try to understand Apache Camel, are Enterprise Integration Patterns. Not everyone in the field is actually aware of them. While you can certainly read the Enterprise Integration Patterns book, a quicker way to get up to speed on them would be to read something like the Wikipedia article on Enterprise Application Integration.
  368.  
  369. One you have read and understood the subject area, you would be much more likely to understand the purpose of Apache Camel 2012-03-23 14:54:02.000 DanielB What exactly is Apache Camel? Java
  370. My take to describe this in a more accessible way...
  371.  
  372. In order to understand what Apache Camel is, you need to understand what Enterprise Integration Patterns are.
  373.  
  374. Let's start with what we presumably already know: The Singleton pattern, the Factory pattern, etc; They are merely ways of organizing your solution to the problem, but they are not solutions themselves. These patterns were analyzed and extracted for the rest of us by the Gang of Four, when they published their book: Design Patterns. They saved some of us tremendous effort in thinking of how to best structure our code.
  375.  
  376. Much like the Gang of Four, Gregor Hohpe and Bobby Woolf authored the book Enterprise Integration Patterns (EIP) in which they propose and document a set of new patterns and blueprints for how we could best design large component-based systems, where components can be running on the same process or in a different machine.
  377.  
  378. They basically propose that we structure our system to be message oriented -- where components communicate with each others using messages as inputs and outputs and absolutely nothing else. They show us a complete set of patterns that we may choose from and implement in our different components that will together form the whole system.
  379.  
  380. So what is Apache Camel?
  381.  
  382. Apache Camel offers you the interfaces for the EIPs, the base objects, commonly needed implementations, debugging tools, a configuration system, and many other helpers which will save you a ton of time when you want to implement your solution to follow the EIPs.
  383.  
  384. Take MVC. MVC is pretty simple in theory and we could implement it without any framework help. But good MVC frameworks provide us with the structure ready-to-use and have gone the extra mile and thought out all the other "side" things you need when you create a large MVC project and that's why we use them most of the time.
  385.  
  386. That's exactly what Apache Camel is for EIPs. It's a complete production-ready framework for people who want to implement their solution to follow the EIPs. 2011-11-12 23:04:33.000 StefanG What exactly is Apache Camel? Java
  387. In short:
  388.  
  389. When there is a requirement to connect / integrate systems, you will probably need to connect to some data source and then process this data to match your business requirements.
  390.  
  391. In order to do that:
  392.  
  393. 1) You could develop custom program that would do it (might be time consuming and hard to understand, maintain for other developer)
  394.  
  395. 2) Alternatively, you could use Apache Camel to do it in standardised way (it has most of the connectors already developed for you, you just need to set it up and plug your logic - called Process):
  396.  
  397. Camel will help you to:
  398.  
  399. Consume data from any source/format
  400. Process this data
  401. Output data to any source/format
  402. By using Apache Camel you will make it easy to understand / maintain / extend your system to another developer.
  403.  
  404. Apache Camel is developed with Enterprise Integration Patterns. The patterns help you to integrate systems in a good way :-) 2011-01-31 23:57:36.000 HonzaBrabec What exactly is Apache Camel? Java
  405. Here is another attempt at it.
  406.  
  407. You know how there are/were things like Webmethods, ICAN Seebeyond, Tibco BW, IBM Broker. They all did help with integration solutions in the enterprise. These tools are commonly known by the name Enterprise Application Integration (EAI) tools.
  408.  
  409. There were mostly drag drop tools built around these technologies and in parts you would have to write adapters in Java. These adapter code were either untested or had poor tooling/automation around testing.
  410.  
  411. Just like with design patterns in programming, you have Enterprise Integration patterns for common integration solutions. They were made famous by a book of the same name by Gregor Hohpe and Bobby Woolf.
  412.  
  413. Although it is quite possible to implement integration solutions which use one or many EIP, Camel is an attempt at doing this within your code base using one of XML, Java, Groovy or Scala.
  414.  
  415. Camel supports all Enterprise Integration Patterns listed in the book via its rich DSL and routing mechanism.
  416.  
  417. So Camel is a competing technoloy to other EAI tools with better support for testing your integration code. The code is concise because of the Domain Specific Languages (DSLs). It is readable by even business users and it is free and makes you productive. 2011-11-15 11:24:00.000 JonSkeet What exactly is Apache Camel? Java
  418. There are lot of frameworks that facilitates us for messaging and solving problems in messaging. One such product is Apache Camel.
  419.  
  420. Most of the common problems have proven solutions called as design patterns. The design pattern for messaging is Enterprise Integration patterns(EIPs) which are well explained here. Apache camel help us to implement our solution using the EIPs.
  421.  
  422. The strength of an integration framework is its ability to facilitate us through EIPs or other patterns,number of transports and components and ease of development on which Apache camel stands on the top of the list
  423.  
  424. Each of the Frameworks has its own advantages Some of the special features of Apache camel are the following.
  425.  
  426. It provides the coding to be in many DSLs namely Java DSL and Spring xml based DSL , which are popular.
  427. Easy use and simple to use.
  428. Fuse IDE is a product that helps you to code through UI 2014-02-15 12:10:16.000 MaryDefal What exactly is Apache Camel? Java
  429. Camel helps in routing, transformation, monitoring.
  430.  
  431. It uses Routes; which can be described as :
  432.  
  433. When service bus receives particular message, it will route it through no of services/broker destinations such as queue/topics. This path is known as route.
  434.  
  435. Example: your stock application has got some input by analyst, it will be processed through the application/web component and then result will be published to all the interested/registered members for particular stock update. 2013-04-10 05:24:49.000 DanielB What exactly is Apache Camel? Java
  436. A definition from another perspective:
  437.  
  438. Apache Camel is an integration framework. It consists of some Java libraries, which helps you implementing integration problems on the Java platform. What this means and how it differs from APIs on the one side and an Enterprise Service Bus (ESB) on the other side is described in my article "When to use Apache Camel". 2014-08-06 15:37:02.000 Brodie What exactly is Apache Camel? Java
  439. Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.
  440. In other words, serializable objects can be written to streams, and hence files, object databases, anything really.
  441.  
  442. Also, there is no syntactic difference between a JavaBean and another class -- a class defines a JavaBean if it follows the standards.
  443.  
  444. There is a term for it because the standard allows libraries to programmatically do things with class instances you define in a predefined way. For example, if a library wants stream any object you pass into it, it knows it can because your object is serializable (assuming the lib requires your objects be proper JavaBeans). 2015-01-20 13:14:26.000 ben What is a JavaBean exactly? Java
  445. @worldsayshi - No, it's not required. For example a bean can contain a String; and String is not a bean. (String is immutable, so you cannot create it by calling an empty constructor and a setter.) It seems reasonable that a Serializable object should have Serializable members, unless it somehow serializes them from outside. So no, Java bean members do not need to have any aspect of Java beans. Although it is more simple if they are beans, too. 2013-01-09 09:20:31.000 Chad What is a JavaBean exactly? Java
  446. As for Serializable: That is nothing but a "marker interface" (an interface that doesn't declare any functions) that tells Java that the implementing class consents to (and implies that it is capable of) "serialization" -- a process that converts an instance into a stream of bytes. Those bytes can be stored in files, sent over a network connection, etc, and have enough info to allow a JVM (at least, one that knows about the object's type) to reconstruct the object later -- possibly in a different instance of the application, or even on a whole other machine!
  447.  
  448. Of course, in order to do that, the class has to abide by certain limitations. Chief among them is that all instance fields must be either primitive types (int, bool, etc), instances of some class that is also serializable, or marked as transient so that Java won't try to include them. (This of course means that transient fields will not survive the trip over a stream. A class that has transient fields should be prepared to reinitialize them if necessary.)
  449.  
  450. A class that can not abide by those limitations should not implement Serializable (and, IIRC, the Java compiler won't even let it do so.) 2014-09-13 18:42:25.000 MaryDefal What is a JavaBean exactly? Java
  451. JavaBeans are Java classes which adhere to an extremely simple coding convention. All you have to do is to
  452.  
  453. Implement java.io.Serializable interface - To save the state of an object
  454. use a public empty argument constructor - To instantiate the object
  455. And provide public getter and setter methods - To get and set the values of private variables (properties ). 2011-03-04 01:07:32.000 Chad What is a JavaBean exactly? Java
  456. Java Beans are using for less code and more work approach... Java Beans are used throughout Java EE as a universal contract for runtime discovery and access. For example, JavaServer Pages (JSP) uses Java Beans as data transfer objects between pages or between servlets and JSPs. Java EE's JavaBeans Activation Framework uses Java Beans for integrating support for MIME data types into Java EE. The Java EE Management API uses JavaBeans as the foundation for the instrumentation of resources to be managed in a Java EE environment.
  457.  
  458. About Serialization:
  459.  
  460. In object serialization an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.
  461.  
  462. After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory. 2012-11-01 02:14:58.000 StefSan What is a JavaBean exactly? Java
  463. As per the Wikipedia:
  464.  
  465. The class must have a public default constructor (with no arguments). This allows easy instantiation within editing and activation frameworks.
  466.  
  467. The class properties must be accessible using get, set, is (can be used for boolean properties instead of get), and other methods (so-called accessor methods and mutator methods) according to a standard naming convention. This allows easy automated inspection and updating of bean state within frameworks, many of which include custom editors for various types of properties. Setters can have one or more than one argument.
  468.  
  469. The class should be serializable. [This allows applications and frameworks to reliably save, store, and restore the bean's state in a manner independent of the VM and of the platform.]
  470.  
  471. For more information follow this link. 2012-09-13 04:00:42.000 AGreenman What is a JavaBean exactly? Java
  472. Properties of JavaBeans
  473.  
  474. A JavaBean is a Java object that satisfies certain programming conventions:
  475.  
  476. The JavaBean class must implement either Serializable or Externalizable
  477.  
  478. The JavaBean class must have a no-arg constructor
  479.  
  480. All JavaBean properties must have public setter and getter methods
  481.  
  482. All JavaBean instance variables should be private
  483.  
  484. Example of JavaBeans 2011-08-02 18:59:33.000 Ankit What is a JavaBean exactly? Java
  485. The anonymous class you're creating works well. However you should be aware that this is an inner class and as such, it'll contain a reference to the surrounding class instance. So you'll find you can't do certain things with it (using XStream for one). You'll get some very strange errors.
  486.  
  487. Having said that, so long as you're aware then this approach is fine. I use it most of the time for initialising all sorts of collections in a concise fashion.
  488.  
  489. EDIT: Pointed out correctly in the comments that this is a static class. Obviously I didn't read this closely enough. However my comments do still apply to anonymous inner classes. 2011-09-30 11:09:47.000 buch How can I Initialize a static Map? Java
  490. The problem with this approach is that it is not type-safe at all (and if you are using Java, you want type safety). You can put any kind of objects as keys and values. It only really works for a Map<Object, Object> (though one could use an analogous approach with an String[][] for Map<String,String> and similar for other Map<T,T>. It doesn't work for Maps where the key-type is different from the value type. 2013-03-05 15:58:54.000 Onorio How can I Initialize a static Map? Java
  491. Quick question regarding the double brace initialization: When doing this, Eclipse issues a Warning about a missing Serial ID. On one hand, I don't see why a Serial ID would be needed in this specific case, but on the other hand, I usually don't like supressing warnings. What are your thoughts on this? 2013-04-21 17:30:45.000 ben How can I Initialize a static Map? Java
  492. But that I more consider is the code readability and maintainability. In this point of view, I stand a double brace is a better code style rather then static method.
  493.  
  494. The elements are nested and inline.
  495. It is more OO, not procedural.
  496. the performance impact is really small and could be ignored.
  497. Better IDE outline support (rather then many anonymous static{} block)
  498. You saved few lines of comment to bring them relationship.
  499. Prevent possible element leak/instance lead of uninitialized object from exception and bytecode optimizer.
  500. No worry about the order of execution of static block.
  501. In addition, it you aware the GC of the anonymous class, you can always convert it to a normal HashMap by using new HashMap(Map map).
  502.  
  503. You can do this until you faced another problem. If you do, you should use complete another coding style (e.g. no static, factory class) for it. 2012-04-10 16:14:49.000 micori How can I Initialize a static Map? Java
  504. (A subset of) Guava used to be called Google Collections. If you aren't using this library in your Java project yet, I strongly recommend trying it out! Guava has quickly become one of the most popular and useful free 3rd party libs for Java, as fellow SO users agree. (If you are new to it, there are some excellent learning resources behind that link.) 2014-11-04 17:15:29.000 Lingfeng How can I Initialize a static Map? Java
  505. I do not like Static initializer syntax and I'm not convinced to anonymous subclasses. Generally, I agree with all cons of using Static initializers and all cons of using anonymous subclasses that were mentioned in previus answers. On the other hand - pros presented in these posts are not enough for me. I prefer to use static initialization method: 2013-11-11 15:06:21.000 Qwerty How can I Initialize a static Map? Java
  506. I like using the static initializer "technique" when I have a concrete realization of an abstract class that has defined an initializing constructor but no default constructor but I want my subclass to have a default constructor. 2013-02-07 00:51:48.000 Lorraine How can I Initialize a static Map? Java
  507. I like the anonymous class syntax; it's just less code. However, one major con I have found is that you won't be able to serialize that object via remoting. You will get an exception about not being able to find the anonymous class on the remote side. 2011-11-18 21:44:12.000 Chad How can I Initialize a static Map? Java
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement