How does an interface remove dependency from implementation? - java

I am reading Uncle Bob's Clean Architecture book. One of the main points throughout the book is that you should depend on abstractions, not on implementations.
For example, he mentions that the higher layers of the software shouldn't know anything from the lower layers (which I agree). He also points out that when a higher layer needs to communicate with a lower layer, the lower layer must implement an interface that the higher layer uses. For example, if the Use Case layer needs to call the Presenter layer, it should be done through an interface OutputBoundary that is implemented by the Presenter, so the Use Case layer does not depend on the presenter. If you do it without an interface, it is really bad because the Use Case layer is depending on the Presenter layer.
How is that true? If in the future the Presenter layer needs more or different data to be sent by the Use Cases, you not only will have to modify the Presenter, but the OutputBoundary Interface and the Use Cases as well. So no, the Use Cases are never completely independent from the Presenter.
If the Presenter changes the way he presents data just changing the body of the method, then the Use Case layer won't have to change anything. If the Presenter changes the way he presents data by changing the method declaration it won't matter if you have an interface or not, because you will have to modify the method call in the Use Case layer. In none of the two cases the use of an interface really matter.
Is there something that I am missing here? I know the uses of an interface, and I know that if you have or plan to have multiple presenters, then having them to implement a common interface would be the right way to go, but even so I can't see the independence from lower layers that he mentions on his books.

How is that true? If in the future the Presenter layer needs more or
different data to be sent by the Use Cases, you not only will have to
modify the Presenter, but the OutputBoundary Interface and the Use
Cases as well. So no, the Use Cases are never completely independent
from the Presenter.
If the presenter layer needs more or different data then the use cases layer must change to provide that data.
But, if you decide to make changes in the presentation layer, or replace it for a new technology, but the information is the same, you would not need to modify the Use cases layer.
Same idea with data access, you use interfaces so it depends on application instead of the other way around, and when you need to change the data access to use a different database technology, as long as your data access layer keeps implementing the same interfaces, you don't need to make changes in application.

Imagine that Radio is higher level of software, then Battery will be lower level of dependency. In real life, Radio does not have tight coupling to Duracell battery, you can use any battery you want.
Let me show an example in C# (sorry, I do not have installed Java editor, but code is really simple):
class Radio
{
private IBattery _battery;
public Radio(IBattery battery)
{
_battery = battery;
}
public void TurnOn()
{
_battery.GiveEnergy();
}
}
interface IBattery
{
void GiveEnergy();
}
class Duracell : IBattery
{
public void GiveEnergy()
{
}
}
and usage:
IBattery battery = new Duracell();
var radio = new Radio(battery);
radio.TurnOn();
Your higher level - Radio does not depend on implementation of lower level Battery.
So you can use any battery you want.

How is that true? If in the future the Presenter layer needs more or different data to be sent by the Use Cases, you not only will have to modify the Presenter, but the OutputBoundary Interface and the Use Cases as well. So no, the Use Cases are never completely independent from the Presenter.
The answer is yes and no
Yes it is true since all layers pointing inwards not outwards
which make the communication between layers based on interfaces/abstraction the application layer as example will implement all the code against the interface and not aware with the implementation of that interface but since the higher layer pointing inward so it will consume the interface of the lower layer then implement it which makes the answer yes
every layer by itself it depend on the one lower so Application depend on Core/Entities
and Infrastructure depend on application but here is the trick in your presentation layer you actually will use DI to point the implementation of every interface to that interface which will make them depend on each others only in the run time
in this image you could see the direction of each layer
If the Presenter changes the way he presents data just changing the body of the method , then the Use Case layer won't have to change anything.
yes since the data still the same coming from application layer but if the presentation layer required completely diff let's say View model then the application layer will have to change the data which might need a change in persistence / infrastructure layer which will lead to change in the interface in application layer which persistence / infrastructure will need to implement !!!
I Actually recommend you to watch this video for Jason Taylor
https://www.youtube.com/watch?v=dK4Yb6-LxAk
Let me know if you have any questions

Related

Do we really need ServiceFacade Design Pattern while consuming a web-service?

