What sections of a class are designated to be public? - c#

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.

Related

How to distinguish 'Role' interfaces from 'Result' interfaces?

This issue comes up for me so often in my coding that I'm astonished I can find so little reference to it, and would value other people's thoughts and ideas.
I define lots of APIs, for the frameworks I work on, and within large domain models that I want to break up. Those APIs consist almost entirely of interfaces (meaning, in my case, C# interfaces). I find, over and over again, that I want to distinguish between two kinds of interface. In the absence of finding any more widely used terms, I define these two as follows:
'Role' interfaces are intended to be implemented by objects outside of the API, in order that those objects can be used as arguments for methods defined on the API.
'Result' interfaces are implemented by objects inside the API and made available to other parts of the system via the API. The intent of defining a result interface rather than exposing the object that implements it is to restrict the view of the object to the outside world.
To pick one example, a Payments sub-system might define IPayableItem as a Role interface, implemented by many types in other parts of the application in order that Payments may be generated for them. Those generated Payment objects may be retrieved via the API but defined by the Result interface IPayment.
The only way I can currently distinguish these is by naming convention and/or commenting. Ideally, I would like the distinction enforced by the language, and have it enforce the rule: you can't implement a Result interface outside the API, only use it. But C# doesn't provide any such mechanism. (Can anyone advise me of a language that does?). I could define an attribute, but this still wouldn't enforce anything.
Another important significance of the distinction lies in Semantic Versioning of the API. If I add a new member to a Role interface then this should be seen as a breaking change (and hence a first-level version) - because any existing external implementations will need to add that member. But if I add a member to what I deem to be a 'Result' interface then it should only be my own code that is impacted - it is just a new feature (second-level version) for everyone else. But with no enforced distinction between the two types there's some risk that people are implementing the Result interfaces and hence their code would be broken.
Has anyone else encountered this dilemma? If so, how have you dealt with it? I look forward to your answers.
But please don't both to respond with either of the following arguments (which I have heard all too often):
My Result interfaces should be abstract classes rather than interfaces. This does not solve the problem, and potentially makes it worse, since external code can sub-class them.
I should be returning the concrete type and ensuring that anything I don't want accessible outside the API is marked 'internal'. There are lots of cases where I need things inside the API to be public, e.g. to be accessible to other frameworks (not going through the API).
I think what you're asking is it possible to expose an interface, but determine that a given instance is one you created?
If so, you could also create an internal private interface, and mark all your implementations as also implementing the private interface. Then upon being given an object from the outside world, verify it has the internal interface implementation as well.
public interface IPublic
{
...
}
internal interface ISecret { }
public class PublicImplementation : IPublic, ISecret
{
...
}
Only you can implement the ISecret, so even if someone implements the IPublic and passes it to you, it will fail the ISecret test.

Avoiding Public methods in another class?

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.

When does encapsulation trump SOLID - public vs private c# class?

I'm working on some MonoTouch code that I derived from one of the samples (this is not a MonoTouch specific question) and the sample code declares a private class inside another class. I've not seen private classes used much in c# and I'm at a loss as to when it might make sense. I can see how a class that is only referenced within another class could be declared private but isn't this going to cause more grief than it's worth? Doesn't this break a number of the SOLID principles?
Single Responsibility - broken?
Open/Closed - broken?
Liskoff Substitution - maybe ok?
Interface Segregation - broken?
Dependency Inversion - broken?
Right now I'm finding it confusing just trying to navigate the source because of the private class definition. I guess this could be mitigated somewhat by declaring a partial class to contain the private class and separating them into separate files that way but is this really a good approach?
Usually, nested types (either class or struct, including enumerations) are used for some kind of contextual data and/or behavior, which doesn't have any sense without its context.
E.g., you could make nested types for some interop API, when you don't want to provide access to that API from external code, or you're using some kind of helper data container, which provides functionality, useful only for surrounding class.
So, even making these types internal can bring confusion to other developers (especially, where a single project is being edited by several people).
I don't see, how SOLID is broken here - nesting the type is just a limiting of type scope. It is not an extending of functionality of the surrounding class.
I've used private classes in situations where an API says "you must implement and provide to us an implementation of this interface when we ask you for it" and there is no other use or consumer of that class other than the use of the API interface.
In this situation, the interface provides public or cross-functional access so there is no need for access to the implementation.
Why would the SRP be broken? You separate a responsibility that is only accessed inside a class into a nested class.
Most other principles do not apply to private members or private nested classes.
I'm not sure but I think Single Resposibilty can be broken by nested classes, since a class can now have more resasons to change. The definition is not very clear at Single Resposibilty... Anyway I think ms does also use nested classes in .net, so maybe c# is missing some features in terms of encapsulation here. I think nested classes can be fixed with not doing nested classes and writing a analyzer. Nested classes are often used to get access to private members of the wrapping class.

Why choose a static class over a singleton implementation?

The Static Vs. Singleton question has been discussed before many times in SO.
However, all the answers pointed out the many advantages of a singleton.
My question is - what are the advantages of a static class over a singleton?
Why not simply choose a singleton every time?
Static class is a technical tool in your box - basically a language feature.
Singleton is an architectural concept.
You may use a static class as a means to implement the singleton concept. Or you may use some other approach.
With static classes in C# there are two potential dangers if you're not careful.
The requested resources will not be freed until the end of application life
The values of static variables are shared within an application. Especially bad for ASP.NET applications, because these values will then be shared between all users of a site residing in a particular Application Domain.
From MSDN
Static classes and class members are used to create data and functions
that can be accessed without creating an instance of the class. Static
class members can be used to separate data and behavior that is
independent of any object identity: the data and functions do not
change regardless of what happens to the object. Static classes can be
used when there is no data or behavior in the class that depends on
object identity.
A key point is that static classes do not require an instance reference. Also note that static classes are specifically enabled by the language and compiler.
Singleton classes are just user coded classes implementing the Singleton design pattern. Singleton purpose is to restrict instantiation of an class to a single instance.
If you coded every static class as a singleton you'd have to instantiate the class every time you used it.
i.e.
Console.WriteLine('Hello World');
would become
Console c = Console.getInstance();
c.WriteLine('Hello World');
I'd say they're both (generally) poor solutions. There are a few use cases for static classes, primarily simple utility ones (Extension Methods in C# 3.0 come to mind). With any degree of complexity, though, testability issues start cropping up.
Say class A depends on static class B. You want to test class A in isolation. That's hard.
So you go with a Singleton. You have the same problem - class A depends on singleton B. You can't test class A in isolation.
When class B has other dependencies (such as hitting a database) or is mutable (other classes can change its global state), the problem is exacerbated.
IoC (Inversion of Control) container libraries are one solution to this problem; they let you define Plain Old Classes as having a long lifespan. When combined with a mocking library, they can make your code very testable.
Static classes are much easier to implement - I have seen many attempts at thread-safe singletons in C# that employs naive locking schemes instead of depending on the run-time's guaranteed one-time initialization of static fields (optionally inside a nested class to delay instantiation).
Other than that, I think singletons are great if you need to pass around a reference to an object that implements a specific interface, when that 'implemention' should be singleton, something which you cannot do with static classes.
One consideration I don't see mentioned is that preferring a solution using an instance of a class (singletons, or their DI equivalent) allows you to provide a class on which other users of your code may define extension methods -- since extension methods only work with non-static classes as the this parameter. In other words, if you have a line like:
GlobalSettings.SomeMethod();
Then syntactically the only thing that can be accessed via GlobalSettings are members you provide. In contrast, if GlobalSettings is an instance (singleton or otherwise) then consumers may add their own extensions to GlobalSettings that they would be unable to do otherwise:
application.GlobalSettings.CustomSomethingOrOther();
or
GlobalSettings.Instance.CustomSomethingOrOther();
The question leads to the need for a better understanding of what you are implementing, how it suppose to work, and what it should be capable of.
Let's say, you need some kind of Manager class that handles your object's in a particular way. Singleton requires a bit more work, but in return, it gives you the ability to treat your manager by its interface (IManager) rather than the strict name. With a static class, you obviously losing the inheritance, interfaces, and the ability to swap or reset the object by just re-instantiating it rather than manually zeroing all the static variables, but it also gets you rid of a bit of extra work in case if your static object is kept simple.
There are more extra details if you go deeper, but in general 99% of times, it's just a question of personal preference or your team's coding guidelines.

Does internal types compromise good API design?

It seems to me that anytime I come across internal calls or types, it's like I hit a road block.
Even if they are accessible in code like open-source, it still feels they are not usable parts of the API code itself. i.e. it's as if they are discouraged to be modified.
Should one keep oneself from using the internal keyword unless it's absolutely necessary?
I am asking this for an open-source API. But still not everyone will want to change the API, but mostly use it to write their own code for the app itself.
There is nothing wrong with having an internal type in your DLL that is not a part of your public API. In fact, if you have anything other than a trivial DLL is more likely a sign of bad design if you don't have an internal type (or at least a non-public type)
Why? Public APIs are a way of exposing the parts of your object model you want a consumer to use. Having an API of entirely public types means that you want the consumer to see literally everything in your DLL.
Think of the versioning issues that come along with that stance. Changing literally anything in your object model is a breaking change. Having internal types allows you great flexibility in your model while avoiding breaking changes to your consumers.
Internal types are types that are explicitly meant to be kept out of the API. You should only mark things internal that you don't want people to see.
My guess is that you're coming across types that are internal, but would have been valuable additions to the public API. I've seen this in quite a few projects. That's a different issue, though - it's really the same issue as whether a private type should have been public.
In general, a good project should have internal or private types. They help implement the required feature set without bloating the public API. Keeping the public API as small as possible to provide the required feature set is part of what makes a library usable.
An API is comprised of its public types and members, anything else is an implementation detail.
That being said, I think that internal types can be very useful especially when you want to return interface types from your API and don't want to expose the concrete types that you have used to implement those interfaces. This gives the API designer a lot of flexibility.

Categories