Constructor in an Interface - delphi

I know - I cannot, but.
I want all classes who will implement my interface to have the same owner (usually defined in constructor). What is the best practice to do that?
Should I use some base abstract class or something like this?

An interface defines a contract between implementor and consumer.
Part of that contract is enforced by the compiler. For example, that all implementations of the interface have the requisite functions of particular names, which take specific parameters.
But there is another part of an interface that is not enforced by the compiler. That's the part of the contract that is described in the interface documentation. You could decide that it suffices to tell all implementors what rules they must abide by. Many libraries take that stance. The Windows API is one prominent example.
If you are dead set on enforcement through code then an interface cannot help. You need something that expresses the constraint in code and in this case that's going to require implementation. Which means you would need to use a class. An (almost) abstract base class could get it done. The only concrete part of the class would enforce the ownership constraint. The rest of the class would be a series of abstract virtual methods. That's not an interface in the sense implied by the Delphi keyword. However, it's an interface in semantic terms.

Of course you can choose to implement the interface in a common ancestor, or at least have a common ancestor for the classes that implement the interface. However, you cannot enforce this through the interface. An interface has no constructor and an interface cannot enforce which class can or cannot implement it.
I think the best option would be to expose an Owner property through the interface. That way, you can at least get the owner through the interface, and you will enforce the implementing classes to at least implement that property. B.t.w, an interface is allowed to have properties and methods that return objects or have object parameters.

Related