I wanted to know if ServiceFacade Design Pattern is really required while consuming a web-service.
http://soapatterns.org/design_patterns/service_facade
Any insight and code snippet would be really helpful.
Thanks in advance !!
The aim of the facade is to provide a forward (or client) facing endpoint, which in turn provides only what is needed for communication and hide anything which is behind it to the outside world.
Having a facade will allow you to abstract your behaviour without exposing it. It will also allow you to make changes without potentially affecting the endpoint itself. That depends on the type of changes obviously, but if you have some requirements which require some change in the logic it might be possible that the actual input and output of the service remain untouched.
If you where to do away with the service facade, any changes to the code might require your clients to update the code from their end, and those who, for some reason do not update might end up with a broken system or else you would have to cater for multiple versions.
Service Facade design pattern is not mandatory consuming a web-service. it is required when you don't want to expose core service contract changes.
How it works
You will define a core business service contract (CoreServiceContract)
You will define implementation for that contract (CoreServiceContractImpl)
You will define one service facade which is customer facing ( ServiceFacade )
This ServiceFacade holds the reference of contract - CoreServiceContract
You will invoke methods defined in CoreServiceContract through ServiceFacade. CoreServiceContract holds implementation of CoreServiceContractImpl
Advantages:
1) The Service Facade insulates the service definition from its implementation.
2) It is the way of decoupling the Web tier from the Business tier.
3) From a transactional point of view, the business service may implement his transaction scope or be part of the current transaction.
4) The contract of the Service Facade interface is oriented to be invoked by Web tier or client software, but methods of the contract should not be invoked
within the business implementation.
Have a look at this article for working code

MVC practices. Service within another service

Service1 injects Repository1. Service2 injects Repository2.
Suppose two different scenarios:
1)
Some method of Service2 needs to retrieve data from Repository1.
Should Service2 inject Service1 or Repository1 when both of them provide respective get() method?
2) Some method of Service1 at it's end should call another method from Service2. Is it a bad practice to inject Service2 to Service1 for such needs? Is it a good practice to use event listen techniques like AOP for such needs?
There are many factors to consider here when we talked about best practices.
As a good start, try to understand the concept of SOLID principles.
Generally, it is good to have multiple classes with very focused roles that calls the other rather than combining all functionalities in one class. High reusability and least code duplication which in turn gives maintainability.
For scenario 1.)
It is perfectly fine to have a service calling another service if that business code defined in the method is the same business functionality needed by the other service. This follows the DRY principle, no redundant codes.
But it is also perfectly fine to just directly call the Dao from a service instead of calling a different service to do that for you if it is just a simple call with no further business logic. Especially if the two services are in the same module anyway, there is no strong reason to make another service a bridge class for an obvious simple single line of code unless you want to abstract it, but in your case, its just a simple get call.
For scenario 2.)
But another thing to consider is modularity and direction of dependency. If each service calls each other, there could be problem in your design, as much as possible avoid circular dependency on different modules because this could lead to spaghetti code, better to extract same code to a different class declared on common module that can be shared by many modules.
Final note, as what Robert Martin says, you won't be able to code at once the cleanest code in one round. Best codes are forged by continuous refactoring and code cleanup. To quote Robert Martin,
The Boy Scouts have a rule: "Always leave the campground cleaner than you found it."
I am not greatly experienced with this problem, but personally I would avoid coupling controllers. My first approach would be trying to create an interface that would fit all models if possible. It would then be possible to create a model that wires multiple models together to access the data you need without adding references to the controller. For instance:
Model1 implements iModel{}
Model2 implements iModel{}
ModelWrapper implements iModel{
private iModel model1;
private iModel model2;
public ModelWrapper(iModel model1, iModel model2)
{
this.model1 = model1;
this.model2 = model2;
}
public SomeDataType getSomeValue(){
SomeObject.param1 = model1.method();
SomeObject.param2 = model2.method();
return SomeObject;
}
}
I am sure there is a better way to approach the number of models passed into the constructor and also a way to search each model for the data you are looking for. If the data is not found a null reference or better a custom error could be thrown. If the implementation is consistent perhaps the wrapper could combine all models and allow access to many custom combinations. At least this way, when requirements change you can simply add an additional wrapper to get what you need without changing the current implementation.
Perhaps a more experienced developer will build on my response to provide you a better implementation, but I hope this helps.

On properly implementing complex service layers

I have the following situation:
Three concrete service classes implement a service interface: one is for persistence, the other deals with notifications, the third deals with adding points to specific actions (gamification). The interface has roughly the following structure:
public interface IPhotoService {
void upload();
Photo get(Long id);
void like(Long id);
//etc...
}
I did not want to mix the three types of logic into one service (or even worse, in the controller class) because I want to be able to change them (or shut them) without any problems. The problem comes when I have to inject a concrete service into the controller to use. Usually, I create a fourth class, named roughly ApplicationNamePhotoService, which implements the same interface, and works as a wrapper (mediator) between the other three services, which gets input from the controller, and calls each service correspondingly. It is a working approach, though one, which creates a lot of boilerplate code.
Is this the right approach? Currently, I am not aware of a better one, although I will highly appreciate to know if it is possible to declare the execution sequence declaratively (in the context) and to inject the controller with and on-the fly generated wrapper instance.
Also, it would be nice to cache some stuff between the three services. For example, all are using DAOs, i.e. making sometimes the same calls to the DB over and over again. If all the logic were into one place that could have been avoided, but now... I know that it is possible to enable some request or session based caching. Can you suggest me some example code? BTW, I am using Hibernate for the persistence part. Is there already some caching provided (probably, if they reside in the same transaction or something - with that one I am totally lost)
The service layer should consist of classes with methods that are units of work with actions that belong in the same transaction. It sounds like you are mixing service classes when they could be in the same class and method. You can inject service classes into one another when required too, rather than create another "mediator".
It is perfectly acceptable to "mix the three types of logic", in fact it is preferable if they form an expected use case/unit of work
Cache-ing I would look to use eh cache which is, I believe, well integrated with hibernate.

