简体   繁体   中英

Should I place every class in separate file?

Should I place every class in separate file? Even those short helper classes that are used only in one place? Like this one:

public class IntToVisibilityConverter : GenericValueConverter<int, Visibility>
{
    protected override Visibility Convert(int value)
    {
        return value == 0 ? Visibility.Collapsed : Visibility.Visible;
    }
}

我这样做,通常这样做是最佳做法,但有时这是一个见仁见智的问题。

That depends greatly of personal preference, but I like to do it.

In this case, I would have a folder inside my application called ValueConverters, and put all converters, including short ones, inside their own files.

I find it makes it easier to get an overview of what your project consist of from the Solution Explorer.

I'll rephrase the question for you: should I use StyleCop ? (it includes this rule). The answer is yes. I use it and my code is much more readable (but I have to admit I disable all the rules that require the method documentation to be complete :-) )

I do think that when you program in a team, having a fixed and uniform code format is very important. And even when you program "solo". A cluttered code is more difficult to read and errors can hide better in the clutter :-)

It is usually the best practise to put every class in a seperate file. Taking into account your short helper classes; you could create a helper class which contain all your helper methods, to prevent having way too many classes. If your helper class gets too big, you can seperate your helper functions per category

It is good practice to do so.

You can easily find the class if you name the file after the class.

Resharper has a built in error for classes not matching the file name they are in...

Typically, IMO yes. Think about any new developers who must find where code lives. Yes, you can use go to definition, but that is not the be all, end all. However, I will say that sometimes if you have an interface that is small and only used for the class that it is within, then you can probably get away with it. However, even that can expand and later be required to be pulled out (and maybe those contracts should be in another namespace anyways).

So, ultimately, I would say the majority of the time, yes, but there are some caveats. As with anything, it is never black and white

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM