c++ program to convert centimeters to feet and inches
Round top 25 C# Programming Tips
@ wownetort
Nikita Starichenko7+ years weighed down-stack developer
Hi everyone! On that point is a good deal of information about different C# features. About various life hacks and best practices therein language.
I want to say you about evenly profitable, but fewer popular tips for employed with this language.
1. Not-async "Task/Task<T>" methods should non refund null
Returning null from a not-async Project/Labor<T> method wish cause a NullReferenceException at runtime. This problem can be avoided past returning Chore.FromResult<T>(null) instead.
Bad example:
public Tax<object> GetFooAsync() { return nil; // Recalcitrant } Good illustration:
common Task<object> GetFooAsync() { turn back Task.FromResult<object>(null); } 2. Strings should non be concatenated using '+' in a loop
StringBuilder is more businesslike than string concatenation, especially when the manipulator is continual over and over as in loops.
Bad example:
string str = ""; for (int i = 0; i < arrayOfStrings.Length ; ++i) { str = str + arrayOfStrings[i]; } Solid example:
StringBuilder bld = new StringBuilder(); for (int i = 0; i < arrayOfStrings.Distance; ++i) { bld.Supply(arrayOfStrings[i]); } string str = bld.ToString(); 3. String offset-supported methods should be preferred for finding substrings from offsets
Superficial for a disposed substring starting from a specified offset can be achieved by such code: str.Substring(startIndex).IndexOf(char1). This works well, simply it creates a new string for each Call to the Substring method. When this is finished in a iteration, a great deal of strings are created for zip, which can lead to performance problems if str is large.
To avoid performance problems, string.Substring(startIndex) should non be in chains with the following methods:
- IndexOf
- IndexOfAny
- LastIndexOf
- LastIndexOfAny
For each of these methods, other method acting with an additive parametric quantity is visible to limit an offset.
Using these methods gives the same result while avoiding the initiation of additive String instances.
Bad example:
str.Substring(StartIndex).IndexOf(char1); // Noncompliant; a new string is going to be created by "Substring" Good example:
str.IndexOf(char1, startIndex); 4. Collections should not be passed American Samoa arguments to their have methods
Transient a collection as an argument to the collection's own method is either an error - other statement was intended - or simply nonsensical code.
Further, because much methods require that the argument stay unmodified during the execution, passing a collection to itself rump result in an unexpected behavior.
Bad examples:
var list = new List<int>(); list.AddRange(list); // Unwilling inclination.Concat(listing); // Balker list.Union(list); // Insubordinate; always returns list list.Except(list); // Noncompliant; e'er empty list.Cross(name); // Noncompliant; always heel list.SequenceEqual(number); // Intractable; always true volt-ampere set = new HashSet<int>(); set.UnionWith(set); // Noncompliant; nobelium changes set.ExceptWith(set); // Noncompliant; always empty set.IntersectWith(set); // Noncompliant; no changes set.IsProperSubsetOf(set); // Noncompliant; forever unreal set.IsProperSupersetOf(set); // Noncompliant; always inharmonious set.IsSubsetOf(set); // Recalcitrant; always true fructify.IsSupersetOf(set); // Noncompliant; always true localize.Overlaps(solidification); // Noncompliant; always admittedly put on.SetEquals(set); // Noncompliant; always true set.SymmetricExceptWith(set); // Noncompliant; always empty 5. Empty arrays and collections should equal returned rather of null
Backward null instead of an actual array or collection forces callers of the method to explicitly test for nullity, making them more complex and less readable.
Moreover, in many cases, null is used as a equivalent word for empty.
Bad examples:
public Resultant[] GetResults() { return null; // Noncompliant } public IEnumerable<Result> GetResults() { return null; // Noncompliant } Good examples:
public Result[] GetResults() { return new Result[0]; } public IEnumerable<Result> GetResults() { return Enumerable.Empty<Result>(); } 6. Results of whole number division should not be assigned to unfixed stop variables
When division is performed on ints, the result will forever embody an int. You can assign that result to a double, float Beaver State decimal with automatic type conversion, but having started as an int, the result will likely not glucinium what you expect. If the result of int division is assigned to a aimless-power point variable, preciseness will have been lost before the assignment. Instead, at least one operand should be cast operating theatre promoted to the last type ahead the operation takes place.
Examples:
decimal celestial latitude = 3/2; // Noncompliant decimal fraction dec = (quantitative)3/2; 7. Shared resources should not glucinium used for lockup
Divided resources should not be used for locking as it increases the chance of deadlocks. Whatsoever other thread could acquire (or attempt to acquire) the same lock for another unrelated role.
Instead, a ordained object instance should represent used for each shared resource, to avoid deadlocks or lock contention.
The shadowing objects are considered as shared resources:
- this
- a Type object
- a string along literal
- a string instance
8. Togs should not lock on objects with weak individuality
A thread acquiring a lock on an object that can be accessed across application domain boundaries runs the risk of being blocked by another thread in a different application domain. Objects that terminate be accessed across practical application region boundaries are aforementioned to have weak identity. Types with weak identity are:
- MarshalByRefObject
- ExecutionEngineException
- OutOfMemoryException
- StackOverflowException
- String
- MemberInfo
- ParameterInfo
- Thread
9. Neither "Thread.Resume" nor "Thread.Suspend" should be used
Thread.Freeze and Thread.Resume can give unpredictable results, and both methods have been deprecated. Indeed, if Thread.Suspend is not used very carefully, a thread john equal suspended while holding a lock u, thus leading to a deadlock. Other safer synchronization mechanisms should be used, such as Monitor, Mutex, and Semaphore.
10. Exceptions should non represent explicitly rethrown
When rethrowing an exception, you should do it away simply calling throw; and not throw exc;, because the batch trace is reset with the second syntax, making debugging much harder.
Examples:
try {} catch(ExceptionType1 exc) { Console.WriteLine(exc); bewilder exc; // Noncompliant; stacktrace is reset } catch(ExceptionType2 exc) { Console.WriteLine(exc); throw; // Compliant } catch (ExceptionType3 exc) { throw new Exclusion("My custom message", exc); // Compliant; stack trace well-kept } 11. Exceptions should not be thrown from unheralded methods
IT is expected that whatsoever methods should atomic number 4 called with caution, but others, such as ToString, are potential to "just crop". Throwing an exception from much a method is likely to break callers' code out of the blue.
The problem occurs when an exception is thrown from any of the undermentioned:
- Event accessors
- Object.Equals
- IEquatable.Equals
- GetHashCode
- ToString
- static constructors
- IDisposable.Dispose
- manipulator ==, !=, <, >, <=, >=
- implicit cast operators
Rotten example:
public override string ToString() { if (drawstring.IsNullOrEmpty(List)) { thrust new ArgumentException("..."); // Resistive } } 12. General exceptions should ne'er be thrown
Throwing such general exceptions as Exception, SystemException, ApplicationException, IndexOutOfRangeException, NullReferenceException, OutOfMemoryException and ExecutionEngineException prevents career methods from treatment true, system-generated exceptions otherwise than application-generated errors.
13. Exceptions should not be thrown and twisted in finally blocks
Throwing an exception from within a finally block will masqu some exception which was previously thrown in the try or catch block, and the masked's elision content and stack trace will be squandered.
14. Elision types should be "common"
The point of having custom exclusion types is to convey more information than is available in standard types. But made-to-order exception types essential be public for that to work.
If a method throws a not-populace exception, the best you can do on the caller's side is to catch the closest public base of the class. That is, you lose wholly that customised data you created the exception type to pass.
15. Destructors should not throw exceptions
If Finalize or an overrule of Finalize throws an exception, and the runtime is non hosted by an application that overrides the default policy, the runtime terminates the process immediately without graceful cleanup (finally blocks and finalizers are not dead). This behavior ensures process integrity if the finalizer cannot free or ruin resources.
Bad model:
class MyClass { ~MyClass() { throw new NotImplementedException(); // Insubordinate } } 16. "IDisposables" created in a "using" statement should non be returned
Typically you want to apply using to make a local IDisposable variable; it will trigger disposal of the object when control passes out of the block's scope. The elision to this rule is when your method acting returns that IDisposable. In that case using disposes of the object before the caller can draw practice of it, in all probability causing exceptions at runtime. So you should either absent using or avoid returning the IDisposable.
Bad example:
public FileStream WriteToFile( string path, string text edition) { victimisation (var fs = Data file.Create(path)) // Noncompliant { volt-ampere bytes = Encoding.UTF8.GetBytes(text); fs.Write(bytes, 0, bytes.Length); generate fs; } } 17. "operator==" should not be overloaded along reference book types
The use of == to comparability to objects is expected to do a reference compare. That is, information technology is expected to recall true if and only if they are the same objective instance. Overloading the operator to do anything other testament inevitably lead to the introduction of bugs by callers. Then again, overloading it to coif exactly that is pointless; that's what == does aside default option.
18. "Equals(Object)" and "GetHashCode()" should be overridden in pairs
There is a contract 'tween Equals(objective) and GetHashCode(): If cardinal objects are equal reported to the Equals(object) method, and so calling GetHashCode() happening apiece of them must yield the same result. If this is not the example, many collections won't handle class instances correctly.
In regulate to abide by with the contract, Equals(targe) and GetHashCode() should be either both inherited, or both overridden.
19. "GetHashCode" should not acknowledgment changeable fields
GetHashCode is used to lodge an object in a Lexicon or Hashtable. If GetHashCode uses non-readonly fields and those W. C. Fields change after the object is stored, the object immediately becomes mis-filed in the Hashtable. Any consequent tryout to see if the object is in the Hashtable will return a false disconfirming.
Inferior example:
public int age; national string name; public override int GetHashCode() { int hasheesh = 12; hash += this.age.GetHashCode(); // Noncompliant hash += this.name.GetHashCode(); // Noncompliant return hashish; } Good example:
semipublic readonly DateTime birthday; public thread identify; public reverse int GetHashCode() { int hash = 12; hashish += this.natal day.GetHashCode(); rejoinder hash; } 20. "abstract" classes should not have "public" constructors
Since abstract classes can't be instantiated, there's no point in their having public operating room interior constructors. If there is basic initialization logic that should run when an extending socio-economic class instance is created, you can by entirely means put it in a constructor, but make that constructor reclusive or protected.
21. Character inheritance should not cost algorithmic
Recursion is acceptable in methods, where you rear break come out of it. But with classify types, you end up with code that will compile only non run if you try to instantiate the class.
Dreadful example:
course of instruction C1<T> { } class C2<T> : C1<C2<C2<T>>> // Noncompliant { } var c2 = new C2<int>(); 22. "current Guid()" should non be used
When the syntax new Guid() (i.e. parameterless instantiation) is used, it must be that one of three things is loved:
- An empty GUID, in which character Guid.Empty is clearer.
- A randomly-generated GUID, in which case Guid.NewGuid() should be used.
- A new GUID with a specific initialization, in which subject the initialization parametric quantity is missing.
23. "GC.Collect" should not be named
Calling Gigacycle per second.Collect is seldom necessity, and can significantly bear upon application performance. That's because it triggers a blocking operation that examinesall object in storage for cleanup. Further, you don't have control concluded when this blocking cleanup will actually test.
As a general rule, the consequences of calling this method cold outweigh the benefits unless perhaps you've just triggered some event that is unique in the prevail of your program that caused a lot of long-lived objects to die.
24. Sections of code should not be commented out
Programmers should not annotate forbidden code Eastern Samoa it bloats programs and reduces readability.
Idle code should be deleted and can be retrieved from source control history if required.
25. "goto" statement should not be exploited
goto is an unstructured control flow statement. It makes code less legible and maintainable. Structured control flow statements such as if, for, while, continue or break should be used instead.
P.S. Thanks for indication! More tips coming soon! Special thanks to SonarQube and their rules - https://www.sonarqube.org/
Tags
c++ program to convert centimeters to feet and inches
Source: https://hackernoon.com/top-25-c-programming-tips-xlo31wv
Posting Komentar untuk "c++ program to convert centimeters to feet and inches"