order of public/private members/functions style? [closed] - c#

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Is there a standard or accepted code style for whether public or private members / functions come first in a class?
I expected to find a lot on Google regarding this but have found nothing.

Take a look at this SO question. It has the StyleCop Rules Documentation's requirements.
Fairly well used standard.
ASIDE: There is a free plugin for C#. Makes following the rules much simpler when you know what you are doing wrong. It will tell you if you violate the rules and can be set to run during the build step.

There are ordering rules with StyleCop which are useful to follow as a point of standardisation.

No this is simply a matter of personal preferences. Just follow your company one if that applies.

As people are saying, the order generally doesn't matter. However, there is one important exception, and that's initializing static fields. You can initialize static fields based on the value of other static fields - it all ends up getting compiled into the static constructor, but in the order that it's written in the code.
For example:
class Program {
private static int j = 4;
private static int i = Program.j;
static void Main(string[] args) {
Console.WriteLine(Program.i); // 4
}
}
But:
class Program {
private static int i = Program.j;
private static int j = 4;
static void Main(string[] args) {
Console.WriteLine(Program.i); // 0
}
}
So keep this case in mind if you decide to re-shuffle your members around. To be totally safe, you can put the initializations in the static constructor, like:
class Program {
private static int i;
private static int j;
static Program() {
Program.j = 4;
Program.i = Program.j;
}
}

There are rules enforced by StyleCop that I have seen many people use as a standard.
Frankly, they make sense1, but I don't think it's the best way.
I think things should be grouped by functionality, not by type, or accessibility, or static, etc. I would argue that a scheme that is organized by functionality requires the least amount of navigation when trying to read or maintain a code base. Any other ordering scheme (or *rules) would leave you navigating all over the class as you try to work with it. A conceptual ordering that places things together that make sense will minimize that jumping around. It's about making it easier to understand and work with it. It's a practical perspective, rather than forming rules for the sake of having rules that can be enforced.
1: They make sense in that they are a rule, they appeal to the OCD among us, and they can be enforced by a machine, but who cares if the machine can enforce them? But code is not for the machine, it is for the humans. When I need to understand the code, I don't think to myself "if only I could first understand all the constant fields, and then all the fields, etc." I take a very different approach. I want to see the big picture first, and one thing that is going to assist with that is seeing the code organized by functionality.

Here is the Microsoft C# Coding Conventions (C# Programming Guide)
It makes no mention of ordering for public, protected or private functions or members in a class.
I know in my past experience that FxCop had "suggested" that I put my public functions before my private functions, but again not necessarily a standard.

Related

Guaranteeing immutability in c# [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
After reading a lot about immutability in C#, and understading it's benefits (no side effects, safe dictionary keys, multithreading...) a question has come to my mind:
Why there is not a keyword in C# for asserting that a class (or struct) is immutable? This keyword should check at compile time that there is no way you can mutate the class (or struct). For example:
public immutable class MyImmutableClass
{
public readonly string field;
public string field2; //This would be a compile time error
public readonly AnyMutableType field3; //This would be a compile time error
public string Prop { get; }
public string Prop2 { get; set; } //This would be a compile time error
public AnyMutableType Prop3 { get; } //This would be a compile time error
}
I think the compiler work would be quite easy, as it would need to check just a few things:
All public fields are readonly.
All public properties only have getters.
All public fields or properties have immutable types as well (simple value types, or immutable classes/structs).
All public functions or public property getters only depend on immutable fields or properties (public fields/props as described before, or private fields/props which comply to the same restrictions). This of course includes Equals(), GetHashCode() and ToString().
Some possible problems come to my mind with this design:
For the compiler to know that a compiled class/struct is immutable, it would probably be necesary to make changes in the intermediate language.
Readonly generic collection (such as IEnumerable<T>) immutability would depend on the immutability of the type <T>. The proposed immutable keyword would not be useful in this context, as you could not declare that IEnumerable<string> is immutable, even though it is.
Are the reasons stated before enough for this keyword to not exist?
Am I missing any other drawbacks?
Is this just not necessary enough for such big changes in the language?
The short version would be: because nobody has proposed, spec'd, designed, implemented, tested, documented, translated and supported that feature.
The longer version would relate to why to do it, given that it can be achieved indirectly with the readonly field - what benefit would it add.
For classes, it turns out to be relatively minor. Note that there is an [ImmutableObject(true)] attribute that can be used, but no features or frameworks really have a use for it, so ... nobody uses it.
There was a proposal to add "readonly structs" in a future version of C# (related to ref locals, Span<T>, etc) - but: it died a death and evaporated. However, the ref readonly stuff lives on, which is intended to prevent reassignment of this in struct instance methods.