what is the main purpose technically speaking about the abstraction in programming using DI, Interfaces, and Abstract Classes? [closed]

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 months ago.
Improve this question
I viewed a couple of answers online regarding Abstractions, Abstract Classes, Interface's, DI, and Loose coupling. But none of these answers are answering my question. I grouped these topics because they are related to achieving abstractions. Got a good understanding of the mentioned topics, but yet not fully understand them in detail and how they related to each other.
Generally speaking, interfaces are used to make classes loosely coupled. Thus define a set of functions and fields to be implemented. The idea of making Loosely Coupled classes is that will need to remove dependency over several classes.
For instance, if we make a change to one of these classes then we do not need to change other places making code maintainable. The only good example I can think of to use loosely coupling is through DI. So when we say interfaces make classes loosely coupled do we mean by passing an interface as a dependency?
"Please continue reading will further clarify".
A question here is if we are going to use DI and pass interfaces as dependencies then why not pass a class as a dependency instead? maybe I will need further clarification about Interfaces before answering the previous question. I will further explain.
The main idea of interfaces is to establish contact with classes that going to implement the interface meaning we are going to need to define functions and fields to enforce to implement them. but still, the idea of interfaces as a contract is not yet clear because if we enforce a developer to implement an interface called a server that has methods to turn on and off the server but the developer forgot to turn off the server programmatically then what is the point of this contract?
Further, my understanding is that this all falls under the concept of abstraction which means we do not need to worry about details but an abstraction. Does that not mean when building an application we first need to create classes/structures without code such as using UML?
Further, why would we use an abstract class over interfaces where an abstract class has similarities to an interface such as defining a function but without a body?
Coming back to Interfaces and DI we can inject interfaces as a dependency but why? Can we not inject a class it self? is it not easier to use classes as a dependency? where we can access all functions or this is not the idea of interface Can sombody help with this. I only understand one use case on why we should use DI. Example:
//Class1
//Class1 Con
Public Class1 Con(){
Class2 class2 = new Class2(1,1,1)
}
The above example is not maintainable because if we add a new parameter to Class2 then we need to modify it elsewhere. but if we use DI Injection then we won't are there any other reasons.
Also, DI can be useful to create one instance and use that instance across the whole application. Does that save some memory by not creating multiple instances? or saving time connecting to DI?
The question should we use abstractions at the very early coding stage where we create classes without code?
Further, do we use interfaces to make the developer aware that they need to implement a certain set of functions? But why?
Do I predict that we need to use an interface by creating UML diagrams to see if there would be different classes to use an interface with similar functionalities
"Can we not just create a superclass and override methods"
Can somebody explain when to use superclass and override methods over interfaces and provide an implementation?
Also, when to pass an interface as a dependency? And when to pass a class as a dependency? One advantage I can think of when using interfaces is polymorphism where we can make an interface of any implemented types and then access the interface type function; polymorphism. Example:
Class1 class = new Interface1();
Can this be possible?
Bottom line is we would like always to make our class's loosely coupled. Meaning that decouple class's to achieve maintainable. Thus, loosely coupled classes provider's late binding, extensibility, maintainability and easy testing. May refer to reference 1. We use interface's to make class's loosely coupled as well. but before answering how. we need to understand interface's why we use them and how they are different to abstract class's. Interface's are mainly used as contract meaning that when we create multiple class's sharing same behaviour but with different implementation then we use interface's. Thus, its a set of infrastructure to tell developer's what method's to implement. interface's only includes functions, fields signature with no implementation.
How we use DI to achieve loosely coupled class's is by injecting dependencies. suppose the following class's implements interface called Database:
public interface Database
{
void Save();
}
class SqlServer : Database
{
public void Save()
{
Console.WriteLine("Saving...");
}
}
class Oracle : Database
{
public void Save()
{
Console.WriteLine("Saving...");
}
}
Then we can easily inject dependencies as follows:
class Library
{
//private Database _SqlServer;
private Database _Oracle;
public Student(IDAL _SqlServer)
{
this._SqlServer = _SqlServer;
}
public void SaveBoo()
{
_SqlServer.Save();
}
}
Using the above approach we are injecting dependencies meaning that class's are now not fully tightly coupled. if any change made to _SqlServer we do not have to worry. To achieve full decoupled class's then use DI container Refer to reference 1.
The difference between abstract class's and interface's is that we use interface to define a contract where we use abstract if we want partial implementation. In Abstract class's you can define some method's implementation while leaving other as abstract.
You may create UML class diagrams to represent class's relationship without the need to worry about the coding side yet
As I am replying to my own question I would think it’s good to create classes and relationship I will call it classes structure then do all code later in case UML Class diagram is not going to be used. I guess this will fall under the technique/concept that is called abstraction where we do not yet worry about the details yet. So we can have an image about how is the application is structured without using UML’s.
Hope make sense
References:
(https://findnerd.com/account/#url=/list/view/Dependency-Injection-in--Net/24098/)

Encapsulation - Why I am using getter setter to make my data members public if I already declare them private in class

I just want to ask, we are having one class, in which we have two private data members say:
class Employee{
private int empid;
private String empname;
}
I am declaring them private that means I can use them in Employee class only. So what is the need to create getter setter for both the data members and making them public.
Hope you got my problem.
This is an excellent question. Often you see code examples that make members private but exposing them via a getter/setter pair, without the getter/setter doing anything else than setting the corresponding member.
In my book this is not encapsulation at all. You are no better of than just making the members public. Although a lot of people are uneasy to do that, they would happily provide accessors automatically for all their members.
One reason to do provide accessors is the ability to do input validation. E.g. if you empIds have a checksum, you could enforce it in the setter. Something that is not possible with direct access to the member.
In my opinion it would be better to think about the role this object will play and see how it can achieve that role with a minimum of accessors. Otherwise your code will probably violate the Law of Demeter.
You are absolutely right, that creating a setter/getter or making the fields public both violate encapsulation in the same way, therefore if you do want to encapsulate your private fields, presumably because you are working in an Object-Oriented environment, you do not want to use either of those things.
To your question why there is a need to have create setter/getters: Most projects (consciously or unconsciously) do not base their designs on Object-Orientation. There are other paradigms, where data and function are separated, thus encapsulation plays a minor role if any.
In the Java world it is common to have pure (or very close to pure) data structures (Beans), and Services/Components/EJBs/etc that work on these Beans (have access to all fields basically). Often these architectures split the function part further into topics like Presentation, Business, Persistence (3-tier architectures), or create explicit control procedures that has access to all the relevant fields (like how MVC is often done).
Whether one approach is better than the other would be a subjective discussion probably, but the short answer is: It's a different paradigm usually (not OO), that is why setters/getters get created.

protected virtual methods in f#

F# does not support the definition of protected methods. Here it is explained why
F# replaces virtualmethods with abstractmethods defined in abstract classes (see here).
I was wondering if there is a way to prevent access to abstract methods from outside the derived classes at all.
Like Patryk Ćwiek, I also don't think it's possible, but here's one alternative:
From Design Patterns we know that we should favour Composition over Inheritance. In my experience, everything you can do with Inheritance, you can also do with Composition. As an example, you can always replace Template Method with a Strategy.
A Template Method is a typical use of an abstract method, but if you replace it with a Strategy, you can (sort of) hide it from clients:
type Foo(strategy : IBar) =
member this.CreateStuff() =
// 1. Do something concrete here
// 2. Use strategy for something here
// 3. Do something else concrete here
// 4. Return a result
No outside client of Foo can invoke strategy, so that accomplishes the same goal as making a member protected.
You may argue that the original creator of Foo may keep a reference to strategy, and will still be able to invoke it. That's true, but protected members aren't really completely hidden either, because you can often derive from the class in question, which enables you to invoke the protected member.
Another point is that if you separate the creator of Foo from the client of Foo, the strategy will be unavailable to the client.

What is the best strategy for Dependency Injection of User Input?

I've used a fair amount of dependency injection, but I'd like to get input on how to handle information from the user at runtime.
I have a class that connects to a com port. I allow the user to select the com port number. Right now, I have that com port parameter as a constructor argument. The reasoning being that the class cannot function without that information, and it's implementation specific (a mock version of this class wouldn't need a com port).
The alternative is to have a "Start" method that takes in the com port, or have a property that sets the com port. This makes it very compatible with an IoC container, but it doesn't necessarily make sense from the perspective of the class.
It seems like the logical route conflicts with the dependency injection design, but it's because my UI is getting information for a specific type of class.
Other alternatives would include using an IoC container that lets me pass in additional constructor parameters, or just constructing the classes I need at the top level without using dependency injection.
Is there a generally accepted standard pattern for this type of problem?
There are two routes you can take, depending on your needs.
1. Wire the UI directly to your concrete classes
This is the simplest option, but many times perfectly acceptable. While you may have a Domain Model with lots of interfaces and use of DI, the UI constitutes the Composition Root of the object graphs, and you could simply wire up your concrete class here, including your required port number parameter.
The upside is that this approach is simple and easy to understand and implement.
The downside is that you get less flexibility. You will not be able to arbitrarily replace one implementation with another (but then again, you may not need that flexibility).
Even with the UI locked to a concrete implementation, this doesn't mean that the Domain Model itself wouldn't be reusable in other applications.
2. Add an Abstract Factory
The other option is to add another layer of indirection. Instead of having your UI create the class directly, it could use an Abstract Factory to create the instance.
The factory's Create method could take the port number as an input, so this abstraction belongs best in a UI sub-layer.
public abstract class MyFactory
{
public abstract IMyInterface Create(int portNumber);
}
You could then have your DI container wire up an implementation of this factory that uses the port number and passes it as a constructor argument to your real implementation. Other factory implementations may simply ignore the parameter.
The advantage of this approach is that you don't pollute your API (or your concrete implementations), and you still have the flexibility that programming to interfaces give you.
The disadvantage is that it adds yet another layer of indirection.
Most IoC containers have some form of Constructor Injection that would allow your IoC container to pass a mocked COM port into your class for unit testing. That seems like the most clean solution.
I would avoid adding a "Start" method, etc. Its much better practice to (when possible) always have your classes in a valid state, and switching to a parameterless constructor with a start method leaves your class invalid between those calls. Doing this to enable testing is just making your class more difficult in order to test (which should make it nicer).

