Which design pattern should be used? - java

I have a some functionality implemented to store documents inside a data base.
Now, I want to access the functionality in my module but not directly.
As I have the FileInputStream with me and the functionality implemented accepts JSON string.
So, which design pattern could be used to bridge the gap in input parameters?
I know Adapter is one of the answers but can anyone suggest anything else?
Below is the sample of the functionality.
public interface DocumentService {
public String create(String jsonRequest);
public String search(String jsonRequest);
public String update(String jsonRequest);
public String fetch(String jsonRequest);
}

To elucidate my comments:
Trying to wedge every bit of functionality into an explicit "pattern" isn't a productive use of your time.
Even if it is, trying to find the perfect "name" for what you actually come up with isn't.
You need a helper class that converts an FIS into JSON, and that's about it.
You could compose a service that uses that helper and your existing class, or...
Compose your existing class into the FIS => JSON converter, or...
Modify your data flow so that you pass the data through a filter that JSONifies it, or...
In other words, (a) the "best" answer depends on your very specific situation, and (b) it doesn't matter what it's called. Do something, put it somewhere half-way reasonable, and if it ends up not being exactly right, iterate until it is. Don't waste time trying to name the "pattern".
It's like throws and joint locks: don't look for them, find them. The patterns are hidden in your application, surface them and implement.

Just make a private converting method
String toJSON(FileInputStream fs) {
...
}
If you happen to need that method in multiple locations move it into a utility class.
If that single method is not flexible enough for every situation you need it in right now then you should consider writing an adapter class.
The desire to design a perfect, flawless architecture for every functionality is natural in many programmers. It poses the risk of paralyzing the actual objective, which is to deliver a working product.
The important thing about good design is not that it fulfills every possible use case that may arise in the future, but that it is easy to understand and easy to change should that use case actually arrive.

Looks like Adapter is a good choice. I will move forward.

Why don't you use the DAO pattern?
Pass the input stream to the DAO object and make it convert it from the file input stream to JSON and call the create methods.
http://www.tutorialspoint.com/design_pattern/data_access_object_pattern.htm

Related

Determining Subclasses Types with Attribute

I have the following class hierarchy
Promotion - abstract
- Coupon
- Sales
- Deals
(Coupons, Sales and Deals are all subclasses of Promotion).
and would like to determine the type of the object when exchanging data between the REST APIs (JSON) and the Client (Angular). Users can submit a Coupon or a Deal or a Sale. For instance when a coupon is sent from the client, I want to be able to know that this is coupon so that i can call the correct method.
To solve this problem I have declared a variable and an abstract method in Promotion.
protected String promotionType = getPromotionType();
protected abstract String getPromotionType();
In the subclasses for instance in Coupon I have something like this
protected String getPromotionType() {
return "coupon"
// OR return this.getClass().getSimpleName().toLowerCase();
}
This will automatically initialize the promotionType variable so that in the Controllers I can check if the object is Coupon or Sales or Deal. Remember that JSON send data in String formats so I must I have a way to determine the type of object coming.
In this case I will have a single controller to handle all my CRUD operations. In my controller method I will do something like::
#PostMapping public void create(#RequestBody Promotion){
// And inside here I will check the type of **promotionType**
}
Here am using Promotion as argument instead of any of the subclasses in the create() method.
My question is, is it the best way to solve this?
Or do I have to create a separate Controller for each of the subclass? I am looking for the best way to do it in the real world.
I am using Hibernate for my mappings.
My question is, is it the best way to solve this?
Answers to this question will always be opinion-based, especially, as we don't know about your entire application, not only technically but business-wise, and how the client-code consumes and displays the code.
Or do i have to create a separate Controller for each of the subclass?
No, not necessarily. If the code is and would probably stay simple - sometime you can anticipate this - it doesn't make sense to inflate the code. Having three Controllers instead of a single PromotionController will very likely increase redundant code. Otherwise, if the subclasseses are rather heterogeneous, three Controllers could be more advisable.
Another thought, you might have a (human) client that manages only the Deals and that client has special requirements leading to a bunch of customized rest interfaces only for the Deal, you'd probably like to have a separate Controller.
I am looking for the best way to do it in the real world.
There is no best way. Five developers have probably five opinions on how to solve this. And even if one is more reasonable for the time being, it may change on the next day due to or changed new business requirements.
The best way is to discuss this in the team, create a common sense and if unsure, let the lead architect decide which way to go. Imo, your approach seems quite ok. That's my 2 cents.

Where is the correct place to put find functions?