Shortcut methods

My original question was quite incorrect, I have classes (not POJO), which have shortcut methods for business logic classes, to give the consumer of my API the ability to use it like:
Connector connector = new ConnectorImpl();
Entity entity = new Entity(connector);
entity.createProperty("propertyName", propertyValue);
entity.close;
Instead of:
Connector connector = new ConnectorImpl();
Entity entity = new Entity();
connector.createEntityProperty(entity, "propertyName", propertyValue);
connector.closeEntity(entity);
Is it good practice to create such shortcut methods?
Old question
At the moment I am developing a small framework and have a pretty nice separation of the business logic in different classes (connectors, authentication tokens, etc.), but one thing is still bothers me. I have methods which manipulates with POJOs, like this:
public class BuisnessLogicImpl implements BusinessLogic{
public void closeEntity(Entity entity) {
// Business Logic
}
}
And POJO entities which also have a close method:
public class Entity {
public void close(){
businessLogic.closeEntity(this);
}
}
Is it good practice to provide two ways to do the same thing? Or better, just remove all "proxy" methods from POJOs for clarity sake?
You should remove the methods from the "POJOs"... They aren't really POJO's if you encapsulate functionality like this. The reason for this comes from SOA design principles which basically says you want loose coupling between the different layers of your application.
If you are familiar with Inversion of control containers, like Google_Guice or Spring Framework-- this separation is a requirement. For instance, let's say you have a CreditCard POJO and a CreditCardProcessor service, and a DebugCreditCardProcess service that doesn't actually charge the CC money (for testing).
#Inject
private CardProcessor processor;
...
CreditCard card = new CreditCard(...params...);
processor.process(card);
In my example, I am relying on an IoC container to provide me with a CardProcessor. Whether this is the debug one, or the real one... I don't really care and neither does the CreditCard object. The one that is provided is decided by your application configuration.
If you had coupling between the processor and credit card where I could say card.process(), you would always have to pass in the processor in the card constructor. CreditCards can be used for other things besides processing however. Perhaps you just want to load a CreditCard from the database and get the expiration date... It shouldn't need a processor to do this simple operation.
You may argue: "The credit card could get the processor from a static factory". While true, singletons are widely regarded as an anti-pattern requiring keeping a global state in your application.
Keeping your business logic separate from your data model is always a good thing to do to reduce the coupling required. Loose coupling makes testing easier, and it makes your code easier to read.
I do not see your case as "two methods", because the logic of the implementation is kept in bussinessLogic. It would be akin of asking if it is a good idea java.lang.System has both a method getProperties() and a getProperty(String), more than a different method is just a shortcut to the same method.
But, in general, no, it is not good practice. Mainly because:
a) if the way to do that thing changes in the future, you need to remember that you have to touch two implementations.
b) when reading your code, other programmers will wonder if there are two methods because they are different.
Also, it does not fit very well with assigning responsabilities to a specific class for a given task, which is one of the tenets of OOP.
Of course, all absolute rules may have a special case where some considerations (mainly performance) may suggest breaking the rule. Think if you win something by doing so and document it heavily.

How to learn "separation of concern" in java

