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.)
Related
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.
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.
At the moment my Form1 code is extremely heavy, mainly full of menu and control events. One thing I would like to do is organize it in some way, so I could expand or collapse "related code" (in Visual Studio).
My first attempt at this was to put code relating to the main menu, for example, inside a nested class called "MainMenu", which was within the Form1 class, so that I could simply collapse the nested class when I don't need it. This resulted in all sorts of problems (i.e. I couldn't find a way to set up the main menu inside this nested class).
Is there a simpler solution to this that I'm missing? Or can someone shed some light on why my nested class idea is faulty?
While #testalino's answer certainly does what you ask for, I would say that your real problem is probably related to code design. Chances are that the form class simply contains more code than it should, and that some of it ought to move into other classes.
If done in a good way, this might give you some benefits:
You will likely get more encapsulated (and less coupled) behavior, when various functions operates on data passed to the methods through parameters and return values instead of fetching and setting values directly in UI controls.
You might get a more testable code base (you do have unit tests, right?).
It will be easier for several persons to collaborate on the code, since the code is spread across several different code files. This reduces merging conflicts (you do have a source control system, right?). This point may not be as applicable if you are working on something alone, but it doesn't hurt to have this habit anyway.
You can use #region and #endregion to organize code within a class. These regions are then collapseable.
I suggest you using User Controls to encapsulate some of Form's behavior. This is the simplest solution available for you right now, I guess. You just pick some piece of user interface and extract it to user control and define some public properties accessible from the form.
Keeping all handlers in Form.cs is a bad, bad practice. You must avoid it because it's unmaintanable (I've seen much code like that, and at later stages adding or changing functionality is proven to be impossible without breaking anything, let alone changing the UI without affecting the way app works).
In future, you may want to try different approaches to separation UI from application logic, e.g. explore MVP/MVC patterns.
If your form has become so big and complex that you suddenly desire to organize it in some way it is a strong hint towards the need of refactoring, which will improve readability, testability and maintainablity of your code. How you actually refactor depends upon your actual code.
Is it a form that has a lot of controls? Think about splitting it up in separate UserControls where each of them displays a certain aspect of your domain data. Do you have a lot of interaction logic, reacting to a lot of events? Maybe introduce a some sort of Controller or EventAggregator.
There are a lot of well known patterns that can help you organize your UI and domain code. This series talks about just that and introduces you to patterns MVC, MVP, EventAggregator and much more. It discusses the patterns in the context of windows forms just as you need it.
Use the partial class keyword in order to split your class into several files.
I agree with what the other answers say about grouping alike event handlers together in #regions is solid given a massive number of events. In addition, if the code itself in the handlers is voluminous as well, you might want to think of refactoring those into logical business logic classes. Example:
pseudocode before:
private void SomeButton_Click(...)
{
using (FileStream fs = ...)
{
fs.Write(some form data);
fs.Write(some more form data);
}
DoMoreBusinessLogicStuff();
...
// lots more stuff
...
}
pseudocode after:
private void SomeButton_Click(...)
{
IBusinessObject obj = new BusinessObject(injectable form data);
using (IPersistence store = new FilePersistence(...))
{
obj.Persist(store);
}
obj.DoBusinessRules();
}
This should move business, persistence and support logic to their own classes and leave your event handlers as lightweight shells designed only to gather UI input and pass it along.
Nested classes are generally frowned upon as being only a slight upgrade from god-classes for one thing, and encapsulation and code reuse being pretty murky.
You should be aiming to express the objects you actually have as individual business classes within your code: one class, one file. Is there any particular reason you aren't doing this?
Depending on the type of code it is doing will depend on where you can move it.
If its processing data code then you can move this out into separate classes in a different namespace returning the processed data to controls to allow for data binding etc.
If Form1 is getting very heavy with code then is this because you've got too much going on in Form1? Could you break it out into a different/new form?
You could use the summary which is collapsible but I think this is more intended for providing other developers with information, always good practice though!
In VB:
''' <summary>
'''
''' </summary>
''' <remarks></remarks>
In C#
/// <summary>
///
/// </summary>
/// <remarks></remarks>
When writing GUI apps I use a top level class that "controls" or "coordinates" the application. The top level class would be responsible for coordinating things like initialising network connections, handling application wide UI actions, loading configuration files etc.
At certain stages in the GUI app control is handed off to a different class, for example the main control swaps from the login screen to the data entry screen once the user authenticates. The different classes need to use functionality of objects owned by the top level control. In the past I would simply pass the objects to the subordinate controls or create an interface. Lately I have changed to passing method delegates instead of whole objects with the two main reasons being:
It's a lot easier to mock a method than a class when unit testing,
It makes the code more readable by documenting in the class constructor exactly which methods subordinate classes are using.
Some simplified example code is below:
delegate bool LoginDelegate(string username, string password);
delegate void UpdateDataDelegate(BizData data);
delegate void PrintDataDelegate(BizData data);
class MainScreen {
private MyNetwork m_network;
private MyPrinter m_printer;
private LoginScreen m_loginScreen;
private DataEntryScreen m_dataEntryScreen;
public MainScreen() {
m_network = new Network();
m_printer = new Printer();
m_loginScreen = new LoginScreen(m_network.Login);
m_dataEntryScreen = new DataEntryScreen(m_network.Update, m_printer.Print);
}
}
class LoginScreen {
LoginDelegate Login_External;
public LoginScreen(LoginDelegate login) {
Login_External = login
}
}
class DataEntryScreen {
UpdateDataDelegate UpdateData_External;
PrintDataDelegate PrintData_External;
public DataEntryScreen(UpdateDataDelegate updateData, PrintDataDelegate printData) {
UpdateData_External = updateData;
PrintData_External = printData;
}
}
My question is that while I prefer this approach and it makes good sense to me how is the next developer that comes along going to find it? In sample and open source C# code interfaces are the preferred approach for decoupling whereas this approach of using delegates leans more towards functional programming. Am I likely to get the subsequent developers swearing under their breath for what is to them a counter-intuitive approach?
It's an interesting approach. You may want to pay attention to two things:
Like Philip mentioned, when you have a lot of methods to define, you will end up with a big constructor. This will cause deep coupling between classes. One more or one less delegate will require everyone to modify the signature. You should consider making them public properties and using some DI framework.
Breaking down the implementation to the method level can be too granular sometimes. With class/interface, you can group methods by the domain/functionality. If you replace them with delegates, they can be mixed up and become difficult to read/maintain.
It seems the number of delegates is an important factor here.
While I can certainly see the positive side of using delegates rather than an interface, I have to disagree with both of your bullet points:
"It's a lot easier to mock a method than a class when unit testing". Most mock frameworks for c# are built around the idea of mocking a type. While many can mock methods, the samples and documentation (and focus) are normally around types. Mocking an interface with one method is just as easy or easier to mock than a method.
"It makes the code more readable by documenting in the class constructor exactly which methods subordinate classes are using." Also has it's cons - once a class needs multiple methods, the constructors get large; and once a subordinate class needs a new property or method, rather than just modifying the interface you must also add it to allthe class constructors up the chain.
I'm not saying this is a bad approach by any means - passing functions rather than types does clearly state what you are doing and can reduce your object model complexity. However, in c# your next developer will probably see this as odd or confusing (depending on skill level). Mixing bits of OO and Functional approaches will probably get a raised eyebrow at the very least from most developers you will work with.
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.