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;
}
}
I do this and it is usually best practice to do so, but it is sometimes a matter of opinion.
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
Related
I have a legacy class that is rather complex to maintain:
class OldClass {
method1(arg1, arg2) {
... 200 lines of code ...
}
method2(arg1) {
... 200 lines of code ...
}
...
method20(arg1, arg2, arg3) {
... 200 lines of code ...
}
}
The methods are huge, unstructured, and repetitive (developer loved copy/paste aprroach). I want to split each method into 3-5 small functions, with one pulic method and several helpers.
What would you suggest? Several ideas come to my mind:
Add several private helper methods to each method and join them in #region (straight-forward refactoring)
Use Command pattern (one command class per OldClass method in a separate file).
Create helper static class per method with one public method & several private helper methods. OldClass methods delegate implementation to appropriate static class (very similiar to commands).
?
Thank you in advance!
SRP - Single Responsibilty principle and DRY - Don't Repeat yourself
I would start by finding the bits that are repetitive and extracting them into helper functions. Once you've narrowed the code base down in this way, you can consider other ways to refactor, and the code will be much easier to wrap your head around.
See SD CloneDR for a tool that can tell you what code blocks each of your methods have in common, including possible parameterizations.
DRY - Don't repeat yourself.
The first thing I always do is to remove (all) repetition. Even a single line is repetition.
That will normalise the code plus also give you a bunch of enhancements such as genericising the code.
Start by mapping the current functionality and making an UML class diagram. That way you can effectively achieve DRY.
Change the design to be effective and DRY, while still keeping the interface of your system as much the same as you can.
Then you write unit tests for the new system, it would be better to write them for the old system as wel, but since you are probably going to change method names and arguments, the unit tests probably cannot work on both systems.
Ask your manager feedback on the unit test, did you understood the functionality properly? Don't implement any new features, this will cause problems with existing systems using the code, and if you get the new design right adding new features
Implement the approved system.
Use default values as arguments to reduce overloading: SelectUser(int userId = 0) can be called with SelectUser();
I am entry level .Net developer and using it to develop web sites. I started with classic asp and last year jumped on the ship with a short C# book.
As I developed I learned more and started to see that coming from classic asp I always used C# like scripting language.
For example in my last project I needed to encode video on the webserver and wrote a code like
public class Encoder
{
Public static bool Encode(string videopath) {
...snip...
return true;
}
}
While searching samples related to my project I’ve seen people doing this
public class Encoder
{
Public static Encode(string videopath) {
EncodedVideo encoded = new EncodedVideo();
...snip...
encoded.EncodedVideoPath = outputFile;
encoded.Success = true;
...snip...
}
}
public class EncodedVideo
{
public string EncodedVideoPath { get; set; }
public bool Success { get; set; }
}
As I understand second example is more object oriented but I don’t see the point of using EncodedVideo object.
Am I doing something wrong? Does it really necessary to use this sort of code in a web app?
someone once explained OO to me as a a soda can.
A Soda can is an object, an object has many properties. And many methods. For example..
SodaCan.Drink();
SodaCan.Crush();
SocaCan.PourSomeForMyHomies();
etc...
The purpose of OO Design is theoretically to write a line of code once, and have abstraction between objects.
This means that Coder.Consume(SodaCan.contents); is relative to your question.
An encoded video is not the same thing as an encoder. An encoder returns an encoded video. and encoded video may use an encoder but they are two seperate objects. because they are two different entities serving different functions, they simply work together.
Much like me consuming a soda can does not mean that I am a soda can.
Neither example is really complete enough to evaluate. The second example seems to be more complex than the first, but without knowing how it will be used it's difficult to tell.
Object Oriented design is at it's best when it allows you to either:
1) Keep related information and/or functions together (instead of using parallel arrays or the like).
Or
2) Take advantage of inheritance and interface implementation.
Your second example MIGHT be keeping the data together better, if it returns the EncodedVideo object AND the success or failure of the method needs to be kept track of after the fact. In this case you would be replacing a combination of a boolean "success" variable and a path with a single object, clearly documenting the relation of the two pieces of data.
Another possibility not touched on by either example is using inheritance to better organize the encoding process. You could have a single base class that handles the "grunt work" of opening the file, copying the data, etc. and then inherit from that class for each different type of encoding you need to perform. In this case much of your code can be written directly against the base class, without needing to worry about what kind of encoding is actually being performed.
Actually the first looks better to me, but shouldn't return anything (or return an encoded video object).
Usually we assume methods complete successfully without exceptional errors - if exceptional errors are encountered, we throw an exception.
Object oriented programming is fundamentally about organization. You can program in an OO way even without an OO language like C#. By grouping related functions and data together, it is easier to deal with increasingly complex projects.
You aren't necessarily doing something wrong. The question of what paradigm works best is highly debatable and isn't likely to have a clear winner as there are so many different ways to measure "good" code,e.g. maintainable, scalable, performance, re-usable, modular, etc.
It isn't necessary, but it can be useful in some cases. Take a look at various MVC examples to see OO code. Generally, OO code has the advantage of being re-usable so that what was written for one application can be used for others over and over again. For example, look at log4net for example of a logging framework that many people use.
The way your structure an OO program--which objects you use and how you arrange them--really depends on many factors: the age of the project, the overall size of the project, complexity of the problem, and a bit for just personal taste.
The best advice I can think of that will wrap all the reasons for OO into one quick lesson is something I picked up learning design patterns: "Encapsulate the parts that change." The value of OO is to reuse elements that will be repeated without writing additional code. But obviously you only care to "wrap up" code into objects if it will actually be reused or modified in the future, thus you should figure out what is likely to change and make objects out of it.
In your example, the reason to use the second set up may be that you can reuse the EncodedVideo object else where in the program. Anytime you need to deal with EncodedVideo, you don't concern yourself with the "how do I encode and use video", you just use the object you have and trust it to handle the logic. It may also be valuable to encapsulate the encoding logic if it's complex, and likely to change. Then you isolate changes to just one place in the code, rather than many potential places where you might have used the object.
(Brief aside: The particular example you posted isn't valid C# code. In the second example, the static method has no return type, though I assume you meant to have it return the EncodedVideo object.)
This is a design question, so answer depends on what you need, meaning there's no right or wrong answer. First method is more simple, but in second case you incapsulate encoding logic in EncodedVideo class and you can easily change the logic (based on incoming video type, for instance) in your Encoder class.
I think the first example seems more simple, except I would avoid using statics whenever possible to increase testability.
public class Encoder
{
private string videoPath;
public Encoder(string videoPath) {
this.videoPath = videoPath;
}
public bool Encode() {
...snip...
return true;
}
}
Is OOP necessary? No.
Is OOP a good idea? Yes.
You're not necessarily doing something wrong. Maybe there's a better way, maybe not.
OOP, in general, promotes modularity, extensibility, and ease of maintenance. This goes for web applications, too.
In your specific Encoder/EncodedVideo example, I don't know if it makes sense to use two discrete objects to accomplish this task, because it depends on a lot of things.
For example, is the data stored in EncodedVideo only ever used within the Encode() method? Then it might not make sense to use a separate object.
However, if other parts of the application need to know some of the information that's in EncodedVideo, such as the path or whether the status is successful, then it's good to have an EncodedVideo object that can be passed around in the rest of the application. In this case, Encode() could return an object of type EncodedVideo rather than a bool, making that data available to the rest of your app.
Unless you want to reuse the EncodedVideo class for something else, then (from what code you've given) I think your method is perfectly acceptable for this task. Unless there's unrelated functionality in EncodedVideo and the Encoder classes or it forms a massive lump of code that should be split down, then you're not really lowering the cohesion of your classes, which is fine. Assuming you don't need to reuse EncodedVideo and the classes are cohesive, by splitting them you're probably creating unnecessary classes and increasing coupling.
Remember: 1. the OO philosophy can be quite subjective and there's no single right answer, 2. you can always refactor later :p
Out of habit I tend to put classes/structs/enumerations in separate files when not nested.
For delegates, it seems like overkill to create a seperate file for a one liner:
public delegate string MyDelegateThatIsNotNestedInAnyClass ( string par );
I usually add it to the bottom of the most closely related class file. I was just wondering what other people do?
I tend to put each type in a separate code file. Doing so will help you navigate in Solution Explorer, though ReSharper rocks with "Go To File"
(source: jetbrains.com)
and "Go To Type":
(source: jetbrains.com)
I usually add it to the .cs file of the class which implements the delegate function (at the namespace level). If there are several of these, I put it in a separate file.
If I know for sure that only one class will implement the delegate function, I nest it in the implementing class.
I personally add it before a closely related class definition. I make good use of namespaces, though, so I don't pollute!
If it's closely related enough to belong in the same file as the class, then you can probably justify nesting it in the class. Then you'll have no trouble remembering which class file it's in.
If there's no single class that's an obvious choice to nest in, creating the one-line file is probably worthwhile since you'll never waste time trying to remember which class file you decided to put it in.
I allways declare my own events, even if I don´t need them in the sence that a generic event would suffice. The reason for that is that the class name of the event gives the code so much more readability and also not seldom the declared event will be needed further down the road for some reason.
Since I have an event class, I allways put the delegate above the class declaration of the event. They are closely coupled and if you need to listen to the event then you´ll need both the event and the delegate. I don´t know if this violates some design rules of any kind, but this has worked nicely for me.
Usually, I just use:
Func<string, string>
these days
I'm not too quite sure about what i should do about a grouped set of classes.
My situation: I have 11 classes that relate only to the class Character.cs, but all of those classes (including Character.cs and CharacterManager.cs) are within the namespace Models.Characters.
Which is the more "proper" or preferred way of naming the classes:
(examples):
CharacterDetails.cs
CharacterSprites
CharacterAppearance
CharacterClientRights
CharacterServerRights
or:
Details.cs
Sprites
Appearance
ClientRights
ServerRights
(They're all noticed in Models.Characters (so eg. Models.Characters.CharacterDetails, Models.Characters.Appearance)
Thanks in advance.
Personally for me it"depends". Usually I would prefix everything with the word Character to keep things consistant, however if you have everything already under the Character namespace the Character prefix could seem redundant.
I could easily see going with the shorter convention of Models.Character.[X] if there never will be another class called Details, if there for instance could be UserDetails then Details and UserDetails could be confusing when looking back at the code weeks or months from now and I would personally prefer then the CharacterDetails option.
In the end it is your personal preference, what more accurately describes your domain, Details or CharacterDetails?
Personally I'd stick with the second method as that is what namespaces are for: grouping related sets of classes. The first method is just making the class names longer with negligible benefits.
Your namespace already is grouping its classes under the Characters umbrella, so I would not name your classes with the Character moniker.
There is probably no right or wrong answer here. I find myself prefering your first style, but I have used the second style as well. I think in this specific situation if I were a caller of your API I would find it easier to read code that used the first style.
It is really a personal preference.
I would favor
CharacterDetails
CharacterSprites
CharacterAppearance
CharacterClientRights
CharacterServerRights
Because it is more readable.
You are typically going to have a using statement of
Models.Characters.Appearance
Unless you are going to do the full notation.
I would favor anything that would increase readability. It might matter on the project and the team you are working with. If it is just you than do what you like best and would help you maintain the code in the future.
As long as you pick one and consistantly use that throughtout your code, then whichever one you choose is the right one.
My personal choice is your second option. If your namespace is character, I see no reason to use the prefix character in the class name.
Think about ambiguity that may be created by naming class. For example if I have a class called "Thread" denoting "CharacterThread" (hypothetical) and if some other class uses two namespaces
Models.Characters
System.Diagnostics
I will have to fully qualify the Thread name everytime I use it ... which can be a pain sometimes
This question already has answers here:
Order of items in classes: Fields, Properties, Constructors, Methods
(16 answers)
Closed 9 years ago.
Is there a standard way of laying out a C# file? As in, Fields, then Properties, then Constructors, etc?
Here's what I normally do, but I'm wondering if there's a standard way?
Nested Classes or Enums
Fields
Properties
Events
Constructors
Public Methods
Private Methods
Do people group their fields together, or do they put them with the properties? Or do people not worry about an order? Visual Studio seems to make it so hard to do.
Edit: Moved other part about ReSharper here: Make Resharper respect your preference for code order.
I tend to use Microsoft StyleCop, which has a set order according to rule SA1201:
Cause An element within a C# code
file is out of order in relation to
the other elements in the code.
Rule Description A violation of this
rule occurs when the code elements
within a file do not follow a standard
ordering scheme.
To comply with this rule, elements at
the file root level or within a
namespace must be positioned in the
following order:
Extern Alias Directives
Using Directives
Namespaces
Delegates
Enums
Interfaces
Structs
Classes
Within a class, struct, or interface,
elements must be positioned in the
following order:
Fields
Constructors
Finalizers (Destructors)
Delegates
Events
Enums
Interfaces
Properties
Indexers
Methods
Structs
Classes
Complying with a standard ordering
scheme based on element type can
increase the readability and
maintainability of the file and
encourage code reuse.
When implementing an interface, it is
sometimes desirable to group all
members of the interface next to one
another. This will sometimes require
violating this rule, if the interface
contains elements of different types.
This problem can be solved through the
use of partial classes.
Add the partial attribute to the class, if the class is not already
partial.
Add a second partial class with the same name. It is possible to place
this in the same file, just below the
original class, or within a second
file.
Move the interface inheritance and all members of the interface
implementation to the second part of
the class.
I think there's no best way. There are two important things to consider when it comes to layout. The first most important thing is consistency. Pick an approach and make sure that the entire team agrees and applies the layout. Secondly, if your class gets big enough that you are searching for where those pesky properties live (or have to implement regions to make them easier to find), then your class is probably too large. Consider sniffing it, and refactoring based on what you smell.
To answer the reshaper question, check under Type Members Layout in Options (under the C# node). It's not simple, but it is possible to change the layout order.
I don't believe regions are necessarily a sign of bad code. But to determine that you will have to review what you have. As I've stated here this is how I regionize my code.
Enumerations
Declarations
Constructors
Methods
Event Handlers
Properties
But the main thing is keeping it consistent and purposeful.
I tend to clump private data and tend to clump related methods/properties in functional groups.
public class Whatever {
// private data here
int _someVal = kSomeConstant;
// constructor(s)
public Whatever() { }
#region FabulousTrick // sometimes regionize it
// fabulous trick code
private int SupportMethodOne() { }
private double SupportMethodTwo() { }
public void PerformFabulousTrick(Dog spot) {
int herrings = SupportMethodOne();
double pieces = SupportMethodTwo();
// etc
}
#endregion FabulousTrick
// etc
}
You can try Regionerate to help with this. I really like it and it's a Scott Hanselman pick.
As said, I don't think there is a best way as such. But some organisation does help you the programmer.
How often in a long project have you spent time going up and down one or more source files trying to find one of your functions.
So I make use of the #region a lot to in this sort of way -
region Events : All of the event references that this class uses (at least in this particular partial class).
region Controls : All functions that directly interact with controls on a form.
region MDI : set the mdi up
Then there will be some to do with functionality rather than interface,
region Regex searches
I sort of make it up as I go along, but using the same pattern I always use. I must say I have been told by some programmers picking up my work that it is easy to follow and others that its messy.
You can please half the people half the time and the other half a quarter of the time and the other quarter of the time you confuse everyone including yourself. I think Winston Chrchil said that.
Whatever makes your more productive. Some like private fields next to property accessors, some like fields together above the constructors. The biggest thing that can help is grouping "like," elements. I personally like bringing together private methods, private properties, etc.
Try some things out and again, whatever you feel makes you more productive and helps you keep your code maintained.
Each to their own, but I tend to follow the same order that the MSDN help follows.
I also don't like to nest classes or enums, instead create separate files for them, that also makes writing unit tests easier (since it's easy to find the associated test file when you need to add/fix/refactor a test).
IMHO the order isn't that important because VS makes it very easy to find all members (especially if you follow the one class/interface/enum per file approach), and Sandcastle will group them if you want to build docs, so I'd be more concerned about giving them meaningful names.
On top of keeping a consistent set of regions in your class files, I keep all components of a region in alphabetical order. I tend to have a bit of "visual memory" when it comes to reading code and it drives me crazy having to use the navigation dropdown to find code in a file because it's all over the place.
I use the following layout:
events
globals/class-wide fields
private/internal
properties
methods
public/protected
properties
methods
nested classes (although I try to avoid these whenever possible)
I also firmly believe in 1 code "thing" (class, interface, or enum) per file, with the file name the same as the "thing" name. Yes, it makes a larger project but it makes it infinately easier to find things.