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 3 years ago.
Improve this question
We have a small disagreement within my team over whether injected dependencies should be stored as readonly fields:
public class MyClient
{
private readonly IService service;
public MyClient(IService service)
{
this.service = service;
}
}
or as private readonly properties:
public class MyClient
{
private IService Service { get; }
public MyClient(IService service)
{
Service = service;
}
}
Are there any advantages to one choice over the other? I favour the former but it seems half of our classes use the latter.
You should use a readonly field.
The are three reasons to use properties over fields:
You want to add some extra logic which is run when the property is accessed.
You want to reserve the right to add some extra logic in the future, without changing your interface.
You're using some tool / serialization framework which only deals with properties, and ignores fields.
Point 2 is why people recommend using properties instead of fields for all public (and sometimes protected) members. Point 1 (and perhaps point 3, in rare cases) is the only reason you would create a private property.
None of those points apply here. The property is only adding extra overhead, and there's no reason to pay that cost for zero gain.
I think readonly field is the safest approach as it prevents you from creating a new instance of the field in a different place than the constructor(Single Responsibility Principle). The decision what kind of implementation for interfaces should be used in a given class should be done at the level of the DI container. You can inject different objects for different environments, based on the app settings in your Continuous Delivery pipeline. Though you don't have to worry about weird things like e.g. using some AzureSerive when using OnPremise version of the app etc.
[Using a private readonly property with a getter or a private readonly field is equivalent in term of generated bytecode, so it's just a matter of taste.] <-- this is not true, as pointed below. Sorry for the inconvenience.
I prefer (and use) private fields, as I consider them more clear semantically (in my mind a field is private, fullstop) and less verbose (no need for that awful { get; }, I hate getters 😄).
Related
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
Here is two classes MyClass and Helper, in order to have one instance of Helper class in MyClass it could be initialize with property:
public class MyClass
{
private IHelper _helper;
private IHelper Helper
{
get
{
if (_helper != null)
{
_helper = new Helper();
}
return _helper;
}
}
}
or constructor:
public class MyClass
{
private IHelper Helper { get; set; }
MyClass()
{
Helper = new Helper();
}
}
The question: What is benefits and potential issues with each solution? Is it some other better options?
The two approaches are not identical:
The first approach creates _helper on the first read; if Helper property is never accessed, no instance of Helper is created
The second approach creates _helper eagerly, meaning that you would have an instance of Helper in each instance of MyClass.
The choice between these two behaviors is based on your requirements, not on an opinion. Note that you can use Lazy<T> class to achieve the behavior from your first example with less code:
public class MyClass {
private Lazy<IHelper> _helper = new Lazy<IHelper>(() => new Helper());
private IHelper Helper {
get => _helper.Value;
}
}
Those two examples don't do the same and so there is no "matter of style", but of "how should it work". The difference is minor but still there is one:
In your first example the instance of Helper is only created if it is accessed at least once, but in your second example it is always created even if it is not needed.
Also in the second example it has a private setter an thus can be changed later on in time again.
IMO you should use the first one if it is not always used and the second one if it is needed every time, but then make the property read-only (remove the setter - setting in the constructor still works if your compiler is up to date).
Another shorter version for the first one I tend to use in such cases (Lazy<T> has some minor overhead and do not use it for "singleton like patterns"):
private IHelper helper;
public IHelper Helper => helper ?? (helper = new Helper());
NOTE: This code-example is NOT thread-safe, so if that is a requirement use the example from dasblinkenlight. Here it could happen that two instances of Helper are created if the property is accessed the same time by two threads and the second one is then set to helper in the end. If that is not the case or no problem it is safe to use. If I remember correctly the thread-safety is also the main reason why Lazy<T> creates some measurable overhead which led us to not use it in all cases.
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 5 years ago.
Improve this question
It seemed like this was possible, but I can't find a reference on how to accomplish it, though I've seen a few things that are closely related. I have a particular type of class that requires a public or private default ctor. The reason is stylistic; it is a domain aggregate and the only case where a default ctor should be used is during event store replay. There are obvious ways to work around this, but I'm trying to lock this particular type down. At any rate, what I'm hoping to do is create an attribute that can be applied at the class level that would enforce the existence of a default ctor. If one isn't found, it won't compile... or at the very least, give it the big nasty blue underline like [Obsolete()] does. I figured this was potentially doable with Roslyn. Any direction would help. The solution would ideally travel with the project rather than being something that needs to be installed on visual studio.
Just a simple idea, for a public default constructor you could make use of the where T : new() constraint - even though attributes cannot be generic you can supply typeof(HasDefaultConstructor<MyClass>) as an argument to an attribute:
public static class HasDefaultConstructor<T> where T : new() { }
public class CheckAttribute : Attribute
{
public CheckAttribute(Type type) { }
}
[Check(typeof(HasDefaultConstructor<MyClass>))]
public class MyClass
{
public MyClass() { }
}
But it feels a bit hacky having to supply the type you're applying the attribute to, and doesn't work for the non-public constructors, but it does fail at compile-time without needing any addons.
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
public class MyTokenStore: ITokenStore
{
public IToken CreateRequestToken(IOAuthContext context)
{
...some code here...
}
public IToken CreateAccessToken(IOAuthContext context)
{
...some code here...
}
}
Which one of below is better ?
Option1 - ITokenStore x = new MyTokenStore(); OR
Option2 - MyTokenStore x = new MyTokenStore()
What are the advanatges of both ?
Can I restrict user from using Option 2 ?
Users decide for themselves which version they use. The advantage of option 1 is that the user can really instantiate any class that implements the interface. Say you have a helper class that contains a method
DoSomethingVeryUseful(ITokenStore store)
then again that method becomes more useful because it can be called with any object that implements said interface.
The advantage of using option 2 is that your class may contain methods that are not part of the interface, and thus those methods can only be used with option 2.
There is no general good response to this, as it fully depends on you concrete case.
ITokenStore x = new MyTokenStore()
mades a "slice" over concrete MyTokenStore instance where not all members are inside ITokenStore, so you missing access to some additional information that may be present in MyTokenStore and is not present in ITokenStore.
On other hand you create an abstraction layer, so gain a flexibility.
The purpose of an interface is to expose functionality that is common to all implementer's and is agnostic of the concrete implementation. If you are trying to pass around multiple concrete objects to a consumer that needs to access an interface method, then cast it as an interface.
However, if you need a specific member on the concrete implementation, use that.
This is not which is better question but more what are you going to do with it ? Somethings to consider
Are you going to have multiple objects implement the interface ?
Are you going to be doing unit testing ?
Are you going to be doing any in Dependency Injection ?
If you can answer yes to at least one of the questions the using a interface is a good idea but if your using a interface just to use a interface you might want to rethink the solution
My suggestion is the below option. Instead creating "new" object, we can go with contructor injection.
public class MyTokenStore{
private readonly ITokenStore;
public MyTokenStore{ITokenStore TokenService)
{
this.TokenStore=TokenService;
}
}
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 :-)