how to inject interface to class in java? - java

i have my DTO class that is :
public class EmailResponse {
// Make public to avoid getters and setters
public Email email;
public RequestData reqData;
public EmailResponse() {
super();
}
}
and i want to implement to it this interface:
public interface IAssertionErrorDo {
public void onErrorDo();
}
but i want to do it during execution, i don't want to touch "EmailResponse" because it would not be ok to make it implements that interface due they don't belong to the same layer, i mean, EmailResponse would belong to service layer and IAssertionError would belong to test layer. I am using TestNG.
Do you know how i could do this? Regards
EDIT:
My implementation is this:
EmailResponse emailResponse = emailService.getUserEmail(userId);
And the reason i want to do this "injection" is because i have
public class LoggingAssert
extends Assertion {
private static final Logger LOGGER = LoggerFactory.getLogger(LoggingAssert.class);
private IAssertionErrorDo dataE;
#Override
public void onAssertFailure(IAssert a, AssertionError ex) {
LOGGER.info("[ERROR] " + a.getMessage());
if (this.dataE != null) {
this.dataE.onErrorDo();
}
}
public LoggingAssert setOnErrorDo(IAssertionErrorDo object) {
this.object = object;
return this;
}
}
loggingAssert.setOnErrorDo(emailResponse).assertNotNull(emailResponse.getEmail().getId(),
"Checking created email doesn't exists");
So i want to if assert fails execute method onErrorDo() from emailResponse

You could do
public class MyEmailResponse extends EmailResponse implements IAssertionErrorDo {
...
}

