Question

I am designing an interface in a C# project which will be extended with various extension methods. Now I thought of putting the static class containing the extension methods in the same file as the interface itself.

I am not sure though if this is against the principle of 1 thing per file. I tend to think that this is related so closely that they can go into the same file. Yet I'd still like to hear the opinion of a more experienced developer.

In terms of maintainability, code readability and good structure, what would be the way to go here? I thought of something along the lines of:

public interface IFoo
{
    int Property { get; }
    void Method();
}

public static class IFooExtensions
{
    public static void AnExtension(this IFoo foo)
    {
        // Do Something
    }

    public static void AnotherExtension(this IFoo foo)
    {
        // Do Something else
    }
}

Where all of this would go into the same file. Thanks for any advice!

Was it helpful?

Solution

I find there are some practical exceptions to the "one thing per file" rule; interfaces are a common case. Perhaps you want a simple enum that's used only in the context of that interface, or you pair an interface with its implementation as mentioned by @jlew, or in your case, perhaps a couple of simple extension methods could go in the same file. But I would move them to a separate file if the implementations get to complicated.

However, remember that extension methods are made available by importing the namespace in which they are defined. So consider the typical usage of your extension method. Perhaps there is a different namespace that is associated with the specific context in which these extension methods will be used. But if these extension methods are general purpose, it would make sense to keep them in the same namespace as the interface itself, and perhaps in the same file.

OTHER TIPS

I think that's fine. Files are largely irrelevant if you use the code navigation abilities of Visual Studio and tools like ReSharper. I like to put closely-related things together (like simple interfaces and their one concrete implementation).

Go ahead with different file like interface should be in one file and the class should be in different file which will inherit the interface. If u do so u can use the interface for different classes to get the same signature. Change the class name, starting with 'I' for Interface.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top