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 :-)
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 3 years ago.
Improve this question
When implementing an interface on a concrete class, is it appropriate to have extra public methods exposed to help facilitate unit tests?
For example, let's say I have the following concrete class:
public class MyClass : IMyInterface
{
public int InterfaceMethod(ComplexObject complexObject)
{
return NonInterfaceMethodOne(complexObject)
+ NonInterfaceMethodTwo(complexObject);
}
public int NonInterfaceMethodOne(ComplexObject complexObject)
{
//Do complex logic that needs to be unit tested
}
public int NonInterfaceMethodTwo(ComplexObject complexObject)
{
//Do more complex logic that needs to be unit tested
}
}
If I wrote my class this way, I could have unit tests for both non-interface methods, but I feel like this pattern is not correct. Is there a better way?
What you have there looks perfectly acceptable to me. A general answer to your question is "it depends," because there could be scenarios where you want to hide those methods, and there could be scenarios where you want to expose them.
It's reasonable to consider your test suite as the first client of your code base, and it makes sense to support the needs of your client--you would still want to give careful consideration to what functionality you want to expose and hide.
In spite of the fact that NonInterfaceMethodOne and NonInterfaceMethodTwo are both public, if you inject this implementation into a parameter of the interface type, the client will still only have access to the interface method and will have no knowledge of the other 2 methods.
A client that is using the implementation will of course have access to all 3 methods, but will still not know how the interface method is implemented.
If it would be useful to expose those methods for unit testing and if you can determine that no damage is done by keeping the methods public, then keep them public.
But, it could still be appropriate to write your tests to ensure that NonInterfaceMethodOne and NonInterfaceMethodTwo work the way you want, then cover your interface method with another test(s), and then you may possibly no longer have a need for the unit tests covering NonInterfaceMethodOne and NonInterfaceMethodTwo--in which case you could remove these tests, and then make NonInterfaceMethodOne and NonInterfaceMethodTwo private--because your unit test(s) covering the interface method covers the other 2 methods.
and if you find that this approach doesn't hide any functionality that your test suite needs, I would lean toward this approach, because it's normally good to limit the functionality you expose
You can get something similar to this, but without having to make the members public, by using the InternalsVisibleToAttribute.
Let's say your assemblies/projects are named ProductCode.dll and TestFixtures.dll. You can make the internal types and members in ProductCode.dll visible to TestFixtures.dll, but no other assemblies, by declaring the following in the ProductCode project (typically in AssemblyInfo.cs):
[assembly: InternalsVisibleTo("TestFixtures")]
Then you can declare these exposed-for-testing-only methods as internal instead of public, but the unit tests can still call them.
If you only run your tests in a Debug configuration, not in the Release configuration, you can make this access control exemption only happen in the Debug configuration by surrounding the attribute like this:
#if DEBUG
[assembly: InternalsVisibleTo("TestFixtures")]
#endif
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 😄).
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 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 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.