I have 2 forms and 1 Class.
I made the class a Static Class.
It has two methods with public modifiers.
Ex: Public string PrintHello(), Public void Task1()
I want these methods to be accessible from both Form1 and Form2.
I understand that using "Public" modifier is not good, so I've looked at "Internal" modifier and it seems to do the job.
Basically, I want to create a secure way of accessing my class.
What would be the best way of doing so and could you provide an example of how to do so ?
Thank you
Access modifiers does not provide security to you code.
Is someone really wants to use your privet methods he can use ILDASM to de-compile your code and use them, that would be just one example of many.
Access modifiers are there to to allow you to program using with an Object Oriented code design.
In general:
Private modifiers are internal to your class implementation and other classes or layers of your code dose not NEED nor want to know about there existence.
Internal modifiers are there to provide additional functionality required for the whole assembly but again they are not required for any one else (outside of the assembly) because they are implementation specific.
And finally Public modifiers are used to define the interface of your class with the outside world, these are methods and properties that should and will be used by any one that requires some sor of functionality from your code.
Depends on where you think the code that calls this methods will likely live. If it is only going to be ever called from the class that defined this method, then it should be private. If you only want to call it from the same assembly (dll) but you don't want to call the methods from other dlls, then you should make it internal. This way you can ship your dll to other projects and you don't have to worry about supporting your methods (because they won't have access to your methods).
But if you are doing a general purpose libarary/dll etc. Then the methods should be public.
It all depends on who or what you think is going to call your methods.
Related
I am publishing a public class as part of my C# framework for users to be able to register within my application. I don't want users to extend my class so I marked it sealed. Now I have some users reporting that they see more methods in that class than the ones I provided. After some investigation, it appeared that these users have defined extension methods that show (by intellisense) just like if they were defined in my public sealed class.
Question
Is there a way I can forbid users to define extension methods on my public sealed class?
No, you can't. I can't see why you'd want to, to be honest. If you have users who want to use extension methods, let them do so. No-one's going to force them to do so, and it may make their life easier. At least as your type is sealed, you know that if anyone reports unexpectedly-available methods, they must be extension methods.
Note that anyone can define an extension method on object, and that would always be available, even if there were a way of prohibiting extension methods on just your class.
I have heard some people are against the use of internal modifier to hide classes and members from outside the assembly in which they are declared because it defeats the main principles of OOP. Is this really true?
Is this really true?
No, it is not true. Internal visibility modifier has its usages. There are classes which you don't want to be used outside of their containing assembly but still to be public inside the assembly. For example if you are designing an API, there might be classes that you don't want to expose to consumers of your API.
internal keyword allows developers to hide members of the assembly if it is used by another assembly. In .NET framework for example there are many types that are internal, meaning they are only required for the inner assembly usage and are not visible from outside the library. This is encapsulation on the assembly level.
Well people are free to have their opinions. I'm not sure how "internal" defeats the main principles of OOP.. perhaps a link would help me to evaluate their stance.
I use internal to hide types that I don't want anyone outside the assembly to use. This is pro-OOP in my opinion
expose behavior but hide implementation.
use the most restrictive access possible
e.g. I refactor some common code out of 2 public types ; this new type starts out as internal. Unless some client/test drives me to increase the visibility. Also I sometimes use it as a temp cheat to avoid writing tests for some types (all public types should have tests). It has served me well.
As it says, Which section of a class should be public?
I really feel like this is a security question myself.
"What class components are typically designated as public?"
The public parts of a class are those parts you want other classes to interface with. So that could be methods, properties, delegates, etc.
The private parts of a class are those things that no other class needs to interface with and is only internal to that class.
It is not a security issue.
When the author of a class marks members as private he is not stating "you may not know" but insted "you don't have to know" .
Encapsulation is about designing (organizing) a class with an 'inside' and an 'outside' , It is not about secrets or privileges.
Public vs private class declarations has nothing to do with security. It's about information hiding for the sake of keeping a clear definition of the contract that the class claims to support with its clients (and claims to continue supporting in future revisions), and keeping implementation details that need to be handled in a specific manner (kept in sync, consistent internal state) or that may need to be changed in future implementations away from clients.
Do not think of public vs private access as a form of security. These access modifiers exist primarily in the source code and are primarily enforced by the language compiler at compile time; at runtime any program or code is capable of enumerating the public and private members of your class using the .NET type system, and calling those public and private members through reflection.
Private declarations are a social nicety, not a security.
C# access modifiers are an aspect of design and cannot really be used for security. Obviously they can help you implement some kind of security by enforcing (really just encouraging) certain access patterns (i.e. your internal APIs encourage database connections only through some kind of factory which connects with a connection string created securely or in some consistent way, or all access to passwords is through classes which are designed to properly scramble the memory and encrypt on disk), but they can't really enforce security.
Public, private, protected and internal are the access modifiers applied to classes and members and relate to the interfaces exposed and how they behave with respect to inheritance, intra and inter-assembly-level access.
What should be public are members which need access visibility outside the class (and outside the assembly). Anything else should not be exposed until its need for visibility in the interface is properly justified. In many cases, I would suggest most things be private until justified that they need to be public. Sometimes they are immediately obvious. Certainly for static members you should really be careful about exposing as public.
I'm working with a 3rd party c# class that has lots of great methods and properties - but as time has gone by I need to extend that class with methods and properties of my own. If it was my code I would just use that class as my base class and add my own properties and method on top - but this class has an internal constructor. (In my opinion it was short sited to make the constructor internal in the first place - why limit the ability to subclass?)
The only thing I could think of was to create method / properties on my class that simply called into theirs - but it's acres of code and, well, it just doesn't "feel" right.
Is there any way to use this class a base class?
You ask: "Why limit the ability to subclass?"
Because designing for inheritance is tricky, particularly if you're designing for other developers to inherit from your class. As Josh Bloch says in Effective Java, you should design for inheritance or prohibit it. In my view, unless you have a good reason to design for inheritance, you shouldn't do so speculatively.
Does the class implement an interface which you could also implement (possibly by proxying most calls back to an instance of the original)? There's often no really elegant answer here - and the best solution will depend on the exact situation, including what you're trying to add to the class.
If you're not adding any more state - just convenience methods, effectively - then extension methods may work well for you. But they don't change what data an object is capable of storing, so if you need to add your own specialised data, that won't work.
Sounds like a perfect application for extension methods:
MSDN extension method docs
"Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type."
If the class has an internal constructor, and there are no public constructors, then that suggests that the designers did not intend for it to be subclassed. In that case, you can use encapsulation, or you can use extension methods.
Only if your class lives in the same assembly as the class you want to inherit from. An internal constructor limits the concrete implementations of the abstract class to the assembly defining the class. A class containing an internal constructor cannot be instantiated outside of the assembly.
Resharper has a nice feature to create delegating members.
Here is a sample of what you can do with it. It takes a couple of seconds.
I will not discuss whether you can build your own Facade around that 3rd party class. Previous authors are right, the library could be designed in the way that will not allow this. Suppose they have some coupled classes that have singletons that should be initialized in specific order or something like this - there may be a lot of design mistakes (or features) that 3rd party developers never care about, because they do not suppose that you will use their library in that way.
But OK, lets suppose that building a facade is not an impossible task, and you have in fact only one problem - there are too many methods you have to write wrappers around, and it is not good to do this manually.
I see 3 solutions to address exactly that problem
1) I suppose that new "dynamic" types of .NET 4.0 will allow you to workaround that problem without having to write "acres of code"
You should incapsulate an instance of 3rd party class into your class as a privare member with dynamic keyword
Your class should be derived from Dynamic or implement IDynamicObject interface. You will have to implement GetMember/SetMember functions that will forward all calls to the encapsulated instance of 3rd party class
Well, c# 4.0 is a future, Let's see on other solutions:
2) Do not write code manually if you have significant number of public methods (say more then 100). I would write a little console app that uses reflection and finds all public members and then automatically generates code to call encapsulated instance. For example
public type MethodName(params)
{
this.anInstanceOf3rdPartyClass.MethodName(params);
}
3) You can do the same as 2, but with the help of existing reflection tools, for example RedGate .NET Reflector. It will help you to list all classes and methods signatures. Then, paste all this in Word and a simple VB macro will let you generate the same code as you could do in 2.
Remark: As soon as you are not copying the code, but only copying method signatures, that are publicly available, I don't think you will violate the license agreement, but anyway it worth to re-check
I am developing a set of classes that implement a common interface. A consumer of my library shall expect each of these classes to implement a certain set of static functions. Is there anyway that I can decorate these class so that the compiler will catch the case where one of the functions is not implemented.
I know it will eventually be caught when building the consuming code. And I also know how to get around this problem using a kind of factory class.
Just curious to know if there is any syntax/attributes out there for requiring static functions on a class.
Ed Removed the word 'interface' to avoid confusion.
No, there is no language support for this in C#. There are two workarounds that I can think of immediately:
use reflection at runtime; crossed fingers and hope...
use a singleton / default-instance / similar to implement an interface that declares the methods
(update)
Actually, as long as you have unit-testing, the first option isn't actually as bad as you might think if (like me) you come from a strict "static typing" background. The fact is; it works fine in dynamic languages. And indeed, this is exactly how my generic operators code works - it hopes you have the static operators. At runtime, if you don't, it will laugh at you in a suitably mocking tone... but it can't check at compile-time.
No. Basically it sounds like you're after a sort of "static polymorphism". That doesn't exist in C#, although I've suggested a sort of "static interface" notion which could be useful in terms of generics.
One thing you could do is write a simple unit test to verify that all of the types in a particular assembly obey your rules. If other developers will also be implementing the interface, you could put that test code into some common place so that everyone implementing the interface can easily test their own assemblies.
This is a great question and one that I've encountered in my projects.
Some people hold that interfaces and abstract classes exist for polymorphism only, not for forcing types to implement certain methods. Personally, I consider polymorphism a primary use case, and forced implementation a secondary. I do use the forced implementation technique fairly often. Typically, it appears in framework code implementing a template pattern. The base/template class encapsulates some complex idea, and subclasses provide numerous variations by implementing the abstract methods. One pragmatic benefit is that the abstract methods provide guidance to other developers implementing the subclasses. Visual Studio even has the ability to stub the methods out for you. This is especially helpful when a maintenance developer needs to add a new subclass months or years later.
The downside is that there is no specific support for some of these template scenarios in C#. Static methods are one. Another one is constructors; ideally, ISerializable should force the developer to implement the protected serialization constructor.
The easiest approach probably is (as suggested earlier) to use an automated test to check that the static method is implemented on the desired types. Another viable idea already mentioned is to implement a static analysis rule.
A third option is to use an Aspect-Oriented Programming framework such as PostSharp. PostSharp supports compile-time validation of aspects. You can write .NET code that reflects over the assembly at compile time, generating arbitrary warnings and errors. Usually, you do this to validate that an aspect usage is appropriate, but I don't see why you couldn't use it for validating template rules as well.
Unfortunately, no, there's nothing like this built into the language.
While there is no language support for this, you could use a static analysis tool to enforce it. For example, you could write a custom rule for FxCop that detects an attribute or interface implementation on a class and then checks for the existence of certain static methods.
The singleton pattern does not help in all cases. My example is from an actual project of mine. It is not contrived.
I have a class (let's call it "Widget") that inherits from a class in a third-party ORM. If I instantiate a Widget object (therefore creating a row in the db) just to make sure my static methods are declared, I'm making a bigger mess than the one I'm trying to clean up.
If I create this extra object in the data store, I've got to hide it from users, calculations, etc.
I use interfaces in C# to make sure that I implement common features in a set of classes.
Some of the methods that implement these features require instance data to run. I code these methods as instance methods, and use a C# interface to make sure they exist in the class.
Some of these methods do not require instance data, so they are static methods. If I could declare interfaces with static methods, the compiler could check whether or not these methods exist in the class that says it implements the interface.
No, there would be no point in this feature. Interfaces are basically a scaled down form of multiple inheritance. They tell the compiler how to set up the virtual function table so that non-static virtual methods can be called properly in descendant classes. Static methods can't be virtual, hence, there's no point in using interfaces for them.
The approach that gets you closer to what you need is a singleton, as Marc Gravell suggested.
Interfaces, among other things, let you provide some level of abstraction to your classes so you can use a given API regardless of the type that implements it. However, since you DO need to know the type of a static class in order to use it, why would you want to enforce that class to implement a set of functions?
Maybe you could use a custom attribute like [ImplementsXXXInterface] and provide some run time checking to ensure that classes with this attribute actually implement the interface you need?
If you're just after getting those compiler errors, consider this setup:
Define the methods in an interface.
Declare the methods with abstract.
Implement the public static methods, and have the abstract method overrides simply call the static methods.
It's a little bit of extra code, but you'll know when someone isn't implementing a required method.