Skip to content

Latest commit

 

History

History
207 lines (207 loc) · 21.5 KB

Rules.md

File metadata and controls

207 lines (207 loc) · 21.5 KB

Error list

GCop code Description
100 Replace with Log.Error(...)
101 Too many parameters as argument. Define a container and encapsulate them
102 Use {"Address"}.AsDirectory() instead of {new DirectoryInfo("Address")}
103 Instead of 'null', return an empty collection such as 'Enumerable.Empty<method.ReturnType>'
104 Remove empty partial class
106 Use FileAddressString.AsFile() instead of New FileInfo(FileAddressString)
107 Do not use {this.Get()}. 'this' is never null
108 Instead of GetValueOrDefault(defaultValue) method use " ?? defaultValue".
109 Use something.HasMany() instead of something.Count() > 1, as it will be faster and more descriptive.
111 Use implicit generic method typing
112 This class is too large. Break its responsibilities down into more classes.
114 DateTime.Now is not TDD friendly. Use LocalTime.Now instead.
115 This IF statement is too long for one line. Break the body of the IF into another line
116 Break this down into smaller methods. If such methods would become meaningless as standalone methods in the context of the class, you can refactor this method into a Stateful Service class
117 The meaning of true / false is not obvious. Specify the parameter's name explicitly.
119 Don’t use ref / out parameters in method definition. To return several objects, define a class or struct for your method return type.
120 Use someIntVariable.Hours() instead of TimeSpan.FromHours(someIntVariable)
121 Use numeric string.To< data type >() instead of data type.Parse(numeric string)
122 Use Database.CreateTransactionScope() instead of {TransactionScope}
123 Transaction is created but the method.Complete() is never called.
124 Use numeric string.TryParseAs< data type >() instead of data type.TryParse(numeric string)
126 To handle both null and empty string scenarios, use IsEmpty / HasValue instead
127 Use {CollectionName}.IDs() instead of {ColectionName.select}
128 {IHierarchy} interface should be set in M# on the entity definition
129 Change to an instance method, instead of taking a parameter with the same type as the class.
130 Instead of ?? Enumerable.Empty<>() use .OrEmpty() for collections that can be null
131 Use {collectionName}.ToString({separator}) instead of {string.Join}({separator}, {collectionName})
132 Since the type is inferred, use 'var' instead
134 This method should not contain complex code, Instead call other focused methods to perform the complex logic
135 Add a 'default' block after the last case in a switch statement. For example if you don't support anything other than your specified 'cases' throw a NotSupportedException
136 All constants and class fields should be defined at the top of the class, before all methods.
137 Avoid locking on a Type or on the current object instance.
138 When you catch an exception you should throw exception or at least log the error
140 Consider making it "private" as it's not used outside of this class.
141 Avoid using goto command
142 Replace {!stringObject.HasValue()} with {stringObject.IsEmpty()}
143 First line of OnSaved() method must be a call to base.OnSaved() otherwise CachedReferences will have a problem.
144 Since there is only one statement, remove the unnecessary braces and write it as Database.Update( myObject, x => x.Abc = value );
145 This phrase is translated to SQL which handles NULL implicitly. Do not worry about null values and write your query against the property (path) simply without using .Get(x => x...) or ?.
146 This public method doesn't seem to be used in the solution. Consider removing it.
147 Instead of comparing the Id properties, just compare the objects directly.
148 All constructors should be before all methods in a class.
149 Instead of using string literal as parameter name use nameof(variableName)
151 Equals or == should be used
153 Instead use IEnumerable< T >.Lacks(T item)
154 Should be written simply as {FirstCollection}.Except({SecondCollection})
155 Should be written simply as {CollectionName}.Intersect({AnotherCollectionName})
156 Should be written as CookieProperty.Remove({key})
157 Use == instead
159 In OnSaved method, the property IsNew must not be used, instead use: e.Mode == SaveMode.Insert
160 This is not readable. Either refactor into a method, or use If / else statement.
161 Since the {left / right} side of condition is just Bool, then " == true" is unnecessary
162 Replace with .IsAnyOf()
163 Subsequent OrderBy or OrderByDescending cancel each other out. Instead ThenBy or ThenByDescending should be called.
164 Instead use Config.GetConnectionString()
165 Instead of .IndexOf({intendedChar}) > -1 use .Contains({intendedChar}).
166 Avoid assignment within conditional statements
167 OnSaving() is called after Validate() and property values set in OnSaving() won't be validated. Instead use OnValidating() to write your prep logic.
168 Don't instantiate a variable with the new keyword if you are going to assign it to a different object immediately.
169 Remove {NullableObject.HasValue} which is redundant. If {NullableObject.HasValue} is null, then '{rightExpression}' will be false anyway.
171 There is no need for calling .Value. Replace with 'Parameter without .Value'
172 Remove the check for null. Instead use NullableObject?.Invoke()
173 Don't throw exception inside static constructors.
174 You should use the method Exists() instead of the property, because the property caches the result - which can cause problems.
175 This condition is very long. Either refactor that into a method, or define interim variables to 'document' your purpose, and use the variable(s) in the IF clause.
176 This anonymous method should not contain complex code, Instead call other focused methods to perform the complex logic
177 Variable declaration is unnecessary due to it being used only for return statement
178 Use parenthesis to clarify your boolean logic intention.
179 Do not hardcode numbers, strings or other values. Use constant fields, enums, config files or database as appropriate
180 Double and float comparison isn't exact in .NET. Use myDouble.AlmostEquals(anotherDouble) instead.
181 Define a virtual method and write this logic using polymorphism.
200 Since the class is an attribute, the name of the class must end with 'Attribute'
201 Use camelCasing when declaring local variables / a parameter.
202 Don’t end the name of methods with the same name as the class
203 Use meaningful names instead of single character for foreach identifier
204 Rename the variable 'variable name' to something clear and meaningful.
205 Interfaces must start with the letter 'I'."
206 Avoid using underscores in the class name
207 The logic seems extensive. Rename the method to imply this. E.g: Calculate, Find, Select, Create, Evaluate, etc
209 Use PascalCasing for (class or enum or ... ) names.
210 Suffix the name of a service class with 'Service' as it's inside the Services folder.
214 The variable defined to return the result of the method should be named result
215 Rename the method to 'Count...' as it's shorter and more readable
216 A method named GetMethodName is expected return a value. If it's meant to be void, then use a verb other than Get such as Read, Download, Sync, ...
217 Rename the method to Is...Valid
218 For consistency and clarity, use '@this' instead of {'argumentName'} for the first parameter of extension methods
300 Replace with None()
301 Do not throw exceptions using default constructor or with empty message
302 Since 'Idisposable object' implements IDisposable, wrap it in a using() statement
304 Property named {ParameterName}Id should be used instead
305 Error messageReplace with Database.Find<{T}>({LambdaExpression})
306 Instead use {< Or > Or <= Or >= Or > and < } so it can be converted into a SQL statement and run faster
309 It should be written as {lambdaExpression}, Because the criteria will be faster and eliminate unnecessary database fetches
311 Throw exception without specifying the original exception. Remove 'exceptionIdentifier' from throw statement.
313 Where should be called first, so it is not doing unnecessary ordering of objects that will be thrown away.
314 You don't need the Where clause. Replace with FirstOrDefault(LambdaExpression)
315 It should be written instead as: Database.Count<{T}>{(LambdaExpression)}
317 This code is repeated 'repetition count' times in this method. If its value remains the same during the method execution, store it in a variable. Otherwise define a method (or Func variable) instead of repeating the expression. 'expression type'
318 This will cause the query to be computed multiple times. Instead call .ToList() on the variable declaration line to avoid unwanted extra processing.
319 [Database.Save(this);] without condition will create a loop in {OnSaved / OnSaving} method.
320 While {IEnumerable<T>} is being enumerated at run-time, saving of each of its items can potentially affect the source expression from which this IEnumerable object is define upon. To avoid unintended side effects, evaluate myobjects into an Array or List before passing it to Database.XXX.
321 The variable {VariableName} is enumerated multiple times. To improve performance, call .ToList() where it's defined.
400 Remove empty object initializer.
401 Instead of setting the properties in separate lines, use constructor initializers.
402 Remove unnecessary parenthesis.
403 Change {PropertyName} to an auto property
404 Multiple 'if' and 'else if' on the same variable can be replaced with a 'switch'
405 You should use {'conditional access'}
408 Flag or switch parameters (bool) should go after all non-optional parameters. If the boolean parameter is not a flag or switch, split the method into two different methods, each doing one thing.
410 This method seems unnecessary as it only calls the base virtual method.
412 Don't hardcode a path. Consider using “AppDomain.CurrentDomain.GetPath()" instead.
413 It should be written as 'positive expression'
414 Remove .ToString() as it's unnecessary.
415 The same code is repeated in multiple IF branches. Instead update the IF condition to cover both scenarios.
418 Remove the unnecessary casting.
419 This statement is too long and hard to read. Press Enter at logical breaking points to split it into multiple lines.
420 Methods should not be empty.
421 The conditions seems redundant. Either remove the ternary operator, or fix the values.
423 This condition was just checked on line {lineNumber}.
424 This method is redundant. Callers of this method can just call {Collection Name}.Count() which is as clean.
429 Change to {LambdaIdentifier.Id} == {EntityObject} as you can compare Guid with Entity directly. It handles null too.
430 Use " NotEqualsExpression.HasValue " as negative logic is taxing on the brain.
431 Use " {expression } is {type} " as negative logic is taxing on the brain.
432 Unnecessary parenthesis should be removed.
433 Class name is unnecessary here. Static members can be called directly.
434 Class name is unnecessary here. Static members can be called directly.
435 Finally block should not be empty
437 Complete the task associated to this "TODO" comment.
439 Only one partial file for a class should specify the class modifiers (public, static, ...)
500 Void async methods cannot be awaited. Also they can hide exceptions and cause tricky bugs. Return a Task instead.
501 Do not call {'MethodName'} method of class {'ClassName'} as a static method
502 The parameter '{ParameterName}' doesn't seem to be used in this method. Consider removing it. If the argument must be declared for compiling reasons, rename it to contain only underscore character.
504 The number of arguments in {Format / FormatWith} is incorrect.
507 Remember to implement this method.
508 Since the condition is already a boolean it can be returned directly.
511 Either remove the parameter documentation node, or describe it properly.
512 Use "NullableObject.Value" instead.
513 It should be written as {Collection}.FirstOfDefault({argument}) ?? {conditionWhenFalse}.
516 Mark {PropertyName} as Unique in M# and use the autogenerated FindBy{PropertyName} method instead.
517 {'MethodName()'} returns a value but doesn't change the object. It's meaningless to call it without using the returned result.
519 Use MaxOrNull(LambdaExpression) instead.
521 Change it to {'NotRoundedObject'}.Round(digits).
523 Database search is case insensitive. Simply use {LambdaIdentifier}.{Property} == yourValue for a faster execution.
524 Remove private keyword.
526 Use the Generic version instead. Ensure you have using System.Reflection;
528 Use IsA() or IsA<T>() instead.
529 Use 'IEnumerable< MyClassObject >' instead.
530 Write this as {variableName}.WithSuffix({SuffixString}).
531 Write this as {variableName}.WithPrefix({PrefixString}).
533 Choose return type of IEnumerable<\{entityType}> to imply that it's not modifiable.
534 Use yourMemberInfo.Defines< TYPE > instead.
535 Use ToLocal() method instead, so you get control over it using via LocalTime.CurrentTimeZone.
536 Remove empty xml node documentation
538 File extensions can have different casing. Use case insensitive string comparison.
539 Don't hard-code URLs in the code as they might be subject to change. Use Config.Get(...) instead.
540 Abstract class should not have public constructors. Make it protected instead.
541 Simply the method by removing the async and await keywords and just return the task directly.
543 The Result property of the Task object should never be called. Either properly await it, or call GetAlreadyCompletedResult().
544 It should be written as : SomeParameter = -SomeParameter
605 Use {parameterName}.To<{toType}>() instead.
606 For string value existence checking use the more readable methods of .HasValue() or .IsEmpty()
607 It should be written as Enumerable.Except< TSource >
608 A secure file should be made available only to authorized users, not just any user. Apply proper checks.
611 It should be written as Database.Reload({ParameterName}).
613 It should be written as Database.Get<{T}>({Guid}).
614 Random instance should be defined and instantiated as a static class field.
615 Negative logical comparisons are taxing on the brain. Instead of "!object.Any()" use "object.None()".
616 Reverse your IF criteria and use 'continue'. That will eliminate the need for a big IF block and make the code more readable.
617 Avoid deep nesting of IF statements. Break the method down into smaller methods, or return early if possible.
618 Use {EntityName.FindByPropertyName("SomeValue")} instead.
619 Should be written "{'conditionText'}".
620 To simplify the condition use the "??".
621 Drop "Where" and move the condition into the "FirstOrDefault".
622 Reverse your IF condition and return. Then move the nested statements to after the IF.
624 Write it as {CollectionName}.{Contains}(VALUE)
625 Using != operator on the entity is not converted into SQL. Use x.ID != [...].ID instead.
626 The condition is unnecessary.
627 Instead of « ?? false » use the more readable expression of « == true »
629 {EntityName} already has a property named {PropertyName}, Use that instead of ID
630 Override the Validate() method and write your validation logic there.
631 All validation logic should be written inside Validate() method. OnValidating is meant to be used for special cases such as setting late-bound default values.
632 Use OnValidating() for setting late-bound properties. Validate() should only be used for validation, without changing the object state.
633 Instead of hard-coding the boundary check, set the boundary of the NumericProperty in its M# definition.
634 Instead of private property, use a class field.
635 The condition of the where clause is very long and should be turned into a method.
636 It should be written as if ( {'NullableObject'}?.{'YourProperty'} == someValue)
637 This will be invoked twice: once for a clone of the object, and once for the actual object
638 Shorten this method by defining it as expression-bodied.
639 It should be written as if ({'yourObject'}?.{'Property'} != null)
640 Write it as {CollectionName}.Contains(VALUE)
641 Use the OrEmpty() method instead.
642 Replace with {whenTrueReturnType}.Or({whenFalseReturnType})
643 Change to return {something} ?? {somethingElse};
646 Email addresses should not be hard-coded. Move this to Settings table or Config file.
647 Shorten this property by defining it as expression-bodied.
648 Use stringPhrase.Remove(oldValue) instead
650 If this is an Api controller, instead of [Authorize] use [AuthorizeApi] attribute.
651 Wait() method can cause a deadlock. Use the await keyword on the method call instead.
652 if ({myVariable}.Any()) is unnecessary when using foreach.
653 Use the await keyword on the method call instead of AsyncMethod().Result; Also it can be used AsyncMethod().GetAwaiter().GetResult(); for better exception handling.
654 Awaiting null will throw a runtime error. Add '?? Task.CompletedTask' after the expression.
655 Change this method to return a Task
690 Negative logic is taxing on the brain. Use variable == null instead.
691 Non-public methods should not need basic argument validation.