What's the best way to layout a C# class? [duplicate] - c#

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.

Related

What exactly is encapsulation?

My teacher told me that encapsulation is data/information hiding.
But what I understand from here is that Encapsulation is bundling data and methods that act on that data into one unit. And that [encapsulation] allows us to create information hiding mechanisms. Like, making a variable read-only, or making it accessible through some checkpoints.
Am I right that encapsulation in itself is not data hiding, but a way through which we can hide data?
There is no authoritative source that can tell you with full confidence. You (we all) have to ask unfortunately every time it comes up what exactly the speaker/writer means.
Most of the time is encapsulation a little bit more than information hiding.
Encapsulation is a bit more abstract, and may refer to not just data, but logic or any knowledge in general.
Data hiding is just that (normally), hiding the data (the instance variables).
How these things get implemented is a source of even more debate! For example some (if not most) people refer to data hiding when instance variables are simply declared private. Even if there is a public getter for that same data! (the linked article seem to support this position)
Again for others (myself included) calling data hidden when there is a public getter for it sounds strange to say the least.
Some people insist that getters are ok (the data hiding applies) if the returned data is immutable, since it can not be changed.
Encapsulation is often used together with logic. For example: I encapsulate how to send emails in this class, etc.
The problem is, everyone uses the same words, so it's nigh impossible to tell what someone really means by either of these things. If you want to know what someone is talking about, always demand an example (or two).
I will give an explanation to encapsulation and data hiding as I understood from code complete book
When you create a class/method the primary goal is to reduce complexity of your program. You create a class/method to hide information so that you won’t need to think about it. Sure, you’ll need to think about it when you write the class/method. But after it’s written, you should be able to forget the details and use the class/method without any knowledge of its internal workings.
So each class/method should ask a question "What should I hide in order to reduce complexity?" and hence you start to create the interface that this class/method provides to the outside world (other classes/methods). This consists of creating a good abstraction for the interface to represent and ensuring that the details remain hidden behind the abstraction.
Abstraction helps to manage complexity by providing models that allow you to ignore implementation details. Encapsulation is the enforcer that prevents you from looking at the details even if you want to. If I declare a method as private, I'm forcing that it should be used only inside the class and not from outside and if I declare it as public I'm saying that it is part of the interface this class is providing and it can be used from outside. The two concepts are related because, without encapsulation, abstraction tends to break down.
It means you can't mess with the other object's innards unless that object lets you. It is encapsulated, in a capsule you can't get into. An artifact of this is hiding information. If you are closed up, and only you can open things up, then you've pretty much hidden everything inside of yourself. Thus, the hiding is a consequence of encapsulating.
Think of a Birthday class that takes in a Birthdate (DateTime) in the constructor.
It has properties the following that are filled
Public Property _ZodiacSign As String = String.Empty
Public Property _ChineseZodiac As String = String.Empty
Public Property _ChineseZodiacChar As String = String.Empty
Public Property _is21AndOver As Boolean
Public Property _ChineseDate As String
Public Property _EstimatesConvievedDate As DateTime
You have no idea what the logic is to figure out the zodiac sign or chinesezodiac or are they over 21, it is a black box.

How to keep track and manipulate a variable using multiple classes - c#

i am building a sort of program that generates a random list of word according to a database.
I Made a class that deals with the word selecting and handling (a random select function, a connect to the database function etc..)
I have 3 variables that indicate the last 3 words chosen.
how do I use a funcion on the form1 (button 1 press), to manipulate the same 3 variables, without creating them from scratch everytime (what happens now...)
To make myself clearer:
accualy what I need is to know how to keep track of a variable between multiple classes.
I might be using the whole classes thing wrong... I am now triyng to get the grasp of it.
Thank you very much,
Barak.
Your two options as I see it are:
1) an instance of a class that holds those variables that can be passed around
You may want to use the singleton pattern for this class if you want to make sure there is only ever one of them.
2) A static class with static members holding this information.
It may be that your entire random word class could be static. In this case you'd just call the methods and properties on that class to generate and access your words.
Also I would suggest that you may want to consider a collection to hold your words rather than three separate variables. It will of course depend on your implementation so I will mention it just inc ase you haven't thought of it and I'm not saying you definitely should. :)
I would avoid static or Singletons just for this purpose - they're not good habits to pick up for simple object oriented scenarios.
Encapsulate the state variables in a class, which you instantiate first, then pass by reference into the form and/or data fetch logic.
Key to this is understanding the concept of reference - your form and fetch logic will see the same instance of your state class, effectively sharing it.
If you implement the "variables" as properties on the state class, you can use events to notify other parts of your code when the word states change.
Consider also clearly defining the possible interactions (interfaces) on the state class. One aspect seems to be to add a word, another to pull out statistics based on the added words. The state class can accommodate all this, and provide a nice place for future extensions.
Try to think in terms of public interface methods/properties, while keeping "variables" (i.e. fields like counters or collections) private.
I also agree that your post should be improved with snippets of actual code - help us helping you.
And I hope your code is not being used to generate spam mails/posts... :-)

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;
}
}
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

When to use DebuggerDisplayAttribute

