C# Dependency Injection with OOP Principles - c#

I'm having an issue with coding a basic dependency injection in C#,
To set things out I have an interface IStorage that contains IObject GetObject(int objID).
I then have two windows form:
frmMain
frmSearch
frmMain contains this code:
private readonly IStorage newStorage;
public frmMain()
{
newStorage = new Storage();
}
frmSearch contains this code:
public frmSearch(IStorage newStorage)
{
}
However I am receiving the error:
Inconsistent accessibility: parameter type 'Application.IStorage' is less accessible than method 'Application.frmSearch.frmSearch(IStorage)'
A realise a fix for this is to make my interface public, but that forces me to make the Object Class public as well. I'm fairly new to OOP and this feels like bad coding practice to make all my classes and interfaces public(I could definitely be wrong) so I'm just not quite sure what to do here.
Any help would be greatly appreciated. :)

If your concern is that your classes/interfaces could be referenced outside the current assembly, then take a look at the internal access modifier:
https://learn.microsoft.com/it-it/dotnet/csharp/language-reference/keywords/internal
"A common use of internal access is in component-based development because it enables a group of components to cooperate in a private manner without being exposed to the rest of the application code. For example, a framework for building graphical user interfaces could provide Control and Form classes that cooperate by using members with internal access. Since these members are internal, they are not exposed to code that is using the framework.
It is an error to reference a type or a member with internal access outside the assembly within which it was defined."
Just keep in mind there's a hierarchy in encapsulation, so if a class (for example) has a public visibility, it's public methods can be used from outside the actual assembly. You have then to be careful to avoid having these methods to require parameter types with a lesser visibility, otherwise there would be an inconsistency. Luckily, Visual Studio warns the user about this.

Related

Should I be using "internal" or "private" instead of "public" for methods that call other methods?

In my C# project I have methods that call other methods like this:
options = ReferenceUtilities.GetMenuStatuses();
In my ReferenceUtilities I have coded:
internal static SelectList GetMenuStatuses()
{
throw new NotImplementedException();
}
But should I be using internal or private? I am not sure of the difference here.
As people have already answered, internal means that the member can be accesed by other code in the same assembly. private means that it can be accessed from other code in the same class.
However, one important point to add:
In Properties/Assemblyinfo.cs, you can add the [assembly: InternalsVisibleTo("something")] statement, that lets you access the internal methods from a different assembly.
This can be extremely useful for unit testing purposes, and is a good reason to sometimes use internal over private.
(There is a huge debate over unit testing internals or not, but it is good to know about the possibility.)
internal means that the member can be accesed by other code in the same assembly. private means that it can be accessed from other code in the same class.
This has nothing to do with whether the method calls other methods.
Internal means that other classes in the same assembly can see the method. Private means only the class where the method is defined can see it. If the method will only ever be called by the class that defines it, use private. Otherwise, use internal. Public should only be used when classes outside the assembly need to call the method directly.
As always, there are exceptions, but this is a good general rule to live by.
Going a bit further, service classes (i.e. methods that exist solely to provide a service or feature) should implement interfaces that define the contract for that service or feature. Other classes should pass around an instance of that interface so that only the interface methods are available.
internal is between assemblies while private is between classes
internal: not visible to code from other assemblies, only visible in this assembly
private: not visible to other classes. only visible in this class
public: visible to other classes or assemblies [for class]

Should I set every WinForm object, such as textbox or button, public? What are the risks?

