I have two different #Service classes that use the same methods.
I have extracted those methods in a separate class, that both will reference. To be able to access those methods, I added them to the companion object of the class, but the issue is that they use external services in their implementation, which I cannot wire in a companion object or pass it and access it there.
class CommonMethods {
companion object {
fun firstValidationField(input: User) {
// logic
input.timezone = userRepository.getTimezone(input.userId)
return input
}
etc
}
}
What is the best way to inject userRepository to this class so I can access it and have the common methods work for both external service classes?
I had these methods in the service class, so autowiring repositories there wasn't an issue. But extracting them as they are common, not sure how to approach this.
I use #Autowired to inject it
If firstValidationField() is really so simple as you wrote in the question, you can inject the userRepository in your both services, and userRepo.getTimeZone(..) that's it.
However, if the method impl. is more complex than that, or there are other commonly used methods, I would suggest wrapping those methods in an additional #service, say UserService, and inject the UserService into your other #services.
Usually, Util classes are not designed to be instantiated, it contains mainly static method calls. IMO, "Injecting" objects to a Util class isn't the right direction to go.
Related
I am trying to implement a NotificationService in a correct way from the point of view of OOP. For this I have the next interface:
abstract class NotificationsService {
void initNotificationsHandlers();
int sendGeneralNotification({String? title, String? body});
//...
}
And his subclass:
class FirebaseNotificationService extends NotificationsService {
//All implementations...
}
The problem is when I implement it. I have to instance it on the main:
NotificationsService notificationsService = new FirebaseNotificationService();
But I have to use this service in more classes,and I don't want to instance the FirebaseNotificationService in every class because I would be violating the Dependency Inversion Principle. I want other classes just know the abstraction NotificationsService.
I have thought using something like this:
abstract class NotificationsService {
///Current notification service subclass used.
static final NotificationsService instance;
//...
}
And then implementing the class this way:
Main
NotificationsService.instance = new FirebaseNotificationService();
Other class
NotificationsService.instance.initNotificationsHandlers(); // For example, it could be any method
But it doesn't look very clean because I am using the NotificationService interface to "save" the current subclass. I think it shouldn't be his responsibility.
Maybe should I make another class which "saves" the current implementation? Or apply a singleton pattern? What is the OOP most correct way to do this?
Clarification: I am not asking for a personal opinion (otherwise this question should be close). I'm asking about the correct OOP solution.
In which language are you programming? Java probably, by reading your Code.
What you actually want is Dependency Injection and a Singleton (even though I think that Singleton is overkill for a NotificationService)
If we remain at the Java Standard, it works in this way:
The classes that need your NotificationService would have a constructor annotated with #Inject and an agument of type NotificationService (not your Implementation Class) - so your consumer classes rely on something abstract rather than something concrete, which makes it easier to change the implementation.
The Dependency Injection Container or Framework would take care that when your classes are being injected by them self somewhere, that their Dependencies are being satisfied in order to be able to construct this class.
How does it actually know which Implementation belongs to an Interface?
Well it depends on the Framework or Platform you are using but you either define your bindings of the interface to the concrete class or is is looking it up with reflection (if we are using Java)
If a class gets injected with a new Instance every time or always the same instance this depends on your annotations on the class itself. For example you could annotate it with #Singleton.
I hope it helps a bit.
What is the difference between sealed and internal in Kotlin? I have read Kotlin's documentation on sealed classes and visibility modifiers; however, it is still not clear to me when to use sealed vs. internal. Maybe someone could provide real-world code samples?
Sealed classes | Kotlin & Visibility modifiers | Kotlin resources.
sealed class will be visible in all modules, but extendable only in the same module. This means if you have this:
sealed class MyClass {} then you can do this in the same module:
class MyExtensionClass: MyClass() {}
But you can't do the same thing in another module. But you can still use both MyClass and MyExtensionClass in another module.
For example you can do this in another module:
val x: MyClass = MyExtensionClass()
You can't instantiate a sealed class directly neither in the same or another module. This means you can't do this nowhere:
val x = MyClass()
So sealed class is basically an abstract class which can only be implemented in the same module.
internal class can be used and extended in the same module just like a sealed class, but you can do neither in another module. So you can't even use or instantiate it in another module. Also you can directly instantiate an internal class as long as you are doing it in the same module.
So: Use sealed to better control extending something. For example you create a library and you want a class from this library to be used but not extended. Use internal if you wan't your class to be invisible to other modules (you create a library, but certain class in this library shouldn't even be directly compile time usable by libraries users)
A good use case for sealed class:
You build a library and have some abstract class or interface which has multiple different implementations, but you want to make sure the libraries user doesn't add its own implementations (you wan't to be in control of implementation details).
A good use case for internal class:
You have some interface and a factory that creates implementations, but you don't want the implementing class to be compile-time visible to libraries users. They just use the factory and don't need to worry about the implementation. They might build their own implementation though and therefor not use the factory you provided and this is OK.
These are not mutually exclusive. You can have an internal sealed class as well.
internal is about visibility, and sealed is about inheritance rules.
internal means the class type is only visible within the module. In other modules, you can't even mention the name of the type.
sealed means it is open (can be subclassed), but subclasses (or implementations if it's a sealed interface) can only be defined in the same module, and the compiler keeps track of an exhaustive list of all subclasses. Another rule is that you can't create anonymous subclasses of it (object: MySealedClass). The advantage of a sealed type is that the compiler knows when you've exhaustively checked a type in when statements, if/else chains, etc. It can also be used in a library to ensure that only known implementations of a class or interface are ever passed to it (prevent users from creating subclasses of something and passing them into the library).
Bonus:
Visibility modifier keywords: public, internal, private, protected
Inheritance modifier keywords: open, final, sealed
data and value also cause a class to be final implicitly as a side effect.
I've read what the annotation says but I'm kinda dumb, so couldn't understand propertly
Identifies injectable constructors, methods, and fields. May apply to static as well as instance members. An injectable member may have any access modifier (private, package-private, protected, public). Constructors are injected first, followed by fields, and then methods. Fields and methods in superclasses are injected before those in subclasses. Ordering of injection among fields and among methods in the same class is not specified.
Can you explain me what is #Inject for? If it is possible with a real life analogy with something less abstract
#Inject is a Java annotation for describing the dependencies of a class that is part of Java EE (now called Jakarta EE). It is part of CDI (Contexts and Dependency Injection) which is a standard dependency injection framework included in Java EE 6 and higher.
The most notorious feature of CDI is that it allows you to inject dependencies in client classes. What do I mean by dependencies? It is basically what your class needs to do whatever it needs to do.
Let me give you an example so that it is easier to understand. Imagine that you have a class NotificationService that is supposed to send notifications to people in different formats (in this case, email and sms). For this, you would most probably like to delegate the actual act of sending the notifications to specialized classes capable of handling each format (let's assume EmailSender and SmsSender). What #Inject allows you to do is to define injection points in the NotificationService class. In the example below, #Inject instructs CDI to inject an EmailSender and SmsSender implementation objects via the constructor.
public class NotificationService {
private EmailSender emailSender;
private SmsSender smsSender;
#Inject
public NotificationService(EmailSender emailSender, SmsSender smsSender) {
this.emailSender = emailSender;
this.smsSender = smsSender;
}
}
It is also possible to inject an instance of a class in fields (field injection) and setters (setter injection), not only as depicted above in constructors.
One of the most famous JVM frameworks taking advantage of this dependency injection concept is Spring.
I have little doubt about adapter class. I know what's the goal of adapter class. And when should be used. My doubt is about class construction. I've checked some tutorials and all of them say that I should pass "Adaptee" class as a dependency to my "Adapter".
e.g.
Class SampleAdapter implements MyInterface
{
private AdapteeClass mInstance;
public SampleAdapter(AdapteeClass instance)
{
mInstance=instance;
}
}
This example is copied from wikipedia. As you can see AdapteeClass is passed to my object as dependency. The question is why? If I'm changing interface of an object It's obvious I'm going to use "new" interface and I won't need "old" one. Why I need to create instance of "old" class outside my adapter. Someone may say that I should use dependency injection so I can pass whatever I want, but this is adapter - I need to change interface of concrete class. Personally I think code bellow is better.
Class SampleAdapter implements MyInterface
{
private AdapteeClass mInstance;
public SampleAdapter()
{
mInstance= new AdapteeClass();
}
}
What is your opinion?
I would say that you should always avoid the new operator in a class when it comes to complex objects (except when the class is a Builder or Factory) to reduce coupling and make your code better testable. Off course objects like a List or Dictionary or value objects can be constructed inside a class method (which is probably the purpose of the class method!)
Lets say for example that your AdapteeClass is a Remote Proxy. If you want to use Unit Testing, your unit tests will have to use the real proxy class because there is no way to replace it in your unit tests.
If you use the first approach, you can easily inject a mock or fake into the constructor when running your unit test so you can test all code paths.
Google has a guide on writing testable code which describes this in more detail but some important points are:
Warning Signs for not testable code
new keyword in a constructor or at field declaration
Static method calls in a constructor or at field declaration
Anything more than field assignment in constructors
Object not fully initialized after the constructor finishes (watch out for initialize methods)
Control flow (conditional or looping logic) in a constructor
Code does complex object graph construction inside a constructor rather than using a factory or builder
Adding or using an initialization block
AdapteeClass can have one or more non-trivial constructors. In this case you'll need to duplicate all of them in your SampleAdapter constructor to have the same flexibility. Passing already constructed object is simpler.
I think creating the Adaptee inside the Adapter is limiting. What if some day you want to adapt a pre-existing instance?
To be honest though, I'd do both if at all possible.
Class SampleAdapter implements MyInterface
{
private AdapteeClass mInstance;
public SampleAdapter()
: base (new AdapteeClass())
{
}
public SampleAdapter(AdapteeClass instance)
{
mInstance=instance;
}
}
Let's assume you have an external hard drive with a regular USB port and you are trying to hook it up with a Mac which only has type-c ports. Yes, you can buy a new drive which has a type-c port but what about the data in it?
It's the same for the adapter pattern. There're times you initialize AdapteeClass with tons of flavors. When you do the conversion, you want to keep all the context.
Here's a Clone() implementation for my class:
MyClass^ Clone(){
return gcnew MyClass(this->member1, this->member2);
}
Now I have about 10 classes derived from MyClass. The implementation is the same in each case. Owing to the fact that I need to call gcnew with the actual class name in each case, I am required to create 10 nearly identical implementations of Clone().
Is there a way to write one single Clone() method in the base class which will serve all 10 derived classes?
Edit: Is there a way to invoke the constructor of a class via one of it's objects? In a way that will invoke the actual derived class constructor. Something like:
MyClass ^obj2 = obj1->Class->Construct(arg1, arg2);
I'm doing this on C++/CLI but answers from other languages are welcome.
In plain old C++, you can do this with compile-time polymorphism (the curiously-recurring template pattern). Assuming your derived classes are copyable, you can just write:
class Base
{
public:
virtual Base* Clone() const = 0;
//etc.
};
template <typename Derived>
class BaseHelper: public Base
{
//other base code here
//This is a covariant return type, allowed in standard C++
Derived * Clone() const
{
return new Derived(static_cast<Derived *>(*this));
}
};
Then use it like:
class MyClass: public BaseHelper<MyClass>
{
//MyClass automatically gets a Clone method with the right signature
};
Note that you can't derive from a class again and have it work seamlessly - you have to "design in" the option to derive again by templating the intermediate classes, or start re-writing Clone again.
Not in C++ that I'm aware of. As you say, you need to create an object of a different class in each implementation of Clone().
Hm, I think you can use Factory pattern here. I.e.:
MyClass Clone(){
return MyClassFactory.createInstance(this.getClass(), this.member1, this.member2, ...);
}
In the factory, you would have to create instance of subclass based on passed class type. So probably it has the same disadvantages as your approach.
I would suggest using copy constructors instead (as derived classes can call the base implementation's copy constructor as well) -- also handy, as it will be familiar territory for C++ programmers.
You might be able to create a single Clone method that uses reflection to call the copy constructor on itself in this instance.
Possibly also worth noting that Jeffrey Richter said in the Framework Design Guidelines book, "The ICloneable interface is an example of a very simple abstraction with a contract that was never explicitly documented. Some types implement this interface's Clone method so that it performs a shallow copy of the object, whereas some implementations perform a deep copy. Because what this interface's Clone method should do was never fully documented, when using an object with a type that implements ICloneable, you never know what you're going to get. This makes the interface useless" (emphasis mine)