I can't figure out what a <<use>> or <<create>> relationship looks like in program code? Can someone give me an example?
Thanks
The «Create» dependency says that an object of one class creates instances of another one. A typical example is the factory pattern. The wikipedia article shows both the UML class diagram with create dependency and an example code.
The «use» dependency tells that objects of one class uses instances of another class and therefore need to know about that other class. This other SO answer explains all the details. A typical example is when that some operations (methods) have parameters of the type of the other class:
class B { ... }
class A {
public doSomething(B b) { ... }
}
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.
I know that ABAP Objects are kinda old but as far as my knowledge goes you still have to use at least two "sections" to create a complete class.
ABAP:
CLASS CL_MYCLASS DEFINITION.
PUBLIC SECTION.
...
PROTECTED SECTION.
...
PRIVATE SECTION.
...
ENDCLASS.
CLASS CL_MYCLASS IMPLEMENTATION.
...
ENDCLASS.
Java:
public class MyClass {
<visibility> <definition> {
<implementation>
}
}
Wouldn't it make development easier/faster by having a combination of both like most modern languages have?
What are the reasons for this separation?
Easier/faster for the human (maybe), but costly for the compiler: It has to sift through the entire code to determine the structure of the class and its members, whereas in the current form, it only needs to compile the definition to determine whether a reference is valid. ABAP is not the only language that separates definition from implementation: Pascal did so for units, and Object Pascal for classes. One might argue that C++ allows for same construct without specifying an implementation section when you're not using inline member function declarations.
Maybe another reason:
Most (?) classes are not defined with manual written code, but via SE24. There you define the interface in one dynpro and write the code in another one.
Internally the interfaces are stored in one source, the code is stored in another source. So it is reasonable to separate the interface and the implementation.
Let's say I have a Swing GUI that has to display a certain type of information in two different ways. From a design patterns perspective one would probably use the Strategy pattern here: create an interface that defines how the communication between the display component and the client works like this:
public interface Foo {
void showData(Data bar)
}
The real action is then done by different components that implement Foo and can be created and plugged in for doing the real work.
Now, what happens, if the real components are java.awt.Components? As I see it, it results in a mess of type casts because Component is a class. Let's assume an implementation like this one:
public class Baz extends Component implements Foo {
...
}
If I want to pass objects of class Baz around, the methods can either use "Component" as the parameter type or "Foo". The problem is that some methods need objects that are both Component and Foo (e.g. because they add the object to a JPanel and then supply the data calling the interface method showData()).
As I see it I have some choices to make this happen:
I can pass the reference as Component and cast to Foo. Before, I have to check that the reference is an instance of Foo and I have to handle situations where this requirement is not met. Another problem is that I have to communicate to clients of the method that the Component passed also has to implement Foo, which is awkward and error-prone.
I can do the same thing with Foo
I can add a method "Component getComponent()" to the Foo interface and the implementation would always return "this". This boilerplate method could be put into an abstract sub-class of Component. This solution means an interface method I don't want and an additional sub-class I don't need.
I can pass two references, one Component and one Foo reference to the same object. Internally, I'd have to make sure, though, that both references belong to the same object. And I have to deal with situations in which this requirement is not met.
I can use an abstract sub-class of Component and define the interface using abstract methods. This would allow me to pass references in a type-safe manner, but break with good OOP practices: keeping interfaces and implementations separate and also the interface segregation principle.
So, all of these solutions are merely workarounds. Is there any solution I'm missing? What should I do?
I would use the Strategy design pattern as you mentioned, but perhaps in a different context. The problem with trying to "shoe-horn" both Foo and Component into one class is that you could have combinations of implementations that would require duplicating code.
For example, imagine you have the following implementations of Component:
(Its been too long since Ive used Swing, these classes may not exist)
JPanel
JButton
JMenu
And you also had the following implementations of Foo
MyFoo
HisFoo
OurFoo
WhatTheFoo
And Imagine all the combinations of those: that's whats called a class explosion. This is the classic justification for the Strategy pattern.
I would create a sort of container class that uses a HAS-A relationship for each of the needed classes instead of using the IS-A relationship as follows:
(Im a c++ programmer, so you'll have to excuse the hybrid code :)
class ComponentFooHandler {
Component component_;
Foo fooImpl_;
inline Foo getFoo() {return fooImpl_;}
void setFoo(Foo f) {fooImpl_ = f;}
Component getComponent() {return component_;}
void setComponent(Component c) {component_ = c;}
void doAction() {
component_.someAction();
fooImpl_.anotherAction();
}
}
You would then have to create different implementations of Foo seperately. Then the Component and Foo implementations can be combined as needed with out having to duplicate Foo impl code. Notice also that you can call methods that like doAction() that can operate on both Foo and Component without knowing their details, similar to a Template Pattern.
To solve the issues with your original question:
When a Component is needed, call getComponent() on a handler instance
When a Foo is needed, call getFoo() on a handler instance
I would avoid creating methods that need both in one and split the method args into 2
Or just consider passing around a ComponentFooHandler
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.
I am going over some OO basics and trying to understand why is there a use of Interface reference variables.
When I create an interface:
public interface IWorker
{
int HoneySum { get; }
void getHoney();
}
and have a class implement it:
public class Worker : Bee, IWorker
{
int honeySum = 15;
public int HoneySum { get { return honeySum; } }
public void getHoney()
{
Console.WriteLine("Worker Bee: I have this much honey: {0}", HoneySum);
}
}
why do people use:
IWorker worker = new Worker();
worker.getHoney();
instead of just using:
Worker worker3 = new Worker();
worker3.getHoney();
whats the point of a interface reference variable when you can just instatiate the class and use it's methods and fields that way?
If your code knows what class will be used, you are right, there is no point in having an interface type variable. Just like in your example. That code knows that the class that will be instantiated is Worker, because that code won't magically change and instantiate anything else than Worker. In that sense, your code is coupled with the definition and use of Worker.
But you might want to write some code that works without knowing the class type. Take for example the following method:
public void stopWorker(IWorker worker) {
worker.stop(); // Assuming IWorker has a stop() method
}
That method doesn't care about the specific class. It would handle anything that implements IWorker.
That is code you don't have to change if you want later to use a different IWorker implementation.
It's all about low coupling between your pieces of code. It's all about maintainability.
Basically it's considered good programming practice to use the interface as the type. This allows different implementations of the interface to be used without effecting the code. I.e. if the object being assigned was passed in then you can pass in anything that implements the interface without effecting the class. However if you use the concrete class then you can only passin objects of that type.
There is a programming principle I cannot remember the name of at this time that applies to this.
You want to keep it as generic as possible without tying to specific implementation.
Interfaces are used to achieve loose coupling between system components. You're not restricting your system to the specific concrete IWorker instance. Instead, you're allowing the consumer to specify which concrete implementation of IWorker they'd like to use. What you get out of it is loosely dependent components and better flexibility.
One major reason is to provide compatibility with existing code. If you have existing code that knows how to manipulate objects via some particular interface, you can instantly make your new code compatible with that existing code by implementing that interface.
This kind of capability becomes particularly important for long-term maintenance. You already have an existing framework, and you typically want to minimize changes to other code to fit your new code into the framework. At least in the ideal case, you do this by writing your new code to implement some number of existing interfaces. As soon as you do, the existing code that knows how to manipulate objects via those interfaces can automatically work with your new class just as well as it could with the ones for which it was originally designed.
Think about interfaces as protocols and not classes i.e. does this object implement this protocol as distinct from being a protocol? For example can my number object be serialisable? Its class is a number but it might implement an interface that describes generally how it can be serialised.
A given class of object may actually implement many interfaces.