I have noticed for high demand in my projects for objects such as textboxes or buttons public.
Is there any problems by setting them public?
What does public, private, static really mean?
Access Modifiers (C# Programming Guide)
public
The type or member can be accessed by any other code in the same
assembly or another assembly that references it.
private
The type or member can be accessed only by code in the same class or
struct.
protected
The type or member can be accessed only by code in the same class or
struct, or in a class that is derived from that class.
internal
The type or member can be accessed by any code in the same assembly,
but not from another assembly.
protected internal
The type or member can be accessed by any code in the assembly in
which it is declared, or from within a derived class in another
assembly. Access from another assembly must take place within a class
declaration that derives from the class in which the protected
internal element is declared, and it must take place through an
instance of the derived class type.
There is no security risk as far as I know. But there may be better alternative approach to design your program
public, private, etc are called access modifiers and determine the rules for which other code are allowed to access each member.
There is no technical problem of setting controls as public. But I would not recommend it. Having everything public is a good recipe for creating spaghetti code.
Keep all access to controls within your form and expose only a small set of public methods with a simple interface for external actors to access data and operations on the form.
You should not, for a clean design.
You should in reality put the logic of your application outside forms!
However, if you want to keep logic inside forms, you should at least expose them with public properties and methods, without giving direct access to form controls.
For example you can provide things like a method "EnableSave" or "QuitApplication" or "UpdateState".
Public, private and static deal with scope and what can talk to the objects / methods
Public -> Other classes can create an instance of your class (assuming the class is public) and call this object / method directly
Private -> Other classes can create an instance of your class (assuming the class is public) but can NOT access this object / method
Static -> Other classes can directly access this object / method (assuming class is public and method is public static) such as: YourClassName.ObjectOrMethod without having to create an instance of YourClassName
The best access modifier to give to a gui component when you want to access it directly is :internal (that is the default in VB.NET for example).
However you shouldn't give a public or internal modifier on a GUI control and you shouldn't access it directly, because the presentation layer and business logic layer should be kept separated in a well designed architecture ...

C#/.Net enforcing (or just 'hint to fellow developers') that a class method is only supposed to be called from another specific class?

I'm doing some internal domain-specific library development at the moment, and incidentally the stuff i'm trying to model mimicks "class" and "object" relations fairly well. So objects of my C# class MyClass should sort of act like a domain specific class for objects of my C# class MyObject who play the part of object or instance. Now I would like the code in MyObject to access methods of MyClass, which should not be accessible to other classes/code in the project. Any ideas how to enforce this, asside from documenting it at hoping my fellow developers will respect this.
I hope I made my question clear enough, otherwise let me know.
Best regards!
You could always split MyClass and MyObject up into another project, and define MyClass and/or MyObject as an internal class. That way it can only be accessed by other objects in that assembly.
See: http://msdn.microsoft.com/en-us/library/7c5ka91b(VS.80).aspx
The standard approach here is to declare the members internal and make sure MyClass and MyObject are part of the same assembly. That assembly should contain little else.
Additional: This is the tool that was designed for this purpose. Other languages have other means to fine-tune accessibility (C++: friend) but in .NET a simpler model was chosen.
And you don't have to take the 'nothing else' so strictly, the 2 classes could share an assembly with other related classes. you would then have to verify the no-access rule(s) manually inside that library.
I'd suggest a private nested class. That way, even if your fellow devs are writing code in the same namespace, they'll never be able to access the class.
Once the class declaration is fully enclosed within another class declaration, the class is considered nested and can only be accessed through the containing class.
Pehaps your MyObject should descend from MyClass and declare the methods in MyClas as protected.
If you don't want your consumers to invoke certain implementation specific methods you could try abstracting to interfaces or abstract base classes. That way the consumer will only 'see' the properties and methods you want them to see.
You do not have to use inheritance to provide shared functionality and you do not have to rely on member accesibility to prevent others from using methods you'd rather not expose.
For example:
public interface IDomainSpecific
{
void DoStuff();
}
public interface IDomainService
{
void HelpMeDoStuff();
}
public class DomainObject1 : IDomainSpecific
{
private readonly IDomainService _service;
public DomainObject1( IDomainService service )
{
_service = service;
}
public DoStuff()
{
// Do domain specific stuff here
// and use the service to help
_service.HelpMeDoStuff();
}
}
This uses classic constructor injection and works best when you already use dependency injection in your application, though it works perfectly well with factories as well.
The point is to keep responsibilities crystal clear. There's no chance of anybody invoking anything they shouldn't because the 'DomainObject' never knows what concrete type implements the shared service. The shared service is not exposed on the domain object either. The added bonus is testability and the possibility of swapping the service with another implementation without ever needing to touch the DomainObject.

Encapsulation VS Inheritance - How to use a protected function?

In OOP languages like C# or VB.NET, if I make the properties or methods in a super class protected I can't access them in my Form - they can only be accessed in my class that inherits from that super class.
To access those properties or methods I need to make them public, which defeats encapsulation, or re-write them into my class, which defeats inheritance.
What is the right way to do this?
If you have code which needs to ask an Class to perform a specific operation but the class does not present your code with a means to do that then the Class doesn't fulfill you codes requirements.
Its bit like saying I've got a Car (Automobile) that has a protected steering wheel so I can't access it. The car is no use to me.
Either make those members Public (or at least internal) and use them or ditch the class and use one that gives your consuming code the features it needs.
Perhaps what you are really looking for is an interface. The interface contains the members your code needs and you implement that interface on your class. The advantage here is that your class can determine that the members are being accessed via this Interface rather than an inheriting subclass.
"need to make them public which defeats encapsulation"
Don't conflate good design with the icky visibility rules. The visibility rules are confusing. There are really two orthogonal kinds of visibility -- subclass and client. It's not perfectly clear why we'd ever conceal anything from our subclasses. But we can, with private.
Here's what's important. Encapsulation does not mean hiding. Protected and private are not an essential part of good encapsulation. You can do good design with everything being public (that's the way Python works, for example).
The protected/private stuff is -- mostly -- about intellectual property management: are you willing to commit (in a legally binding, "see-you-in-court-if-it-doesn't-work" way) to an interface? If your software development involves lawyers, then you care about adding protect and private to the things you're not committed to.
If you don't have to cope with lawyers, consider doing encapsulation right but leave everything public.
Sorry, it's not clear what you mean by "in my Form" - what is the relationship between your Form and your two classes? If your classes are controls in the same project, and you want to access properties from the form, you should use the 'internal' keyword.
There are at least three ways you can limit who can use some particular instance method of particular class instances:
Define the method as `protected`, `internal`, or `private`. In the first case, an instance method will only be usable from within derived-class methods of the same instance; in the second case, all classes within the assembly will have access to those methods, but classes outside won't; in the third case, no outside classes, even derived ones in the same assembly, will have access, unless their code is nested within the declaring class.
Define the method as `public`, but have the classes that create instances keep them private and never expose them to the outside world. Anyone wanting to invoke an instance method on an object has to have an instance to invoke it on. If a class holds instances but never exposes direct references to them, the only instance methods that can ever be used on those instances will be those which the holding classes uses itself.
Define the method as `public`, but have a constructor which accepts a location into which one or more delegates to private methods may be stored. Code with access to those delegates will be able to call the methods referred to thereby, but other code will not (except by using Reflection in ways which I think are only usable in full-trust scenarios).
If Reflection in non-full-trust scenarios would allow unbound delegates to be bound to arbitrary object instances, one could use nested classes to reinforce #3 so that one would have to access private fields to gain illegitimate access to the private functions; that would definitely be forbidden outside full-trust scenarios.

Practical uses for the "internal" keyword in C#

Could you please explain what the practical usage is for the internal keyword in C#?
I know that the internal modifier limits access to the current assembly, but when and in which circumstance should I use it?
Utility or helper classes/methods that you would like to access from many other classes within the same assembly, but that you want to ensure code in other assemblies can't access.
From MSDN (via archive.org):
A common use of internal access is in component-based development because it enables a group of components to cooperate in a private manner without being exposed to the rest of the application code. For example, a framework for building graphical user interfaces could provide Control and Form classes that cooperate using members with internal access. Since these members are internal, they are not exposed to code that is using the framework.
You can also use the internal modifier along with the InternalsVisibleTo assembly level attribute to create "friend" assemblies that are granted special access to the target assembly internal classes.
This can be useful for creation of unit testing assemblies that are then allowed to call internal members of the assembly to be tested. Of course no other assemblies are granted this level of access, so when you release your system, encapsulation is maintained.
If Bob needs BigImportantClass then Bob needs to get the people who own project A to sign up to guarantee that BigImportantClass will be written to meet his needs, tested to ensure that it meets his needs, is documented as meeting his needs, and that a process will be put in place to ensure that it will never be changed so as to no longer meet his needs.
If a class is internal then it doesn't have to go through that process, which saves budget for Project A that they can spend on other things.
The point of internal is not that it makes life difficult for Bob. It's that it allows you to control what expensive promises Project A is making about features, lifetime, compatibility, and so on.
Another reason to use internal is if you obfuscate your binaries. The obfuscator knows that it's safe to scramble the class name of any internal classes, while the name of public classes can't be scrambled, because that could break existing references.
If you are writing a DLL that encapsulates a ton of complex functionality into a simple public API, then “internal” is used on the class members which are not to be exposed publicly.
Hiding complexity (a.k.a. encapsulation) is the chief concept of quality software engineering.
The internal keyword is heavily used when you are building a wrapper over non-managed code.
When you have a C/C++ based library that you want to DllImport you can import these functions as static functions of a class, and make they internal, so your user only have access to your wrapper and not the original API so it can't mess with anything. The functions being static you can use they everywhere in the assembly, for the multiple wrapper classes you need.
You can take a look at Mono.Cairo, it's a wrapper around cairo library that uses this approach.
Being driven by "use as strict modifier as you can" rule I use internal everywhere I need to access, say, method from another class until I explicitly need to access it from another assembly.
As assembly interface is usually more narrow than sum of its classes interfaces, there are quite many places I use it.
I find internal to be far overused. you really should not be exposing certain functionailty only to certain classes that you would not to other consumers.
This in my opinion breaks the interface, breaks the abstraction. This is not to say it should never be used, but a better solution is to refactor to a different class or to be used in a different way if possible. However, this may not be always possible.
The reasons it can cause issues is that another developer may be charged with building another class in the same assembly that yours is. Having internals lessens the clarity of the abstraction, and can cause problems if being misused. It would be the same issue as if you made it public. The other class that is being built by the other developer is still a consumer, just like any external class. Class abstraction and encapsulation isnt just for protection for/from external classes, but for any and all classes.
Another problem is that a lot of developers will think they may need to use it elsewhere in the assembly and mark it as internal anyways, even though they dont need it at the time. Another developer then may think its there for the taking. Typically you want to mark private until you have a definative need.
But some of this can be subjective, and I am not saying it should never be used. Just use when needed.
This example contains two files: Assembly1.cs and Assembly2.cs. The first file contains an internal base class, BaseClass. In the second file, an attempt to instantiate BaseClass will produce an error.
// Assembly1.cs
// compile with: /target:library
internal class BaseClass
{
public static int intM = 0;
}
// Assembly1_a.cs
// compile with: /reference:Assembly1.dll
class TestAccess
{
static void Main()
{
BaseClass myBase = new BaseClass(); // CS0122
}
}
In this example, use the same files you used in example 1, and change the accessibility level of BaseClass to public. Also change the accessibility level of the member IntM to internal. In this case, you can instantiate the class, but you cannot access the internal member.
// Assembly2.cs
// compile with: /target:library
public class BaseClass
{
internal static int intM = 0;
}
// Assembly2_a.cs
// compile with: /reference:Assembly1.dll
public class TestAccess
{
static void Main()
{
BaseClass myBase = new BaseClass(); // Ok.
BaseClass.intM = 444; // CS0117
}
}
source: http://msdn.microsoft.com/en-us/library/7c5ka91b(VS.80).aspx
Saw an interesting one the other day, maybe week, on a blog that I can't remember. Basically I can't take credit for this but I thought it might have some useful application.
Say you wanted an abstract class to be seen by another assembly but you don't want someone to be able to inherit from it. Sealed won't work because it's abstract for a reason, other classes in that assembly do inherit from it. Private won't work because you might want to declare a Parent class somewhere in the other assembly.
namespace Base.Assembly
{
public abstract class Parent
{
internal abstract void SomeMethod();
}
//This works just fine since it's in the same assembly.
public class ChildWithin : Parent
{
internal override void SomeMethod()
{
}
}
}
namespace Another.Assembly
{
//Kaboom, because you can't override an internal method
public class ChildOutside : Parent
{
}
public class Test
{
//Just fine
private Parent _parent;
public Test()
{
//Still fine
_parent = new ChildWithin();
}
}
}
As you can see, it effectively allows someone to use the Parent class without being able to inherit from.
When you have methods, classes, etc which need to be accessible within the scope of the current assembly and never outside it.
For example, a DAL may have an ORM but the objects should not be exposed to the business layer all interaction should be done through static methods and passing in the required paramters.
A very interesting use of internal - with internal member of course being limited only to the assembly in which it is declared - is getting "friend" functionality to some degree out of it. A friend member is something that is visible only to certain other assemblies outside of the assembly in which its declared. C# has no built in support for friend, however the CLR does.
You can use InternalsVisibleToAttribute to declare a friend assembly, and all references from within the friend assembly will treat the internal members of your declaring assembly as public within the scope of the friend assembly. A problem with this is that all internal members are visible; you cannot pick and choose.
A good use for InternalsVisibleTo is to expose various internal members to a unit test assembly thus eliminating the needs for complex reflection work arounds to test those members. All internal members being visible isn't so much of a problem, however taking this approach does muck up your class interfaces pretty heavily and can potentially ruin encapsulation within the declaring assembly.
As rule-of-thumb there are two kinds of members:
public surface: visible from an external assembly (public, protected, and internal protected):
caller is not trusted, so parameter validation, method documentation, etc. is needed.
private surface: not visible from an external assembly (private and internal, or internal classes):
caller is generally trusted, so parameter validation, method documentation, etc. may be omitted.
Noise reduction, the less types you expose the more simple your library is.
Tamper proofing / Security is another (although Reflection can win against it).
Internal classes enable you to limit the API of your assembly. This has benefits, like making your API simpler to understand.
Also, if a bug exists in your assembly, there is less of a chance of the fix introducing a breaking change. Without internal classes, you would have to assume that changing any class's public members would be a breaking change. With internal classes, you can assume that modifying their public members only breaks the internal API of the assembly (and any assemblies referenced in the InternalsVisibleTo attribute).
I like having encapsulation at the class level and at the assembly level. There are some who disagree with this, but it's nice to know that the functionality is available.
One use of the internal keyword is to limit access to concrete implementations from the user of your assembly.
If you have a factory or some other central location for constructing objects the user of your assembly need only deal with the public interface or abstract base class.
Also, internal constructors allow you to control where and when an otherwise public class is instantiated.
I have a project which uses LINQ-to-SQL for the data back-end. I have two main namespaces: Biz and Data. The LINQ data model lives in Data and is marked "internal"; the Biz namespace has public classes which wrap around the LINQ data classes.
So there's Data.Client, and Biz.Client; the latter exposes all relevant properties of the data object, e.g.:
private Data.Client _client;
public int Id { get { return _client.Id; } set { _client.Id = value; } }
The Biz objects have a private constructor (to force the use of factory methods), and an internal constructor which looks like this:
internal Client(Data.Client client) {
this._client = client;
}
That can be used by any of the business classes in the library, but the front-end (UI) has no way of directly accessing the data model, ensuring that the business layer always acts as an intermediary.
This is the first time I've really used internal much, and it's proving quite useful.
There are cases when it makes sense to make members of classes internal. One example could be if you want to control how the classes are instantiated; let's say you provide some sort of factory for creating instances of the class. You can make the constructor internal, so that the factory (that resides in the same assembly) can create instances of the class, but code outside of that assembly can't.
However, I can't see any point with making classes or members internal without specific reasons, just as little as it makes sense to make them public, or private without specific reasons.
the only thing i have ever used the internal keyword on is the license-checking code in my product ;-)
How about this one: typically it is recommended that you do not expose a List object to external users of an assembly, rather expose an IEnumerable. But it is lot easier to use a List object inside the assembly, because you get the array syntax, and all other List methods. So, I typically have a internal property exposing a List to be used inside the assembly.
Comments are welcome about this approach.
Keep in mind that any class defined as public will automatically show up in the intellisense when someone looks at your project namespace. From an API perspective, it is important to only show users of your project the classes that they can use. Use the internal keyword to hide things they shouldn't see.
If your Big_Important_Class for Project A is intended for use outside your project, then you should not mark it internal.
However, in many projects, you'll often have classes that are really only intended for use inside a project. For example, you may have a class that holds the arguments to a parameterized thread invocation. In these cases, you should mark them as internal if for no other reason than to protect yourself from an unintended API change down the road.
The idea is that when you are designing a library only the classes that are intended for use from outside (by clients of your library) should be public. This way you can hide classes that
Are likely to change in future releases (if they were public you would break client code)
Are useless to the client and may cause confusion
Are not safe (so improper use could break your library pretty badly)
etc.
If you are developing inhouse solutions than using internal elements is not that important I guess, because usually the clients will have constant contact with you and/or access to the code. They are fairly critical for library developers though.
When you have classes or methods which don't fit cleanly into the Object-Oriented Paradigm, which do dangerous stuff, which need to be called from other classes and methods under your control, and which you don't want to let anyone else use.
public class DangerousClass {
public void SafeMethod() { }
internal void UpdateGlobalStateInSomeBizarreWay() { }
}

Categories

Resources