I'm working on a project that is split into several smaller Java Projects. I have this Account object that stores user credentials, etc. I want to create a function to return all characters that account has, e.g. findCharacters(); Where should I put that, inside an API or in the Account class itself?
It is better place that function inside Account class as it is related functionality to Account object.
public class Account {
//properties go here
int findCharacters() {
//method logic goes here
}
}
Since this is Java, I recommend using its Object Oriented nature and capabilities. Oracle has a decent tutorial on Java and OOP. Here are some references to get you started:
https://docs.oracle.com/javase/tutorial/java/concepts/
http://people.ucls.uchicago.edu/~bfranke/apcs_0809/downloads/BPJ_TextBook_3_0_5.pdf
Just go for the function: findCharacters() inside the Account class.
As the comments say: it depends.
From a pure OO point of view, the first place to look for would be the Account class itself.
But the important thing is: the Account should follow the SOLID principles - namely: single responsibility! Therefore one has to be careful to only have those methods inside a class that contribute to that single responsibility. In other words: you want to avoid adding all kinds of methods on a specific class - just because that method is mainly using objects of that class.
Domain Driven Design gives a hint what to do when the method "doesn't fit" into the "domain object": you turn to special service classes to wrap around that "service like" functionality.
Which model to pick/follow depends on the context of your application.

Implementing new feature using SOLID principles in old code

