Skip to content
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

Automatic fix for IDE0072 is changing code behaviour #2219

Open
jakoss opened this issue Nov 21, 2024 · 0 comments
Open

Automatic fix for IDE0072 is changing code behaviour #2219

jakoss opened this issue Nov 21, 2024 · 0 comments

Comments

@jakoss
Copy link

jakoss commented Nov 21, 2024

I might be in a minority for that, but i think dotnet format should not populate missing switch branches with throw new NotImplementedException(). Scenario:

I had this code in codebase:

query = tasksSortBy switch
{
    TasksSortBy.Name => query.OrderBy(e => e.Name),
    TasksSortBy.Completed => query.OrderBy(e => e.Completed),
    _ => query.OrderBy(e => e.CreatedAt)
};

Even though there is TasksSortBy.Unspecified - this code is just fine, since we have the wildcard _ in the place to handle it. But i still want to keep the diagnostic to avoid missing enum values that are "real". So the diagnostic is fine, maybe Unspecified is too much (but it's a good practise from gRPC protocol, so we are using it there). My issue is with the automatic fix. After running the dotnet format i ended up with:

query = tasksSortBy switch
{
    TasksSortBy.Name => query.OrderBy(e => e.Name),
    TasksSortBy.Completed => query.OrderBy(e => e.Completed),
    TasksSortBy.Unspecified => throw new NotImplementedExcetion(),
    _ => query.OrderBy(e => e.CreatedAt)
};

which for me it is outright dangerous. Fortunately for us - the integration test suite quickly caught the issue in CI pipeline, but the developer did not check the code after running the dotnet format (which is understandable, it should be just format). In this case format command changed the code behaviour. I'm opening this thread to figure out if more people think like me here :).

To be clear - the "solution" isn't that clear either, but from my perspective it would be better if dotnet format left the code "uncompilable" at this point. So:

query = tasksSortBy switch
{
    TasksSortBy.Name => query.OrderBy(e => e.Name),
    TasksSortBy.Completed => query.OrderBy(e => e.Completed),
    TasksSortBy.Unspecified => // TODO : implement that
    _ => query.OrderBy(e => e.CreatedAt)
};

is much better, since it's forcing the developer to implement the missing branch. What do you all think about that?

@jakoss jakoss changed the title Automatic fix for IDE0072 is wrong Automatic fix for IDE0072 is changing code behaviour Nov 21, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant