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++.
Related
This question already has answers here:
Is there an easy way to make an immutable version of a class?
(7 answers)
How do I create an immutable Class?
(8 answers)
Closed 5 years ago.
I want to see if I can make an instance of a class immutable even if the class itself isn't. What I have here is a similar situation to IntPtr.Zero and other static fields like that, except it's a mutable class and not a struct.
class TestClass
{
public static readonly TestClass GoldStandard = new TestClass();
public int field = 0;
}
class Program
{
static void Main(string[] args)
{
TestClass test = TestClass.GoldStandard;
test.field = 1; // I want to keep this from happening.
Console.WriteLine(TestClass.GoldStandard.field);
}
}
What can I do to keep GoldStandard from being modified?
EDIT: I regret that my question was so badly misunderstood. This is clearly not a duplicate of Immutable type and property in C# or How do I create an immutable Class?. Those questions are about how to create an immutable class, and not how to create an immutable instance of a mutable class.
As for Is there an easy way to make an immutable version of a class?, it certainly sounds very similar to my question. However, there are some important reasons it shouldn't count.
The question asks how to make an instance immutable at some point during the instance's lifetime, rather than just having one instance of a mutable class be immutable from the start.
The question asks how an immutable second class can be generated to mimic a mutable class, rather than having one mutable class act as immutable in a specific case.
The answer to the question doesn't even address my question at all, and is mostly about how immutable classes work in general.
I understand moderators can't take too much time to understand the questions in depth when they're scanning for duplicates, but I hardly think it's fair for my question to be closed as a duplicate because of such superficial similarities.
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.
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.
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.
What is the general consensus towards a separate class in the business layer to store the definition of enums? Is this bad practice? Does this conform to good n-tier design? At the moment my enum definitions are dotted around different, what I would deem as, relevant classes - but I feel as though they should be in one place. Is this, in fact, a subjective question and relative to how I've structured the rest of the solution?
I don't really understand why you would place an enum in a class - perhaps you meant file?
Personally I have a separate file for each enum with the name of the enum.
I place this file close to where the enum is being used and namespace it accordingly.
If an enum is to be shared across assemblies/namespaces, I will use the lowest shared namespace, so it is visible to the using namespaces.
Having enums close to where they are used will make separating code out into projects that little bit easier (if needed).
I don't see the point in having them all in one file - navigation wise, Visual Studio has more than enough navigation capabilities that this is not needed.
Keeping enums in separate class
In this case you're tossing unrelated definitions into one class, for almost no benefits.
Defining enum as nested type for class it relates to
When you hold enums within a class, you may run into naming troubles:
class Foo
{
public enum SomeType { /* ... */ }
public SomeType SomeType { get; set; }
}
This would give an error that SomeType is already defined.
It probably just boils to personal taste, but most often I put my enums along with the class that they are related to, without nesting them:
public enum SomeType { }
public class Foo { }
I was tempted many times to have them nested (we're talking about public enums of course), but the naming issues weren't worth it, for example:
class Foo
{
public enum Enumeration { }
}
Then I can use such enum outside of Foo class, as: Foo.Enumeration, but following declaration (in same namespace):
enum FooEnumeration { }
class Foo { }
gives similar result as you just don't have to type '.' when you are referencing enum: FooEnumeration. Moreover, the latter allows you for this:
class Foo
{
public FooEnumeration Enumeration { get; set; }
}
which would cause aforementioned naming conflicts in previous case.
Summary
When using IDE with powerful GoTo capabilities, it seems to me that naming issues are far more important than 'physical' localization of the enum definition.
I would prefer having separate classes for all constants and Enums in my projects.It improves readability of the code. You should do it especially if you have a Comman proj you are referencing in your business layer and other layers. But if you'd be adding unnecessary references just for the sake of a Constant/Enum class then having them inside the same project makes more sense.
public class Enumerations
{
public enum Gender{
Male = 0,
Female = 1,
Unknown = 2
}
}
And when you consume you could do it like
GetPerson(Enumeration.Gender gender)
{
}
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 :-)