implementation calls in interfaces, you can call more than 1 interface if you want by adding commas to separate them..
to call interface methods you simply just use the method's name.
like this:
public class MyEmailResponse implements IAssertionErrorDo
{
public void onErrorDo() {//define it's behavior}
}
if you extend a class you use:
super.MyMethod()
to call the a method inside the extended class, but if you already have an extended class and want a method from another class you have to create an object for that class first then call it, thus:
MyClass mc = new MyClass();
if it is in a different package then
myPackage.MyClass mc = new myPackage.MyClass();
then you call your method from that class using the object you created, which is in this case mc.. so:
mc.MyMethod();
if you want it to return a variable then you will need to add a return statement in that method with the variable you want it to return.
interfaces are usually used for global an changing environments (dynamics), for example if you developed a program and it needs a driver to connect to databases then you will make an interface and send it to the database developers, and each one will fill the codes in that interface and send it back... this guarantees consistency.
when you implement an interface you have to define every method inside it (even if you leave it empty) and you cannot change the interface's methods names nor add... it is used in other areas as well, i don't think you need to use it in your case.

Related

Creating child class based on class content

I have a class structure like this:
LineTemplate (abstract)
/ \
LineOut (abstract) LineIn (final)
/ \
LineOutTransfers (final) LineOutSells (final)
Both LineOut and LineIn should read a line from a file, check its content against a database and run multiple queries.
LineOut, however, contains two slightly different variations, which depend on the contents of the line. Due to the fact that LineOutTransfers and LineOutSells perform different actions when their methods are called, I decided to inherit and treat them as subclasses.
I created a public static LineTemplate __init() method within LineTemplate to determine whether it is a LineOut or LineIn class and return the correct type based on external conditions, and I wanted to implement a similar method to determine the correct type of LineOut subclass.
Since the LineOut child depends on the line content, however, I'm stuck at this point. The class should read the line, then convert itself to the correct child and then perform the checks. But this is impossible as I cannot cast a parent class into a child, if it is not already of that type (polymorphism).
I also thought about reading all the line inside LineOut's __init() method, and then passing the variables as arguments to its child constructor, but since there are a bunch of variables to be read and since it is done differently inside LineIn, it seemed to me like a bad practice.
Any ideas? Thanks in advance.
Can you add a convertWithContext(SomeClassRepresentingContext ctx) method to LineOut that will return a new LineOut that will be the correct subclass of LineOut?
Another approach would be to use a Factory method and supply it the line content and the context. Something like
LineOutFactory.instance().constructLineOut(String line, SomeClassRepresentingContext ctx);
In Java you cannot change the type of a class once it is created you can only build a new class based on the content of the existing class and possibly external context.
Favor composition over inheritance, so instead of
abstract class LineOut {
public void consume(Line l) {
// ...
subclassConsume(l);
// ...
}
protected abstract void subclassConsume(Line l);
}
// and
class LineOutTransfers extends LineOut {
protected abstract void subclassConsume(Line l) { ... }
}
class LineOutSells extends LineOut {
protected abstract void subclassConsume(Line l) { ... }
}
you should do this
abstract class LineOut {
private TransferLineHandler transferHandler;
private SellsLineHandler sellsHandler;
public void consume(Line l) {
// ...
if (isTransfer(l)) {
transferHandler.consume(l);
} else {
sellsHandler.consume(l);
}
// ...
}
protected abstract void subclassConsume(Line l);
}
// with
class TransferLineHandler {
public consume(l) { // stuff from LineOutTransfers }
}
class SellsLineHandler {
public consume(l) { // stuff from LineOutSells }
}
This removes the "dynamic subclassing" issue altogether and makes the code more testable.
Maybe a factory method would be useful for this scenario: https://refactoring.guru/design-patterns/factory-method

How to design classes with static methods

I want to avoid code duplication in next situation: I have two classes NewTx and GetTx, first represents new transaction, second represent a transaction, that joins current. The goal is to make CRUD code as compact as possible, so classes are usually used as:
List<Users> users = NewTx.loadList("select u from User u");
Student s = GetTx.find(Student.class, '02d7c3fe-e9cf-11e4-8ceb-c7b1b9baf140');
These classes actually differ only in a way they obtain a transaction, but all their methods are static, so it seems impossible to move logic to parent class.
Now I have
public final class NewTx extends Tx {
public static <T> List<T> loadList(String query) {
return tx().call(Tx.<T>getLoadListCallable(query));
}
static Transaction tx() {
return DataSource.createTransaction();
}
As I said before, only tx() method is different for NewTx and GetTx classes, other methods just obtain transaction and than delegate job to parent Tx class.
So the goal is to move all CRUD methods like loadList to parent class Tx.
Restriction: method calls must look like before: NewTx.load(..., not NewTx.get().load(..
Any ideas?
Your goal isn't going to happen with the current restrictions you've given. If you were willing to change the method calls, there are multiple ways, but moving common static calls into a shared class doesn't work because static methods can't be inherited in java, only shadowed. Consider the following:
public static class StaticParent
{
public static void commonMethod(){
System.out.println(getOutput());
}
public static String getOutput(){
return "Parent";
}
}
public static class StaticChildA extends StaticParent
{
public static String getOutput(){
return "ChildA";
}
}
public static class StaticChildB extends StaticParent
{
public static String getOutput(){
return "ChildB";
}
}
StaticChildA.commonMethod() and StaticChildB.commonMethod() will both print "Parent" because commonMethod is being shadowed and has no way of knowing that the calling code was from StaticChildA or StaticChildB. If we print the stack trace inside commonMethod, we see the following from both calls:
testpackage.UnitTester$StaticParent.commonMethod(UnitTester.java:4497)
testpackage.UnitTester.main(UnitTester.java:4526)
With no this or difference in the stack, there's no way to even branch inside the code manually to pick an implementation of your tx().

Design Patterns - One public class utilizing many hidden classes

I have gone through http://www.dofactory.com/net/design-patterns in trying to find out the most efficient to create a design pattern in which "one visible class utilizes many hidden classes" to create a fluent API. Below is the code I currently have:
public class VisibleClass {
Private OrderClass order;
private ReceiptClass receipt;
public VisibleClass makeOrder() {
if (!(order instanceof OrderClass))
order = new OrderClass();
order.make();
return this;
}
public VisibleClass printReceipt() {
if (!(receipt instanceof ReceiptClass))
receipt = new ReceiptClass();
receipt.print();
return this;
}
}
class OrderClass implements IOrder {
public void make() {}
}
class ReceiptClass implements IReceipt {
public void print() {}
}
interface IOrder { void make(); }
interface IReceipt { void print(); }
Here is how I am currently using the API:
public static void main(String[] args) {
VisibleClass x = new VisibleClass();
x.makeOrder().printReceipt();
}
It this a good approach? Can a better approach be used for it?
*EDIT: Also, I should add that the VisibleClass will implement all methods of the hidden classes.
Your approach is quite good. Here some recommendations:
1 Change class member types to their interfaces as for 'Program to an interface, not an implementation' principle:
public class VisibleClass {
private IOrder order;
private IReceipt receipt;
2 Do you really need to check class types in makeOrder and printReceipt methods ? Creating instances after null check seems enough:
public VisibleClass makeOrder() {
if (null == order)
order = new OrderClass();
order.make();
return this;
}
public VisibleClass printReceipt() {
if (null == receipt)
receipt = new ReceiptClass();
receipt.print();
return this;
}
3 This approach is valid until methods of VisibleClass will be called by a single thread. If you're going to place it in a multi-thread program, you should ensure that there are only one instances of OrderClass and ReceiptClass each. There are 3 ways you can follow:
a. Create instaces of OrderClass and ReceiptClass in constructor and make VisibleClass singleton.
b. Make OrderClass and ReceiptClass singleton and remove new lines.
c. Create instances surrounded with synchronized block in makeOrder and printReceipt methods.
one visible class utilizes many hidden classes
don't do that with business classes. Fluent syntax's is great for configuration etc, but not for plain business code.
The reason is that the class itself losses control over it's state which can put it in an inconsistent state (i.e generate faulty results).
There is even a principle called Law of Demeter which is about just that.
If you have a business requirement that a receipt should be printed on a new order you should just return it as a return value.
var receipt = visibleClass.makeOrder();
As for using interfaces for entity/business classes, why do you do that? why would you want to abstract away those? The usually do not have any other dependencies or different types of implementations.
You can try using the Facade Design pattern
Or may be try using a Decorator Pattern

Implementing Data Acess API using dependency Injection

I am new to writing API's and did some research and realize to accomplish what I want I would need to do it using Dependency Injection. I am writing an android application that haves two data source. One is expose by web services and the other is SQLlite. The SQLlite is used as backup when no data connection is available (Only interested for the webservice portion of the API for the time being will refactor). I want to write a API that provides a layer of abstraction to this that calls the right data access class based on the model required. Therefore, I have a interface that describes methods that the api should implement, called IDataAccess (Only interested in getAll for the purpose of figuring out what to do).
public interface IDataAccess {
public <T> List <T> getAll ();
public <T> T getById (int id);
}//end IDataAccess
I am using Guice for dependency injection. The guice module is:
public class Data extends AbstractModule {
public void configure () {
bind (IDataAccess.class).to(UserData.class);
}
}
and a Implementation of IDataAccess is (Note I am using Jersey Client API):
public class UserData extends DataAccessManager implements IDataAccess {
#SuppressWarnings("unchecked")
public List <User> getAll () {
WebResource webResource = client.resource (WebResourceURL.URL_USER_ALL);
ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (response.getStatus () == 200)
return response.getEntity(new GenericType <List <User>> () {}) ;
else
return null;
}//end getAllUsers method
}
I have a class that loads and instantiates any resource needed. It also returns a instance of a DataManager called DataAccessFactory.
public class DataAccessFactory {
private Client client;
private static DataAccessFactory instance;
private DataAccessFactory() {
client = Client.create();
}
public static DataAccessFactory getInstance() {
/*
* check if instance variable is instantiated.
* if it is not then instantiated it and returns
* created instance.
*/
if (instance == null) {
instance = new DataAccessFactory();
return instance;
} else
return instance;
}//end getInstance method
public DataAccessManager createDataAccessManager() {
return new DataAccessManager(client);
}//end createDataAccessManager method
}
Then I have the actual DataAccessManager class:
public class DataAccessManager {
protected Client client;
protected DataAccessManager (Client client)n{
this.client = client;
}//end constructor
public <T> List <Object> getAll(T t) {
Data module = new Data ();
Injector injector = Guice.createInjector(module);
IDataAccess data = (IDataAccess) injector.getInstance(t.getClass());
return (List<Object>) data;
}//end fetchAllUser method
}
To call the user model on this class I would do something like this:
#Test
public void fetchUser () {
DataAccessManager m = DataAccessFactory.getInstance().createDataAccessManager();
List<User> user = (List<User>) m.getAll(new Userdata ());
if (user == null)
assertEquals(1, 2);
else
assertEquals(1, 1);
}
Ideally what I want this to do now is, call the UserData to get all the User objects or the OrderData (When implementation is written) class to get all the order objects etc.
The problem is that this is giving a error:
Cannot cast from List to List
.How can I fix this problem or restructure this so that it makes sense?
1) You are creating an injector (Guice.createInjector) per request. Injector creation is expensive and should normally be done during application loading. You should see DI as a bootstrap mechanism and keep it simple.
2) You don't need the DataAccessFactory. First there is no need for a factory as the createDataAccessManager instantiation does not require any logic and secondly Guice could also take care of the factory pattern.
I would personally keep it simple and inject with Guice directly the UserData instance into each service that needs it, without using the rather complicated Abstraction approach showed here. Still, it does not solve the problem of dealing with network issues. My guess is that each data access class will have to deal with connectivity in a specific way, so the logic should be directly here.
For the list casting problem, see http://docs.oracle.com/javase/tutorial/java/generics/subtyping.html
If you will continue that way, I would recommend to read about erasure also.
It's a common problem you fall for. We'd expect that as String is-a Object, List<String> is-a List<Object> is true too. But it isn't. This is why this class cast won't work:
#Test
public void fetchUser () {
//...
List<User> user = (List<User>) m.getAll(new Userdata ());
//..
}
I suggest to rewrite the DataAccessManager.getAll() method to return the right kind of list.
For the record, I found a typo in DataAccessManager.getAll() method. I think when you wrote return (List<Object>) data; then you rather wanted to write return List<Object> data.getAll(); Otherwise you just cannot cast IDataAccess to List.
To escape from this casting hell I suggest to add a type to the IDataAccess interface and to its implementations:
public interface IDataAccess<T> {
public List <T> getAll ();
public T getById (int id);
}//end IDataAccess
public class UserData extends DataAccessManager<User> implements IDataAccess<User> {
// your implementation
}
I'd also clarify DataAccesManager itself:
public class DataAccessManager<T> {
//fields and constructors
public List<T> getAll(IDataAccess<T> access) { //this is how the test suggests you want to use this method
Data module = new Data ();
Injector injector = Guice.createInjector(module);
IDataAccess<T> data = (IDataAccess<T>) injector.getInstance(access.getClass()); //why is this line important? why don't you use the access parameter instead?
return data.getAll();
}
}

Right way to prevent subclass instantiation without calling a desired initialisation method?

Can somebody help a novice programmer to understand if his solution is correct?
My question is similar to the the following two:
What's wrong with overridable method calls in constructors?
Factory pattern in C#: How to ensure an object instance can only be created by a factory class?
Problem: I want to have subclasses which will differ only in their initialisation method. However, I also want to prevent instantiating these classes without initialization. In other words, I want to ensure, that some "initialize()" method will always be called after instantiation of a subclass:
public abstract class Data {
protected Parameter dataSource;
Data(parameter1){
this.dataSource = parameter1;
loadData(); // should be called to initialise class fields and ensure correct work of other class methods
}
protected abstract loadData(){
... //uses dataSource
}
}
So I decided to perform initialization on a constructor. It worked (now I know that it's a very bad practice) until I created a subclass where the initialize method used some additional parameters:
public class DataFromSpecificSources extends Data {
private Parameter dataSource2;
public DataFromSpecificSources(parameter1, parameter2){
this.dataSource2 = parameter2; // I can't put it here because the constructor is not called yet
super(parameter1); // this, of course, will not work
}
#Override
private void loadData(){
... // uses both dataSource 1 and 2
// or just dataSource2
}
}
This, of course, is not going to work. And I started searching for a right pattern... After I read the answers on questions posted before, I decided to use the factory and limit visibility of the subclass constructor to the package:
My solution:
// factory ensures that loadData() method will be called
public class MyDataFactory(){
public Data createSubClass(parameter1,parameter2){
Data subClass;
if (parameter2 != null){
subClass = new DataFromSpecificSources(parameter1, parameter2);
subClass.loadData();
} else {
subClass = new AnotherSubClass(parameter1);
subClass.loadData()
}
return subClass;
}
}
public abstract class Data {
protected Parameter dataSource;
Data(parameter1){
this.dataSource = parameter1;
}
// I don't call it in constructor anymore - instead it's controlled within the factory
protected abstract loadData(){
... //uses dataSource
}
}
public class DataFromSpecificSources {
private Parameter dataSource2;
protected DataFromSpecificSources(){}
// now this constructor is only visible within package (only for the factory in the same package)
DataFromSpecificSources(parameter1, parameter2){
super(parameter1); // it does not initialise data anymore
this.dataSource2 = parameter2;
}
#Override
protected void loadData(){
... // uses dataSources 1 and 2
}
}
Now factory ensures that subclasses will be initialized (data will be loaded) and instantiation of subclasses is not allowed in other packages. Other classes have no access to constructor of subclasses and are forced to use factory to get an instance of a subclass.
I just wanted to ask if my solution is correct (logically) and Factory method with subclass constructor visibility limited to the package is right choice here?! Or there is any other more effective pattern solving the problem?!
Using a factory is definitely a step in the right direction. The issue I see is that what happens when you want to add a third class that takes a third parameter. Now your Factory is either going to have to have a second overloaded createSubClass method taking the third parameter, or all your code is going to have to be rewritten to provide the third parameter. Additionally you are forcing anyone using the Factory to specify null for the second parameter even if they only want the single parameter class.... when you get to the class that takes 15 parameters how are you going to remember which parameter is which
The solution to this is to use the Builder pattern instead.
public class MyDataBuilder(){
private parameter1 = null;
private parameter2 = null;
public MyDataBuilder withParameter1(parameter1) {
this.parameter1 = parameter1;
return this;
}
public MyDataBuilder withParameter2(parameter2) {
this.parameter2 = parameter2;
return this;
}
public Data createSubClass(){
Data subClass;
if (parameter2 != null){
subClass = new DataFromSpecificSources(parameter1, parameter2);
} else {
subClass = new AnotherSubClass(parameter1);
}
subClass.loadData();
return subClass;
}
}
Now the code creating the Data instances can work like so:
Data data = new MyDataBuilder().withParameter1(param1).withParameter2(param2).create();
or
Data data = new MyDataBuilder().withParameter1(param1).create();
And that code is future-proofed for when you add parameter3... and you can even have the builder with a non-null default for parameter3 if you so need that.
The next thing you notice is that you now have this nice Builder object that contains all the required parameters... so now you can add getters to the Builder and just pass the Builder as the constructor parameter, e.g.
public class DataFromSpecificSources {
...
DataFromSpecificSources(MyDataBuilder builder){
...
}
...
}
So that you now almost have a standard constructor signature
Now for some Java specific improvements. We can make the builder not need to know about the sub-classes at all!
Using a DI framework we can inject the classes that implement the Data interface / abstract class into the Builder and then just iterate through each class until we find a class that supports the configuration of the Builder instance.
The poor-man's DI framework is the /META-INF/services contract and the ServiceLoader class available since JRE 1.6 (though the core logic has been in Java since 1.2)
Your builder's create method will then look a little something like
public Data create() {
for (DataFactory factory: ServiceLoader.load(DataFactory.class)) {
if (factory.canCreate(this)) {
Data result = factory.newInstance(this);
result.loadData();
return result;
}
}
throw new IllegalStateException("not even the default instance supports this config");
}
Whether you want to go to that extreme is questionable... but since you might come across it at some point in time when looking at other people's code, it is probably a good time to point it out to you now.
Oh, the reason why we have to add a Factory class to be looked up by the ServiceLoader is because ServiceLoader expects to call the default constructor, and we have hidden the default constructor so we use a Factory class to do the work for us and allow us to keep the constructor hidden.
There is nothing preventing the Factory classes from being static inner classes in the Data classes (which gives them great visibility on the class they are creating), e.g.
public class UberData extends Data {
private UberData(MyDataBuilder config) {
...
}
public static class Factory extends DataFactory {
protected Data create(MyDataBuilder config) {
return new UberData(config);
}
protected boolean canCreate(MyDataBuilder config) {
return config.hasFlanges() and config.getWidgetCount() < 7;
}
}
}
As we can then list in META-INF/services/com.mypackage.DataFactory
com.mypackage.UberData.Factory
com.mypackage.DataFromSpecificSources.Factory
com.some.otherpackage.AnotherSubClass.Factory
The best bit about this type of solution is it allows adding additional implementations just by adding those implementations to the classpath at run-time... i.e. very loose coupling

Categories

Resources