I just try to get more into SOLID principles but get stuck by implementing new structures in my old (not SOLID) code.
I have this Room.Class
public class Room {
private String roomCode;
private String roomDescription;
// getter/setter
}
Now I need to have a translation for the roomDescription. I started to create an interface
public interface ITranslation {
String findTranslation();
}
and an implementation
public class RoomDescriptionTranslation implements ITranslation {
#Override
public String findTranslation() {
return "translated Room";
}
In the already existing code there is a service class which creates some Rooms with codes and descriptions. These Rooms are also used in the view (as jsp bean).
The new requirement is to have the translated description on the view.
So for me the question is where I should implement the logic of translation of the existing Rooms.
Should I implement it in the existing serivce class where the Rooms are created?
Or should RoomDescriptionTranslation be a field inside Room?
Or should I created a new service class where just the description gets translated?
Just need a pointer to go to the right direction.
It could be first or third option, but not the second option in my opinion. I think one important question, in general for designing any class is this:
For a property p and class C, is p a property of C?
So, in your case the question becomes: is translation a property of Room? Semantically, it sounds that it is not.
Then, you can ask the same question on Room Service class. The answer to that depends on how you defined your service class. Again, another rule that helps to decide whether a property belongs to a class, is this:
What is one singe word or phrase that describes this class?
This goes to the very idea of what a class is in OOP and also to S in SOLID. Once, you ask this question and can describe one single purpose for your class, then you can go back and ask the first question, whether certain property belongs to this class or not.
Now, if your service class is such that, "Handle all room related actions" (not saying this is right, but if this is the case) then you can add one more action to it, namely translation. But, if it is not then you may create a new service, translation.
Considering all this, I lean more towards having a new translation service as it looks
Something independent
Will be easily extendible (compared to other option) like adding more languages
Does not require changing existing code
Again, there might be other factors affecting the whole thing.
I would create a model TranslatedRoom extends Room to use only in view this L from SOLID and inside this new model would take care about translations.
Of course if it is possible to refactor service which creates model for views etc.
One more thing (maybe it is S from SOLID) this idea is good if we need to show translated room only in this/these views.
If you want to translate text you should use internationalization solutions which already exist in java.
In your solution you'll create painful maintenance problems and every string which you'll return will be surrounded by if.

Application design - Updating domain object

I would like to improve the design of some part of my application. It is a swing application in which the user interface is updated by data received from a server (TCP/UDP). At the moment i pass my domain object (POJO) to the constructor of the class the will connect with the server, receive and send data, and directly use getter and setter method.
public static void main(String[] args) {
TcpClient client = new TcpClient(server, port, domainModel);
}
public class TcpClient {
public void connect() {
// Code to create the socket and connect to the server.
new Thread(new TcpProtocol(socket, domainModel)).start();
}
}
I 'm using some sort of Factory class inside the TcpProtocol class to create the right object.
I would like to decouple my domain object from the network programming part. Is there some common pattern to use for this ? I was thinking about DAO and Value Object, commonly used for JavaEE applications. Those are the only one i see, but if someone has better proposition please let me know.
Thank you.
As a general rule I consider non-trivial code in the constructor to be a design smell since it complicates inheritance and other forms of extensibility.
If you do not need the object to update itself from the network after it is created, then you can use a Factory to create your POJO. I tend to avoid ValueObjects unless you are wrapping something with very little data like currency/dates otherwise you will end up with a bunch of getters/setters.
If you need the object to access the network during its use, then you can make it a Proxy and pass in a DAO that handles all the network code. For testing you pass in a Mock/Stub instead.
A start to reaching your goal would be to remove the network access code from your constructor (I'm assuming you have one class that contacts the network and you're passing your POJO to its constructor). You would instead create a utility that contacts the network.
To instantiate the correct object type from your data stream, you might consider creating a Factory that knows how to adapt the stream to specific object types.
Maybe using the java.io ObjectInputStream and ObjectOutputStream might be a simple way to do this since it does not depend on the class of the object transferred?
What i would suggest to do is apply the Observer pattern. You might also need to apply the Mediator pattern along with your Observer - but check carefully if your design
warrants this kind of complexity.
The idea behind the observer is that your UI code "listens" for changes in the presented model. When changes take place (presumably from your network-bound code) an event is fired and your UI is thus notified in order to update itself accordingly,

Is it possible to monkey patch in Java?

I don't want to discuss the merits of this approach, just if it is possible. I believe the answer to be "no". But maybe someone will surprise me!
Imagine you have a core widget class. It has a method calculateHeight(), that returns a height. The height is too big - this result in buttons (say) that are too big. You can extend DefaultWidget to create your own NiceWidget, and implement your own calculateHeight() to return a nicer size.
Now a library class WindowDisplayFactory, instantiates DefaultWidget in a fairly complex method. You would like it to use your NiceWidget. The factory class's method looks something like this:
public IWidget createView(Component parent) {
DefaultWidget widget = new DefaultWidget(CONSTS.BLUE, CONSTS.SIZE_STUPIDLY);
// bunch of ifs ...
SomeOtherWidget bla = new SomeOtherWidget(widget);
SomeResultWidget result = new SomeResultWidget(parent);
SomeListener listener = new SomeListener(parent, widget, flags);
// more widget creation and voodoo here
return result;
}
That's the deal. The result has the DefaultWidget deep within a hierarchy of other objects. The question - how to get this factory method to use my own NiceWidget? Or at least get my own calculateHeight() in there. Ideally, I'd like to be able to monkey patch the DefaultWidget so that its calculateHeight did the right thing...
public class MyWindowDisplayFactory {
public IWidget createView(Component parent) {
DefaultWidget.class.setMethod("calculateHeight", myCalculateHeight);
return super.createView(parent);
}
}
Which is what I could do in Python, Ruby, etc. I've invented the name setMethod() though. The other options open to me are:
Copying and pasting the code of the createView() method into my own class that inherits from the factory class
Living with widgets that are too big
The factory class can't be changed - it is part of a core platform API. I tried reflection on the returned result to get to the widget that (eventually) got added, but it is several widget-layers down and somewhere it gets used to initialize other stuff, causing odd side effects.
Any ideas? My solution so far is the copy-paste job, but that's a cop out that requires tracking the changes in the parent factory class when upgrading to newer versions of the platform, and I'd be interested to hear other options.
Perhaps you could use Aspect Oriented Programming to trap calls to that function and return your own version instead?
Spring offers some AOP functionality but there are other libraries that do it as well.
One ugly solution would be to put your own implementation of DefaultWidget (with same FQCN) earlier on the Classpath than the normal implementation. It's a terrible hack, but every other approach that I can think of is even worse.
Just my concept idea,
It is possible that use AOP, with bytecode engineering way, to inject a aspect to the calculateHeight method.
Then, you may enable you patch by ThreadLocal or else variable.
cglib is a Java library that can do some things similar to monkey patching - it can manipulate bytecode at runtime to change certain behaviours. I'm not sure if it can do exactly what you need, but it's worth a look...
It is totally possible to monkeypatch in Java, using Unsafe.putObject and a class finder. Wrote a blog post here:
https://tersesystems.com/blog/2014/03/02/monkeypatching-java-classes/
The object-oriented way of doing this would be to create a wrapper implementing IWidget, delegating all calls to the actual widget, except calculateHeight, something like:
class MyWidget implements IWidget {
private IWidget delegate;
public MyWidget(IWidget d) {
this.delegate = d;
}
public int calculateHeight() {
// my implementation of calculate height
}
// for all other methods: {
public Object foo(Object bar) {
return delegate.foo(bar);
}
}
For this to work, you need to intercept all creations of the widget you want to replace, which probably means creating a similar wrapper for the WidgetFactory. And you must be able to configure which WidgetFactory to use.
It also depends on no client trying to cast the IWidget back to DefaultWidget...
Only suggestions I can think of:
Dig through the library API to see if there's some way of overriding the defaults and sizing. Sizing can be confusing in swing (at least to me) , setMinimum, setMaximum, setdefault, setDefaultOnThursday, ... . It's possible there's a way. If you can contact the library designer(s) you might find an answer that will alleviate the need for unpleasant hacking.
Perhaps extend the factory only overriding some default sizing parameter? depends on the factory but it might be possible.
Creating a class with the same name might be the only other option, as others have pointed out it's ugly and you're liable to forget it and break stuff when you update the api library or deploy in a different environment and forget why you had the classpath set up that way.
You can try using tools like PowerMock/Mockito. If you can mock in tests, you can mock in production too.
However these tools are not really designed to be used that way, so you'll have to prepare the environment yourself and won't be able to use the JUnit runners like you do in tests...
Well, I keep trying to post suggestions, and then I see that they won't work or that you've already mentioned you tried them.
The best solution I can think of is to subclass WindowDisplayFactory, then in the subclass's createView() method, first call super.createView(), then modify the object returned to completely throw out the widget and replace it with an instance of the subclass that does what you want. But the widget is used to initialize stuff, so you'd have to go change all of those.
Then I think of using reflection on the returned object from createView() and trying to fix things up that way, but again, that's hairy because so much stuff was initialized with the widget. I think I would try to use that approach, though, if it was simple enough to justify it over copying and pasting.
I'll be watching this, plus thinking to see if I can come up with any other ideas. Java Reflection sure is nice, but it can't beat the dynamic introspection I've seen available in languages such as Perl and Python.

Categories

Resources