In another question, someone told me to implement the following in my java program. But, I am very new to Java and I do not know how to start to convert my simple program into this structure:
Data Access Layer (read/write data)
Service Layer (isolated business logic)
Controller (Link between view and model)
Presentation (UI)
dependency injection.
program to the interface:
Does that come inside some framework? Should I start learning Spring and this structure will evolve naturally? Or, can I implement above technologies one by one without using a framework?
You can implement them without a framework if you wish, but you give up whatever benefits the framework offers you.
The layering you cite is correct and independent of any framework; it's just programming to interfaces and separation of concerns. You're free to do it without Spring if you wish to minimize the number of new technologies you want to learn right now.
If you don't know what persistence is, then you shouldn't jump into Spring. Persistence means storing data in relational databases using SQL to most people. If you don't know that, I'd recommend starting there.
All the patterns books in the world won't help you if you've never used the underlying technologies.
If you've never done any of this, I'd recommend sticking to straight JDBC, servlets, and JSPs using only JSTL (no scriptlets). Anything beyond that will just be confusing.
If you had a Foo model object, with persistence, service, and view tiers, the interfaces might look like this:
package model;
/**
* A model object that's interesting from your problem's point of view
*/
public class Foo
{
}
package persistence;
/**
* CRUD operations for a Foo
*/
public interface FooDao
{
Foo find(Long id);
List<Foo> find();
void saveOrUpdate(Foo foo);
void delete(Foo foo);
}
package service;
/**
* Just a data service that wraps FooDao for now, but other use cases would
* mean other methods. The service would also own the data connection and manage
* transactions.
*/
public interface FooService
{
Foo find(Long id);
List<Foo> find();
void saveOrUpdate(Foo foo);
void delete(Foo foo);
}
package view;
/**
* A class that owns services, validates and binds input from UI, and handles routing
* to the next view once service is complete.
*/
public interface FooController
{
ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response);
}
These are just interfaces, of course. You'll need to provide implementations.
You might want to check out Domain Driven Design. The Code samples are in Java. The things you listed are design related more than any specific technology.
In short:
Data Access Layer is a module of your application that provides interface to your data. Data may be in SQL database, XML, file wherever. You write interfaces and classes that provide interface to access data usually as VO or DTO via DAOs
Service Layer contains most of the use-case logic. Service layer interacts with Data Access Layer to perform tasks in given use case. I did not find a good article on introductory service layer. You may see here and there
Controller is the one that interacts with Service Layer and/or Data Access Layer and/or other controllers in order to perform a specified client's tasks. For example, a sign-off button controller will request a sign-off action/service to invalidate user's sessions on all services that user is logged on to, then it will choose an appropriate view or log-off web-page to forward user to.
Presentation is your user interface. It can be a web-page made of HTML or Java Swing window or anything that user interacts with. GUI commonly known term for it. This is what your users will be interacting with using mouse clicks, scrolls, swipes, drag-and-drop. These actions are mapped with controller which performs action based on what user performed on UI.
Dependency Injection is a way to wire various components. There are a lot of resources on web. You can look in Martin Fowler's this article. It's basically a mechanism that allows components to behave much like plug-and-play devices, if you know what plug goes where.Spring is a good implementation of dependency injection. You may not want to write your own framework, and at this stage, you should rather not. There is a Spring MVC framework that can do things for you.
But I suggest you start from very basic. Instead of jumping on jargon, read from basic. Start with a good book on application development using Java. You can also look into
Design Patterns - Gang of Four
Core J2EE Patterns
Developing a Spring Framework MVC application step-by-step
dependency Injection with the Spring Framework
You can implement all of this is you want -- it's been done many times before, but nothing prevents you from doing it again.
What would be a better use of your time is to make sure you understand the separation of concerns you listed above (which are generally right) and identify the most efficient integration of existing frameworks to leverage (e.g., Hiberante, Spring, Guice, etc). There are multiple answers for that one (and no shortage of opinions!), but all things being equal, the less frameworks you have to integrate, the easier and better fitting it's likely to be.
Spring has a very well known framework which covers many of these things, so it would be wise to start there. It also allows you to work with other frameworks (i.e., you can use selective parts of Spring). For example, you can use Spring for dependency injection and use a different MVC framework.
It is very hard to answer this question. First of all, I don't know what your program looks like. Second, I don't think 'converting' it is something that can be done, or should be done for that matter. What you're talking about are architectural concepts that the developers usually have in mind while designign the application.
If these concepts interest you, I suggest reading a bit about Model-View-Controller pattern (MVC) and service-oriented Architecture (SOA).
These are general concepts that do not apply specifically to Java. However, they are widely used in Java enterprise development. Various frameworks allow you to create applications utilizing these concepts. For example, Spring Web MVC, as others have pointed out, is part of the Spring Framework that lets you create web applications that adhere to the MVC pattern.
If your program is really simple this separation might be done by using one calss for each
category.
Data Access Layer (read/write data) -> one class for presisting laoding
Service Layer (isolated business logic) -> one calss with bussiness logic
Controller (Link between view and model) -> in simple swing app this merges with UI
Presentation (UI) -> one class for one widnow
dependency injection -> not used in small apps
program to the interface -> Your service class should use interface tah is used by other class instead of directly your serivce implementation:
if it's not as simple program you might want to have package for each category.
BUT - don't overdesign! These concepts are ment to help you manage large scale applications, not to ruin you in your programming begginigs!

Categories

Resources