What are some best practices around the DebuggerDisplayAttribute? What guides your decisions on when and how to apply the attribute to your code? For example..
Do you find DebuggerDisplayAttribute more useful on some types of objects (i.e. custom data structures) rather than others?
Do you define it on public types, internal types, or both?
Will you generally add it to the initial implementation, or wait for a tester/user to request it?
When is it better to define DebuggerDisplayAttribute and when does it make more sense to override .ToString()?
Do you have guidelines on how much data you expose in the attribute, or limits on the amount of computation to include?
Do any inheritance rules apply that would make it more beneficial to apply on base classes?
Is there anything else to consider when deciding when or how to use it?
It's subjective and I'd hesitate to say there are any best practices, but:
Do you find DebuggerDisplayAttribute more useful on some types of objects (i.e. custom data structures) rather than others?
By far the most common use is types that represent business entities - and I'll commonly display ID + name. Also any types that will be stored in collections in the application.
Other than that I add it whenever I find myself frequently searching for properties in the debugger.
2.Do you define it on public types, internal types, or both?
Both.
3.Will you generally add it to the initial implementation, or wait for a tester/user to request it?
Testers/users won't ever see it - it's only used while debugging.
4.When is it better to define DebuggerDisplayAttribute and when does it make more sense to override .ToString()?
Override ToString() when you want the representation at runtime, either for logging or application-specific purposes. Use DebuggerDisplayAttribute if you only need it for debugging.
5.Do you have guidelines on how much data you expose in the attribute, or limits on the amount of computation to include?
As it's not used at runtime, the only constraint is that it should be fast enough not to impede the debugging experience (especially when called multiple times for elements of a collection).
You don't need to be concerned about exposing sensitive data as you would with runtime logging (e.g. by overriding .ToString), because such data will be visible anyway in the debugger.
6.Do any inheritance rules apply that would make it more beneficial to apply on base classes?
No, apply it on the classes you need it.
7.Is there anything else to consider when deciding when or how to use it?
Nothing else I can think of.
Debugging mode without DebuggerDisplay Attribute
Debugging mode with DebuggerDisplay Attribute
[DebuggerDisplay("{Name,nq}")]//nq suffix means no quotes
public class Product {
public int Id { get; set; }
public string Name { get; set; }
//Other members of Northwind.Product
}
DebuggerDisplay attribute best practices
Tell the debugger what to show using the DebuggerDisplay Attribute (C#, Visual Basic, F#, C++/CLI)
Debugger/Diagnostics Tips & Tricks in Visual Studio 2019
Although the attribute is quite old, you should watch the applause and the narrator's reaction :) By the way, if you want to see more debugger tricks, you might want to see this demo at your free time.
I use it a lot when I know that a code section will require a lot of debugging. It saves some time when browsing the objects in the debugger, especially if you are using expressions like "{ChildCollection.Count}". It gives you a quick idea of the data you are looking at.
I almost always put it on class that will end up in collections so that it is really quick to see each item and not just a bunch of MyNamespace.MyClass elements that you have to expand.
My opinion is that ToString() is used to provide an end-user representation of the data. DebuggerDisplay is for developers, you can decide to show the element ID, some additional internal/private properties.
DebuggerDisplay has value for any class which doesn't have a meaningful .ToString() implementation, but I personally haven't seen anyone proactively write the attributes until they are needed.
In general, Omer's link to best practices looks like sound advice; however I personally would lean away from the suggestion to have a dedicated DebuggerDisplay() method--even though it's private it seems to offer little benefit over the attribute aside from removing magic strings.

Semantic #region usage

What's your opinion about using #region folding using application semantic, instead of folding for "syntax".
For example:
#region Application Loop
#region User Management
#region This Kinf of stuffs
instead of
#region Private Routines
#region Public Properties
#region ThisRoutine // (Yes, I've seen this also!)
In this logic, I'm starting fold even routine bodies. I'm starting to love #region directive (even using #pragma region when using C++!).
That would suggest you're doing too much in one type - why would an "application loop" be in the same type as "user management"? If you find yourself wanting to do this, consider splitting the functionality into different types.
Typically I use regions for interface implementations, Equals/GetHashCode overrides, and operators - but that's usually all.
The only time I use a region is to hide something like a bunch of non-implemented interface methods or a bunch of code which is for the chop but I'm not quite ready to kill it.
I tend to think if it needs folding to help you keep track of it all there is too much code in the file (or maybe another general code smell [or is the folding the smell?]) and if it doesn't need folding the only thing folding will achieve is frustrating people who have to go looking for code which should be on display.
I'm not a fan of hiding code from myself.
I prefer dividing my code into regions based on syntax, because I can easily find the constructor, overridden methods and so on...
I use regions to group methods with a common/related purpose.
So, rather than public, protected, private regions, think of "Initialisation", "Load and save", "Event handlers", etc.
The purpose of this is for the folded class to act as a summary or overview of the functionality, and make it easy to find the parts you are looking for. Ideally, you will generally settle on a few standard region "types" that you use throughout your application's classes so that they are all consistently subdivided.
I've seen developers who do this in the past and the end result is rarely good. The problem is with the expectation that those who follow will understand the groupings and correctly identify the correct region for their additions. In my experience what tends to happen is that, at best, one ends up with a proliferation of new regions, one per each functional change and, at worst, new methods junked in any old place or regionless at the end of the class.
I'd say go with a scheme that is obvious. The most common is the 'Private Fields/ Public Fields / Private Properties / Private Methods / Public Properties / Public Methods' scheme. (Personally I favour grouping by visibility: 'Public / Internal / Private' with the more visible members at the top as that is what a casual visitor to a class is going to be interested in first and what goes where is still blindingly obvious.)

Categories

Resources