Naming conventions in C# - Global Variables [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I know there is a debate/opinion about using this keyword or underscore in regards to private fields/properties (and I'll mention, I'm stuck on .NET 2.0)
Personally, I prefer this, but there are times you can't use it, for example when you need to reference a global variable from within a static method. Well, then we are forced to use the underscore (assuming we only have 2 choices, this or underscore). This means if my class uses any static methods I can't use this throughout the document.
Now, I've read the naming guidelines and used StyleCop, both would rather I don't use the underscore, but my Resharper pretty much insists on using _.
I don't feel it is right to have one class use the _ and the next class use this simply to accommodate for when the classes mixes non-static and static methods! The advice here on SO is to keep to one implementation/style but I don't know if that means I should ignore Microsoft (and I know MS don't always follow their own rules)!
It has been suggested to prefix with something else, similarish to Hungarian but prefix with globVariableName where glob indicates global. I hate this idea, it's too bespoke and won't be obvious to any other developer outside my team.
So, my question is, what is the best way to define global variables consistently? Since they are naming guides, may be I can just ignore (at least _ can be used consistently but it feels wrong to ignore the advice from the language creators).
Just use the class name in the same way you'd use "this", in a static class. Example follows:
public static class MyStatic
{
public static object Global;
public static void SomeMethod()
{
var theGlobal = MyStatic.Global;
}
}
public class MyNonStatic
{
public object Global;
public void SomeMethod()
{
var theGlobal = this.Global;
}
}
Note: I can't actually think of any other way to do it.
By global variables, I assume you mean const or static fields
I thing StyleCop used to encourage you to use ClassName.staticField for static and const fields, but it seems to have dropped that rule, at least by default. That is still a nice way to do it though.
Also, you can configure Resharper to play nicely with StyleCop.
I always use underscore for both static and instance variables.
For instance variables i use this.variable
For static variables i , sometimes, prefix them with the name of class, e.g., ClassName.variable
this is just my personal opinion;
I believe using this for every private variable is very useful; it has a positive effect on readability of the code. Also, when you are employing some DI constructor injection method, it enables you to use same variable without any confusion, which seems very proper.
public void SomeMethod(int someVariable)
{
this.someVariable = someVariable;
}
I prefer this instead of underscore; underscore seems pretty at first glance; but refering to the previous examples it has negative effect on readability.
I name static variables with the same way I name class variables; usage of this keyword lowers the risk of confusion between private and static variables.

What are the naming conventions in C#? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
There are a few questions on this, but they all seemed to be targeting a specific part of the language;
What are the most common naming conventions in C#? - Asking specifically about getters/setters.
C# naming conventions for acronyms - Asking more specifically about short uppercase suffixes.
I'm just starting out in C# with a friend on a venture to create games for XBOX Live Arcade. I've developed a number of games using ActionScript 2 and 3 but want to start exploring more powerful languages and devices.
I want to ensure that I don't peeve people that I start working with (if I get to that) or even just people on here when I run into trouble and ask a question with seriously disturbing / "incorrect" naming of methods, etc.
I've found it confusing in the example code that I've seen because there seems to be from my current point of view some flaws. I doubt that a flawed naming convention would be used, so I realize that I'm just having trouble understanding.
As far as I can tell so far, there are these conventions:
public Type SomeMethod()
private Type SomeMethod() - no underscore or anything?
public static Type SomeMethod()
private static Type _SomeMethod() - this one just seems odd..
public Type someProperty - switching it up to camel casing for properties?
public static Type SomeProperty - and then going back to pascal casing for static..
In ActionScript 3, I have developed and strictly stick to these conventions:
private var _someVar
public var someVar
private function _someMethod()
public function someMethod()
public static var SomeStaticVar
public static function SomeStaticMethod()
public const SOME_CONSTANT
Is there a complete list of naming conventions with reasoning behind each so that I can get my head around them? The reversal of syntax (i.e. public Type method() instead of AS3's public function method():Type) is throwing me out enough at the moment that I know I need to keep an eye on how I'm naming things, otherwise I'll forget and develop bad habits, which I'd rather nail and avoid now.
The two main Capitalizations are called camelCase and PascalCase.
The basic rules (with lots of variations) are
Types use PascalCase
properties and methods always use PascalCase
public members (fields, consts) use PascalCase
local variables use camelCase
parameters use camelCase
And although the documentation states that "Internal and private fields are not covered by guidelines" there are some clear conventions:
private fields use camelCase
private fields that back a property prefix a _
There is the All-In-One Code Framework Coding Standards from Microsoft which contains a complete set of rules and guidelines. (also used to be available here)
This document describes the coding style guideline for native C++ and .NET (C# and VB.NET) programming used by the Microsoft All-In-One Code Framework project team.
There are a whole lot of naming conventions advocated by Microsoft for .Net programming. You can read about these here.
As a rule of thumb, use PascalCase for public property, method and type name.
For parameters and local variables, use camelCase.
For private fields, choose one: some use camelCase, other prefix _camelCase with an _.
A commonly seen convention is also to name constants with ALLCAPS.
C# prefers PascalCasing for classes, properties, and methods.
As far as I can tell so far, there are these conventions:
public Type SomeMethod() <-- yes
private Type SomeMethod() <-- correct, no underscore
public static Type SomeMethod() <-- correct
private static Type _SomeMethod() <-- this seems odd to me too. underscore should not be there
public Type someProperty <-- no, a public property should be PascalCased (SomeProperty)
public static Type SomeProperty - and then going back to pascal casing for static..
If you are using Visual Studio, or XNA Game Studio (which I think is a fork of Visual Studio), I highly recommend springing for a ReSharper license (from jetbrains software). They will tell you, in your code editor, how to conform to common C# conventions.
Addition:
You should use camelCasing for private fields and method arguments. For private fields, I usually prepend them _withAnUnderscore.

What are the best practices for nested objects in .Net? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
This question has to do with best practices... please do not confuse it with premature optimization.
I noticed in .Net that deep object referencing takes quite some time to process when compared to flat or shallow objects. For example:
object1.object2.object3.object4.Property
... is not efficient since, I conclude, each object has to be de-referenced along the path. This is in contrast to C, where Property's memory ref would be calculated by the compiler, rather than at run time.
Now, we obviously wouldn't take all the fields of object2+ and flatten them into object1 just for speed. The coding would be unwieldy and hard to manage. But the speed difference could be significant.
So my question is, "What is the best practice in building deep objects vs. flat(ish) objects?" And, further, is there any advantage to using structs where one is simply trying to group a number of fields together, such as:
public struct SizeData
{
public long Written;
public long Read;
public int Size;
}
The two questions relate.
EDIT
To illustrate:
public class Leaf
{
public int Property;
}
public class Depth1
{
public Leaf Leaf;
}
public class Depth2
{
public Depth1 Depth1;
}
public class Depth3
{
public Depth2 Depth2;
}
private void button12_Click(object sender, EventArgs e)
{
Depth3 depth = new Depth3();
depth.Depth2 = new Depth2();
depth.Depth2.Depth1 = new Depth1();
depth.Depth2.Depth1.Leaf = new Leaf();
Leaf leaf = new Leaf();
var T1 = Environment.TickCount;
for (int i = 0; i < 100000000; i++)
{
depth.Depth2.Depth1.Leaf.Property++;
}
var T2 = Environment.TickCount;
for (int i = 0; i < 100000000; i++)
{
leaf.Property++;
}
var T3 = Environment.TickCount;
MessageBox.Show((T2 - T1).ToString() + Environment.NewLine +
((T3 - T2).ToString()));
}
The only concern here IMHO is not speed, but dependency. Have you ever tried to refactor an application that frequently uses deep object nesting like this? It's a pain in the arse. Have a look at the Law of Demeter (or as I say, the Guideline of Demeter). The idea is that instead of using
person.Address.ZipCode
you instead use something like
person.AddressZipCode
to avoid a dependency on the Address object. Is it faster? Maybe, if you implement it right. But I personally don't care because the speedup is really trivial. All I care about here is reducing dependencies.
The term nested class is usually used to mean "nested type".
class Foo
{
private class FoosHelper { .. }
}
The best practice here is to use them sparingly and prefer private.
But your example is not about nested classes but about nested objects instead:
object1.object2.object3.object4.Property
The best practice would be: build a logical and cohesive object-model first and foremost.
Your suggestion of 'flattening' seems to be about sacrificing the core architecture for a tiny optimization. Not such a good idea.
And to the (only slightly) related struct question:
is there any advantage to using structs where one is simply trying to group a number of fields together
No, usually not. There are rare case where you would need very large arrays of small types but in general using a struct brings only disadvantages.
In my opinion, you shouldn't take the speed into consideration until you realize it's a bottleneck.
The classes/structs should be grouped purely logically: if you see that some class is a part of some other class, that it is needed only inside the bigger class and makes sense only inside the bigger class, then you should put it there and thus avoid polluting namespace. If you see that your smaller class is useful outside the bigger class, define it outside. That simple.
Summing it up: put your class/structure to the deepest appropriate level, but not deeper.
Examples:
myCar.RegistrationDate.Year.IsLeap makes perfect sense, and is much better than myCar.IsRegistrationYearLeap
point.Coordinates.Cartesian.X doesn't make much sense, point.X is much better.
Struct field will not have separate memory allocation then the enclosing object, so there is no difference how deep it is, if all of the nested are structs, it's computed by the compiler.
If you nest the reference types, they have to be dereferenced, and this is not any different from C++.

Abstracting away an API [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I've been writing a framework for myself in C# and my framework works on top of the Xna framework. In application code that uses this framework, I often have to include references to my framework and Xna's framework. Most of the time those Xna references are only to include some the struct classes like Vector2 and Rectangle. Because of this though, I try and make sure that the name's of my classes don't conflict with the name's of Xna classes. This can get tiresome and even confusing to myself when I have classes where I have come up with a similar name but not the same as the Xna one. (ie GamePadDevice and GamePad)
I've had an idea as of late but I don't know if it's worth it. I only use a few, 5 or 6 of the structs throughout my framework. Would it be worth it to abstract these structs away so that my application code would only have to deal with my framework? I could do this by either writing my own versions of the structs or inheriting from them or maybe someone could suggest a better way. Is the overhead worth simplifying my application code?
I dont know how deep your framework goes on replacing the XNA layer, but if the user has no contact with XNA anymore, and is "just" using your framework, then it would be nicer if your framework only exposes his own structs to the client. After all, you might want to switch away from XNA one day and support XNB or XNC?
If you write a mapper in your framework that translates you will have the flexibility to do that later on
A good way to abstract away third party libraries is to introduce interfaces with methods you need and let the object creation be done by a Factory. Especially in your case, where you just use a bunch of the classes, this is, in my opinion, the best choice.
Lets assume we need to sanitize html code and do have a kickass library found which can do this for us, but we don't want to stick to this library - maybe somebody relases a super kickass lib someday we would like to use.
This could be implemented as follows (code in java )
First the interface definition:
public interface HtmlSanitizer {
String sanitizeHtml(String html);
}
Then we create an concrete implementation for our interface, based on our kickass sanitizer
public class MyKickassHtmlSanitizer implements HtmlSanitizer {
private com.foolib.kickass.html.Sanitizer delegate;
public MyKickassHtmlSanitizer() {
this.delegate= new com.foolib.kickass.html.Sanitizer();
}
public String sanitizeHtml(String html) {
return delegate.kickassSanitizeHtml(html);
}
}
Now the Factory which creates our sanitizer
public class HtmlSanitizerFactory {
private static final HtmlSanitizerFactory instance = new HtmlSanitizerFactory();
private HtmlSanitizerFactory() {}
public static HtmlSanitizerFactory get() { return instance;}
public HtmlSanitizer getSanitizer() {
return new MyKickassHtmlSanitizer();
}
}
To obtain an instance simply use:
HtmlSanitizerFactory.get().getSanitizer();
Whereas the factory can provide static methods or not, can be a singleton or not. A matter of taste and use case.
Now your dependency to the libs kickass sanitizer is reduced to one point and to change the implementation simply introduce an SuperKickassHtmlSanitizer and let the factory return it.
Hope that helps :-)

Categories

Resources