Practical Singleton & Dependency Injection question

Say I have a class called PermissionManager which should only exist once for my system and basically fulfills the function of managing various permissions for various actions in my application. Now I have some class in my application which needs to be able to check a certain permission in one of its methods. This class's constructor is currently public, i.e. used by API users.
Until a couple of weeks ago, I would have simply had my class call the following pseudo-code somewhere:
PermissionManager.getInstance().isReadPermissionEnabled(this)
But since I have noticed everyone here hating singletons + this kind of coupling, I was wondering what the better solution would be, since the arguments I have read against singletons seem to make sense (not testable, high coupling, etc.).
So should I actually require API users to pass in a PermissionManager instance in the constructor of the class? Even though I only want a single PermissionManager instance to exist for my application?
Or am I going about this all wrong and should have a non-public constructor and a factory somewhere which passes in the instance of PermissionManager for me?
Additional info Note that when I say "Dependency Injection", I'm talking about the DI Pattern...I am not using any DI framework like Guice or Spring. (...yet)
If you are using a dependency-injection framework, then the common way to handle this is to either pass in a PermissionsManager object in the constructor or to have a property of type PermissionsManager that the framework sets for you.
If this is not feasible, then having users get an instance of this class via factory is a good choice. In this case, the factory passes the PermissionManager in to the constructor when it creates the class. In your application start-up, you would create the single PermissionManager first, then create your factory, passing in the PermissionManager.
You are correct that it is normally unwieldy for the clients of a class to know where to find the correct PermissionManager instance and pass it in (or even to care about the fact that your class uses a PermissionManager).
One compromise solution I've seen is to give your class a property of type PermissionManager. If the property has been set (say, in a unit test), you use that instance, otherwise you use the singleton. Something like:
PermissionManager mManager = null;
public PermissionManager Permissions
{
if (mManager == null)
{
return mManager;
}
return PermissionManager.getInstance();
}
Of course, strictly speaking, your PermissionManager should implement some kind of IPermissionManager interface, and that's what your other class should reference so a dummy implementation can be substituted more easily during testing.
You can indeed start by injecting the PermissionManager. This will make your class more testable.
If this causes problems for the users of that class you can have them use a factory method or an abstract factory. Or you can add a parameterless constructor that for them to call that injects the PermissionManager while your tests use another constructor that you can use to mock the PermissionManager.
Decoupling your classes more makes your classes more flexible but it can also make them harder to use. It depends on the situation what you'll need. If you only have one PermissionManager and have no problem testing the classes that use it then there's no reason to use DI. If you want people to be able to add their own PermissionManager implementation then DI is the way to go.
If you are subscribing to the dependency injection way of doing things, whatever classes need your PermissionManager should have it injected as an object instance. The mechanism that controls its instantiation (to enforce the singleton nature) works at a higher level. If you use a dependency injection framework like Guice, it can do the enforcement work. If you are doing your object wiring by hand, dependency injection favors grouping code that does instantiation (new operator work) away from your business logic.
Either way, though, the classic "capital-S" Singleton is generally seen as an anti-pattern in the context of dependency injection.
These posts have been insightful for me in the past:
Using Dependency Injection to Avoid Singletons
How to Think About the "new" Operator with Respect to Unit Testing
So should I actually require API users to pass in a PermissionManager instance in the constructor of the class? Even though I only want a single PermissionManager instance to exist for my application?
Yes, this is all you need to do. Whether a dependency is a singleton / per request / per thread or a factory method is the responsibility of your container and configuration. In the .net world we would ideally have the dependency on an IPermissionsManager interface to further reduce coupling, I assume this is best practice in Java too.
The singleton pattern is not bad by itself, what makes it ugly is the way it's commonly used, as being the requirement of only wanting a single instance of a certain class, which I think it's a big mistake.
In this case I'd make PermissionManager a static class unless for any reason you need it to be an instanciable type.

Resources