-
Notifications
You must be signed in to change notification settings - Fork 227
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Rule S3909: Collections should implement the generic interface #389
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
7db7b13
Rule S3909: Collections should implement the generic interface
michalb-sonar 1e79e7d
Tweaks following code review.
michalb-sonar 9f7ca1a
Adding extension method to dictionary.
michalb-sonar e364ff6
Use overloads instead of optional parameters.
michalb-sonar File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
<p>The NET Framework 2.0 introduced the generic interface <code>System.Collections.Generic.IEnumerable<T></code> and it should be preferred over | ||
the older, non generic, interfaces.</p> | ||
<p>This rule raises an issue when a public type implements <code>System.Collections.IEnumerable</code>.</p> | ||
<h2>Noncompliant Code Example</h2> | ||
<pre> | ||
using System; | ||
using System.Collections; | ||
|
||
public class MyData | ||
{ | ||
public MyData() | ||
{ | ||
} | ||
} | ||
|
||
public class MyList : CollectionBase // Noncompliant | ||
{ | ||
public void Add(MyData data) | ||
{ | ||
InnerList.Add(data); | ||
} | ||
|
||
// ... | ||
} | ||
</pre> | ||
<h2>Compliant Solution</h2> | ||
<pre> | ||
using System; | ||
using System.Collections.ObjectModel; | ||
|
||
public class MyData | ||
{ | ||
public MyData() | ||
{ | ||
} | ||
} | ||
|
||
public class MyList : Collection<MyData> | ||
{ | ||
// Implementation... | ||
} | ||
</pre> | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
{ | ||
"title": "Collections should implement the generic interface", | ||
"type": "CODE_SMELL", | ||
"status": "ready", | ||
"remediation": { | ||
"func": "Constant\/Issue", | ||
"constantCost": "15min" | ||
}, | ||
"tags": [ | ||
|
||
], | ||
"defaultSeverity": "Major" | ||
} |
53 changes: 53 additions & 0 deletions
53
sonaranalyzer-dotnet/src/SonarAnalyzer.CSharp/Helpers/CollectionUtils.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
/* | ||
* SonarAnalyzer for .NET | ||
* Copyright (C) 2015-2017 SonarSource SA | ||
* mailto: contact AT sonarsource DOT com | ||
* | ||
* This program is free software; you can redistribute it and/or | ||
* modify it under the terms of the GNU Lesser General Public | ||
* License as published by the Free Software Foundation; either | ||
* version 3 of the License, or (at your option) any later version. | ||
* | ||
* This program is distributed in the hope that it will be useful, | ||
* but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | ||
* Lesser General Public License for more details. | ||
* | ||
* You should have received a copy of the GNU Lesser General Public License | ||
* along with this program; if not, write to the Free Software Foundation, | ||
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. | ||
*/ | ||
|
||
using System.Collections.Generic; | ||
|
||
namespace SonarAnalyzer.Helpers | ||
{ | ||
public static class CollectionUtils | ||
{ | ||
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> enumerable) | ||
{ | ||
if (enumerable == null) | ||
{ | ||
return new HashSet<T>(); | ||
} | ||
|
||
return new HashSet<T>(enumerable); | ||
} | ||
|
||
public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key) | ||
{ | ||
return dictionary.GetValueOrDefault(key, default(TValue)); | ||
} | ||
|
||
public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue) | ||
{ | ||
TValue result; | ||
if (dictionary.TryGetValue(key, out result)) | ||
{ | ||
return result; | ||
} | ||
|
||
return defaultValue; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
99 changes: 99 additions & 0 deletions
99
...lyzer-dotnet/src/SonarAnalyzer.CSharp/Rules/CollectionsShouldImplementGenericInterface.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
/* | ||
* SonarAnalyzer for .NET | ||
* Copyright (C) 2015-2017 SonarSource SA | ||
* mailto: contact AT sonarsource DOT com | ||
* | ||
* This program is free software; you can redistribute it and/or | ||
* modify it under the terms of the GNU Lesser General Public | ||
* License as published by the Free Software Foundation; either | ||
* version 3 of the License, or (at your option) any later version. | ||
* | ||
* This program is distributed in the hope that it will be useful, | ||
* but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | ||
* Lesser General Public License for more details. | ||
* | ||
* You should have received a copy of the GNU Lesser General Public License | ||
* along with this program; if not, write to the Free Software Foundation, | ||
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. | ||
*/ | ||
|
||
using System.Collections.Generic; | ||
using System.Collections.Immutable; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.CSharp; | ||
using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
using Microsoft.CodeAnalysis.Diagnostics; | ||
using SonarAnalyzer.Common; | ||
using SonarAnalyzer.Helpers; | ||
|
||
namespace SonarAnalyzer.Rules.CSharp | ||
{ | ||
[DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
[Rule(DiagnosticId)] | ||
public sealed class CollectionsShouldImplementGenericInterface : SonarDiagnosticAnalyzer | ||
{ | ||
internal const string DiagnosticId = "S3909"; | ||
private const string MessageFormat = "Refactor this collection to implement '{0}'."; | ||
|
||
private static readonly DiagnosticDescriptor rule = | ||
DiagnosticDescriptorBuilder.GetDescriptor(DiagnosticId, MessageFormat, RspecStrings.ResourceManager); | ||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(rule); | ||
|
||
private static readonly Dictionary<string, KnownType> nongenericToGenericMapping = | ||
new Dictionary<string, KnownType> | ||
{ | ||
[KnownType.System_Collections_ICollection.TypeName] = KnownType.System_Collections_Generic_ICollection_T, | ||
[KnownType.System_Collections_IList.TypeName] = KnownType.System_Collections_Generic_IList_T, | ||
[KnownType.System_Collections_IEnumerable.TypeName] = KnownType.System_Collections_Generic_IEnumerable_T, | ||
[KnownType.System_Collections_CollectionBase.TypeName] = KnownType.System_Collections_ObjectModel_Collection_T, | ||
}; | ||
|
||
private static readonly ISet<KnownType> genericTypes = nongenericToGenericMapping.Values.ToHashSet(); | ||
|
||
protected override void Initialize(SonarAnalysisContext context) | ||
{ | ||
context.RegisterSyntaxNodeActionInNonGenerated(c => | ||
{ | ||
var classDeclaration = c.Node as ClassDeclarationSyntax; | ||
|
||
var implementedTypes = classDeclaration?.BaseList?.Types; | ||
if (implementedTypes == null) | ||
{ | ||
return; | ||
} | ||
|
||
var issues = new List<Diagnostic>(); | ||
foreach (var typeSyntax in implementedTypes) | ||
{ | ||
var typeSymbol = c.SemanticModel.GetSymbolInfo(typeSyntax.Type).Symbol?.GetSymbolType(); | ||
if (typeSymbol == null) | ||
{ | ||
continue; | ||
} | ||
|
||
if (typeSymbol.OriginalDefinition.IsAny(genericTypes)) | ||
{ | ||
return; | ||
} | ||
|
||
var suggestedGenericType = SuggestGenericCollectionType(typeSymbol); | ||
if (suggestedGenericType != null) | ||
{ | ||
issues.Add(Diagnostic.Create(rule, | ||
classDeclaration.Identifier.GetLocation(), | ||
suggestedGenericType)); | ||
} | ||
} | ||
|
||
issues.ForEach(c.ReportDiagnostic); | ||
}, | ||
SyntaxKind.ClassDeclaration); | ||
} | ||
|
||
private static string SuggestGenericCollectionType(ITypeSymbol typeSymbol) | ||
{ | ||
return nongenericToGenericMapping.GetValueOrDefault(typeSymbol.ToDisplayString())?.TypeName; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
43 changes: 43 additions & 0 deletions
43
sonaranalyzer-dotnet/src/SonarAnalyzer.Utilities/Rules.Description/S3909.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
<p>The NET Framework 2.0 introduced the generic interface <code>System.Collections.Generic.IEnumerable<T></code> and it should be preferred over | ||
the older, non generic, interfaces.</p> | ||
<p>This rule raises an issue when a public type implements <code>System.Collections.IEnumerable</code>.</p> | ||
<h2>Noncompliant Code Example</h2> | ||
<pre> | ||
using System; | ||
using System.Collections; | ||
|
||
public class MyData | ||
{ | ||
public MyData() | ||
{ | ||
} | ||
} | ||
|
||
public class MyList : CollectionBase // Noncompliant | ||
{ | ||
public void Add(MyData data) | ||
{ | ||
InnerList.Add(data); | ||
} | ||
|
||
// ... | ||
} | ||
</pre> | ||
<h2>Compliant Solution</h2> | ||
<pre> | ||
using System; | ||
using System.Collections.ObjectModel; | ||
|
||
public class MyData | ||
{ | ||
public MyData() | ||
{ | ||
} | ||
} | ||
|
||
public class MyList : Collection<MyData> | ||
{ | ||
// Implementation... | ||
} | ||
</pre> | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
37 changes: 37 additions & 0 deletions
37
.../src/Tests/SonarAnalyzer.UnitTest/Rules/CollectionsShouldImplementGenericInterfaceTest.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
/* | ||
* SonarAnalyzer for .NET | ||
* Copyright (C) 2015-2017 SonarSource SA | ||
* mailto: contact AT sonarsource DOT com | ||
* | ||
* This program is free software; you can redistribute it and/or | ||
* modify it under the terms of the GNU Lesser General Public | ||
* License as published by the Free Software Foundation; either | ||
* version 3 of the License, or (at your option) any later version. | ||
* | ||
* This program is distributed in the hope that it will be useful, | ||
* but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | ||
* Lesser General Public License for more details. | ||
* | ||
* You should have received a copy of the GNU Lesser General Public License | ||
* along with this program; if not, write to the Free Software Foundation, | ||
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. | ||
*/ | ||
|
||
using Microsoft.VisualStudio.TestTools.UnitTesting; | ||
using SonarAnalyzer.Rules.CSharp; | ||
|
||
namespace SonarAnalyzer.UnitTest.Rules | ||
{ | ||
[TestClass] | ||
public class CollectionsShouldImplementGenericInterfaceTest | ||
{ | ||
[TestMethod] | ||
[TestCategory("Rule")] | ||
public void CollectionsShouldImplementGenericInterface() | ||
{ | ||
Verifier.VerifyAnalyzer(@"TestCases\CollectionsShouldImplementGenericInterface.cs", | ||
new CollectionsShouldImplementGenericInterface()); | ||
} | ||
} | ||
} |
36 changes: 36 additions & 0 deletions
36
.../src/Tests/SonarAnalyzer.UnitTest/TestCases/CollectionsShouldImplementGenericInterface.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
using System; | ||
using System.Collections; | ||
using System.Collections.Generic; | ||
using System.Collections.ObjectModel; | ||
|
||
namespace Tests.Diagnostics | ||
{ | ||
class TestClass_01 : CollectionBase { } // Noncompliant {{Refactor this collection to implement 'System.Collections.ObjectModel.Collection<T>'.}} | ||
// ^^^^^^^^^^^^ | ||
class TestClass_02 : IList { } // Noncompliant {{Refactor this collection to implement 'System.Collections.Generic.IList<T>'.}} | ||
|
||
class TestClass_03 : IEnumerable { } // Noncompliant {{Refactor this collection to implement 'System.Collections.Generic.IEnumerable<T>'.}} | ||
|
||
class TestClass_04 : ICollection { } // Noncompliant {{Refactor this collection to implement 'System.Collections.Generic.ICollection<T>'.}} | ||
|
||
class TestClass_05 : IEnumerable, ICollection { } // Noncompliant {{Refactor this collection to implement 'System.Collections.Generic.IEnumerable<T>'.}} | ||
// Noncompliant@-1 {{Refactor this collection to implement 'System.Collections.Generic.ICollection<T>'.}} | ||
|
||
class TestClass_06 : IEnumerable, ICollection<string> { } | ||
class TestClass_07 : IEnumerable, IList<string> { } | ||
class TestClass_08 : IEnumerable, IEnumerable<string> { } | ||
class TestClass_09 : IEnumerable, Collection<string> { } | ||
class TestClass_10<T> : IEnumerable, IList<T> { } | ||
|
||
class TestClass_11<T> : IEnumerable, ICollection, ICollection<T> { } | ||
|
||
class TestClass_12 : IEnumerable, IList, IEnumerable<string> { } | ||
|
||
class TestClass_13 { } | ||
|
||
class TestClass_14 : Exception { } | ||
|
||
class TestClass_15 : IEqualityComparer { } | ||
|
||
class TestClass_16 : IList, InvalidType { } // Noncompliant | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I was thinking about making this rule to report only once per class and put the additional base classes and interfaces as secondary locations. But then I realized that you should probably report only once anyway, because if you implement at least one generic interface/class the rule will not report anymore. What will happen with FxCop if you have a class like this? How many reports are we going to get? What interface do they suggest in this case?