Our application is getting complex, it has mainly 3 flow and have to process based on one of the 3 type. Many of these functionalities overlap each other.
So currently code is fully of if-else statements, it is all messed up and not organised. How to make a pattern so that 3 flows are clearly separated from each other but making use of power of re-usability.
Please provide some thoughts, this is a MVC application, where we need to produce and consume web servicees using jaxb technology.
May be you can view the application as a single object as input on which different strategies needs to be implemented based on runtime value.
You did not specify what your if-else statements are doing. Say they filtering depending on some value.
If I understand your question correctly, you want to look at Factory Pattern.
This is a clean approach, easy to maintain and produces readable code. Adding or removing a Filter is also easy, Just remove the class and remove it from FilterFactory hashmap.
Create an Interface : Filter
public interface Filter {
void Filter();
}
Create a Factory which returns correct Filter according to your value. Instead of your if-else now you can just use the following :
Filter filter = FilterFactory.getFilter(value);
filter.filter();
One common way to write FilterFactory is using a HashMap inside it.
public class FilterFactory{
static HashMap<Integer, Filter> filterMap;
static{
filterMap = new HashMap<>();
filterMap.put(0,new Filter0());
...
}
// this function will change depending on your needs
public Filter getFilter(int value){
return filterMap.get(value);
}
}
Create your three(in your case) Filters like this: (With meaningful names though)
public class Filter0 implements Filter {
public void filter(){
//do something
}
}
NOTE: As you want to reuse some methods, create a FilterUtility class and make all your filters extend this class so that you can use all the functions without rewriting them.
Your question is very broad and almost impossible to answer without some description or overview of the structure of your application. However, I've been in a similar situation and this is the approach I took:
Replace conditions with Polymorphism where possible
it has mainly 3 flow and have to process based on this one of the 3
type. Many of these functionalities overlap each other.
You say your project has 3 main flows and that much of the code overlaps each other. This sounds to me like a strategy pattern:
You declare an interface that defines the tasks performed by a Flow.
public interface Flow{
public Data getData();
public Error validateData();
public void saveData();
public Error gotoNextStep();
}
You create an abstract class that provides implementation that is common to all 3 flows. (methods in this abstract class don't have to be final, but you definitely want to consider it carefully.)
public abstract class AbstractFlow{
private FlowManager flowManager
public AbstractFlow(FlowManager fm){
flowManager = fm;
}
public final void saveData(){
Data data = getData();
saveDataAsXMl(data);
}
public final Error gotoNextStep(){
Error error = validateData();
if(error != null){
return error;
}
saveData();
fm.gotoNextStep();
return null;
}
}
Finally, you create 3 concrete classes that extend from the abstract class and define concrete implementation for the given flow.
public class BankDetailsFlow extends AbstractFlow{
public BankDetailsData getData(){
BankDetailsData data = new BankDetailsData();
data.setSwiftCode(/*get swift code somehow*/);
return data;
}
public Error validateData(){
BankDetailsData data = getData();
return validate(data);
}
public void onFormSubmitted(){
Error error = gotoNextStep();
if(error != null){
handleError(error);
}
}
}
Lets take example, suppose you have model say "Data" [which has some attributes and getters,setters, optional methods].In context of Mobile application ,in particular Android application there can be two modes Off-line or On-line. If device is connected to network , data is sent to network else stored to local database of device.
In procedural way someone can , define two models as OnlineData,OfflineData and write code as[The code is not exact ,its just like pseudo code ]:
if(Connection.isConnected()){
OnlineData ond=new OnlineData();
ond.save();//save is called which stores data on server using HTTP.
}
else{
OfflineData ofd=new Onlinedata();
ofd.save();//save is called which stores data in local database
}
A good approach to implement this is using OOPS principles :
Program to interface not Implementation
Lets see How to DO THIS.
I am just writing code snippets that will be more effectively represent what I mean.The snippets are as follows:
public interface Model {
long save();//save method
//other methods .....
}
public class OnlineData extends Model {
//attributes
public long save(){
//on-line implementation of save method for Data model
}
//implementation of other methods.
}
public class OfflineData extends Model {
//attributes
public long save(){
//off-line implementation of save method for Data model
}
//implementation of other methods.
}
public class ObjectFactory{
public static Model getDataObject(){
if(Connection.isConnected())
return new OnlineData();
else
return new OfflineData();
}
}
and Here is code that your client class should use:
public class ClientClass{
public void someMethod(){
Model model=ObjectFactory.getDataObject();
model.save();// here polymorphism plays role...
}
}
Also this follows:
Single Responsibility Principle [SRP]
because On-line and Off-line are two different responsibilities which we can be able to integrate in Single save() using if-else statement.
After loong time I find opensource rule engine frameworks like "drools" is a great alternative to fit my requirement.
Related
[See below for updates]
I am having a hard time defining a pattern. My colleague says it's adaptor pattern. I'm not sure. We're stuck mainly because we want to correctly name our components.
Question: Is it adapter pattern? If not what is it? If it is something else, is this the best way to implement the idea?
To put it in summary, it is a main component(is this the adapter?) that shares an interfaces with sub-components (are these providers?). The main components decides/orchestrates which of the sub-components are called. The main component behaves as some sort of "wrapper" to call one of the others that have the same interface. The instances of which are injected through the constructor.
Assumptions:
For simplicity, we will ignore DR/IoC for now, but we understand and apply the pattern/principle.
The code is not the best implemented form...feel free to suggest.
My use of the words main/sub does not infer some kind of inheritence...just bad naming on my part, if confusing.
It's language-agnostic, because I love contributions from C# and Java guys, and the knowledge they share.
I am using a Social Networking scenario where a main component gets stats on a hastag and instantiates the appropriate Social Sub Component (
There is a Social Component interface:
ISocialComponent
{
SomeStatsObject GetStats(string hashTag);
}
Social Sub-Components implement ISocialComponent Interface
Twitter Sub-Component
public class TwitterSubComponent : ISocialComponent
{
public SomeStatsObject GetStats(string hashTag)
{
return SomeMethodThatReturnsStatsObject(hashTag);
}
private SomeMethodThatReturnsStatsObject(string hashTag)
{
//... Twitter-specific code goes here
}
}
Facebook Sub-Component
public class FacebookSubComponent : ISocialComponent
{
public SomeStatsObject GetStats(string hashTag)
{
return SomeMethodThatReturnsStatsObject(hashTag);
}
private SomeMethodThatReturnsStatsObject(string hashTag)
{
//... Facebook-specific code goes here
}
}
Instagram Sub-Component
public class InstagramSubComponent : ISocialComponent
{
public SomeStatsObject GetStats(string hashTag)
{
return SomeMethodThatReturnsStatsObject(hasTag);
}
private SomeMethodThatReturnsStatsObject(string hashTag)
{
//... Instagram-specific code goes here
}
}
Main Component
There is a main social component object that calls any one of the Sub-Components (defined below) that implement the shared ISocialComponent interface
public class MainSocialComponent : ISocialComponent
{
//this is an enum
private RequestedNetwork _requestedNetwork{ get; set;}
//the SocialComponent instance is injected outside of this class
private readonly ISocialComponent _socialComponent;
public MainSocialComponent(ISocialComponent socialComponent)
{
_socialComponent = socialComponent;
}
public SomeStatsObject GetStats(string hashTag)
{
return _socialComponent.GetStats(hashTag)
/**** original code, kept for historical purposes****
switch(_requestedNetwork)
{
case RequestedNetwork.Twitter:
var twit = new TwitterSubComponent();
return twit.GetStats(hashTag)
break;
case RequestedNetwork.Facebook:
var fb = new FacebookSubComponent();
return fb.GetStats(hashTag)
break;
case RequestedNetwork.Instagram:
var in = new InstagramSubComponent();
return in.GetStats(hashTag)
break;
default:
throw new Exception("Undefined Social Network");
break;
}*/
}
}
Updates:
I see why some say it is Factory pattern because it is creating objects. I had mentioned that we use an IoC container and DR. It was my mistake to exclude that. I have refactored the code
As others have mentioned, this is part of the Factory/Service pattern which is pretty popular for Dependency Injection and Inversion of Control.
Right now though there is no reason to declare your sub components as non static, since you aren't saving your instances to anything.
So it seems to me unless you have missing code where you add the components to a list or something, you could just do this:
public static class InstagramSubComponent : ISocialComponent
{
public static SomeStatsObject GetStats(string hashTag)
{
return stuff;
}
}
public class MainSocialComponent : ISocialComponent
{
//this is an enum
private RequestedNetwork _requestedNetwork{ get; set;}
private static var Mappings = new Dictionary<string, Func<SomeStatsObject>> {
{ "Twitter", TwitterSubComponent.GetStats },
{ "Facebook", FacebookSubComponent.GetStats },
{ "Instagram", InstagramSubComponent.GetStats }
}
public SomeStatsObject GetStats(string hashTag)
{
return Mappings[hashTag].invoke();
}
}
}
Now if you are doing stuff like actually saving your instances of sub components to a list for later or whatever, then that changes everything. But I am not seeing that so there's no reason not to just make it all static if these methods are simple.
If they are very complex then you'll want to use dependency injection so you can unit test everything proper.
I believe you can extract creation of SubComponent into a Factory and pass this Factory to MainSocialComponent. Inside of the GetStats method, you will call _factory.Create(hashTag); and than call GetStats on the returned object.
This way you'll have factory pattern.
This is definitely not an adapter pattern.
An adapter pattern does the following in most cases :
• Works as a bridge between two incompatible interfaces.
• Allows classes with incompatible interfaces work together
Your case is more like a Factory pattern. You use high level abstraction and return the type of interface/component whenever you need to.
I was recently asked on a coding interview to write a simple Java console app that does some file io and displays the data. I was going to go to town with a DAO but since I never manipulate the data past a read, the entire idea of a DAO seems overkill.
Anyone know a clean way to ensure separation of concern without the weight of full CRUD when you don't need it ?
Looks like standard MVC pattern. Your console is the view, the code that reads file is the controller and the code that captures file line or whole file content is your model.
You can further simplify it as View and Model where model will encapsulate both file reading and wrapping its content into Java class.
How about Martin Fowler's Table Gateway pattern, explained here. Just include the find (Read) methods and miss create, insert, and update.
you can simply refer Command /Query pattern ,where commands are one which perform create update and delete operation seperately and Queries are introduce to read only purpose .
hence you implement what you need and left the others
This question was in interview so there was not much time for detailed design, As a minimum fulfillment of above concerns, following structure will provide flexibility. details could be filled as per the requirements.
public interface IODevice {
String read();
void write(String data);
}
class FileIO implements IODevice {
#Override
public String read() {
return null;
}
#Override
public void write(String data) {
//...;
}
}
class ConsoleIO implements IODevice {
#Override
public String read() {
return null;
}
#Override
public void write(String data) {
//... null;
}
}
public class DataConverter {
public static void main(String[] args) {
FileIO fData1 = null;// ... appropriately obtained instance;
FileIO fData2 = null;// ... appropriately obtained instance;
ConsoleIO cData = null;// ... appropriately obtained instance;
cData.write(fData2.read());
fData1.write(cData.read());
}
}
The client class uses only APIs of the devices. This will keep option of extending interface to implement new device wrapper (e.g. xml, stream etc)
Given I have a class that uses some kind of searcher to get and display a list of URLs, like this:
package com.acme.displayer;
import com.acme.searcher.SearcherInterface;
class AcmeDisplayer {
private SearcherInterface searcher;
public AcmeDisplayer(SearcherInterface searcher) {
this.searcher = searcher;
}
public void display() {
List<String> urls = searcher.getUrls();
for (String url : urls) {
System.out.println(url);
}
}
}
Whereas the SearcherInterface looks like the following:
package com.acme.searcher;
public interface SearcherInterface {
List<String> getUrls();
}
There's multiple implementations of these searchers. (One, for instance, only returns a hardcoded list of Strings for testing purposes).
Another one, however, performs HTTP Requests to whatever API and parses the response for URLs, like so:
package com.acme.searcher.http;
import com.acme.searcher.SearcherInterface;
public class HttpSearcher implements SearcherInterface {
private RequestPerformerInterface requestPerformer;
private ParserInterface parser;
public HttpSearcher(RequestPerformerInterface requestPerformer, ParserInterface parser) {
this.requestPerformer = requestPerformer;
this.parser = parser;
}
List<String> getUrls() {
InputStream stream = requestPerformer.performRequest();
return parser.parse(stream);
}
}
The splitting of such an HTTP request is done because of seperation of concerns.
However, this is leading to a problem: A Parser might only be built for a certain API, which is represented by a certain RequestPerformer. So they need to be compatible. I've fiddled around with generic types for such a structure now, i.e. having a TypeInterface that both arguments of HttpSearchers constructor should implement, but I didn't get it working... Another approach would be to just implement a check in one class if the other one is compatible with it, but that seems ugly.
Is there any way to achieve such a grouping of RequestPerformers and Parsers by the API they're handling? Or is there something wrong with the architecture itself?
Your HttpSearcher seems like such a device to group these 2 together. You could create a factory class that returns HttpSearcher and other classes like it, and code that factory to group the compatible RequestPerformers and Parsers together.
The reason why I wouldn't advice leveraging the type system, e.g. through generics, is that the type InputStream can guarantee nothing about the format/type of data it holds. Separating the responsibility of getting the raw data, and parsing seems like a good idea, but you will still have to 'manually' group the compatible types together, because only you know what format/type of data the InputStream will hold.
I have a "legacy" code that I want to refactor.
The code basically does a remote call to a server and gets back a reply. Then according to the reply executes accordingly.
Example of skeleton of the code:
public Object processResponse(String responseType, Object response) {
if(responseType.equals(CLIENT_REGISTERED)) {
//code
//code ...
}
else if (responseType.equals(CLIENT_ABORTED)) {
//code
//code....
}
else if (responseType.equals(DATA_SPLIT)) {
//code
//code...
}
etc
The problem is that there are many-many if/else branches and the code inside each if is not trivial.
So it becomes hard to maintain.
I was wondering what is that best pattern for this?
One thought I had was to create a single object with method names the same as the responseType and then inside processResponse just using reflection call the method with the same name as the responseType.
This would clean up processResponse but it moves the code to a single object with many/many methods and I think reflection would cause performance issues.
Is there a nice design approach/pattern to clean this up?
Two approaches:
Strategy pattern http://www.dofactory.com/javascript/strategy-design-pattern
Create dictionary, where key is metadata (in your case metadata is responseType) and value is a function.
For example:
Put this in constructor
responses = new HashMap<string, SomeAbstraction>();
responses.Put(CLIENT_REGISTERED, new ImplementationForRegisteredClient());
responses.Put(CLIENT_ABORTED, new ImplementationForAbortedClient());
where ImplementationForRegisteredClient and ImplementationForAbortedClient implement SomeAbstraction
and call this dictionary via
responses.get(responseType).MethodOfYourAbstraction(SomeParams);
If you want to follow the principle of DI, you can inject this Dictionary in your client class.
My first cut would be to replace the if/else if structures with switch/case:
public Object processResponse(String responseType, Object response) {
switch(responseType) {
case CLIENT_REGISTERED: {
//code ...
}
case CLIENT_ABORTED: {
//code....
}
case DATA_SPLIT: {
//code...
}
From there I'd probably extract each block as a method, and from there apply the Strategy pattern. Stop at whatever point feels right.
The case you've describe seems to fit perfectly to the application of Strategy pattern. In particular, you've many variants of an algorithm, i.e. the code executed accordingly to the response of the remote server call.
Implementing the Stategy pattern means that you have to define a class hierachy, such the following:
public interface ResponseProcessor {
public void execute(Context ctx);
}
class ClientRegistered implements ResponseProcessor {
public void execute(Context ctx) {
// Actions corresponding to a client that is registered
// ...
}
}
class ClientAborted implements ResponseProcessor {
public void execute(Context ctx) {
// Actions corresponding to a client aborted
// ...
}
}
// and so on...
The Context type should contain all the information that are needed to execute each 'strategy'. Note that if different strategies share some algorithm pieces, you could also use Templeate Method pattern among them.
You need a factory to create a particular Strategy at runtime. The factory will build a strategy starting from the response received. A possibile implementation should be the one suggested by #Sattar Imamov. The factory will contain the if .. else code.
If strategy classes are not to heavy to build and they don't need any external information at build time, you can also map each strategy to an Enumeration's value.
public enum ResponseType {
CLIENT_REGISTERED(new ClientRegistered()),
CLIENT_ABORTED(new ClientAborted()),
DATA_SPLIT(new DataSplit());
// Processor associated to a response
private ResponseProcessor processor;
private ResponseType(ResponseProcessor processor) {
this.processor = processor;
}
public ResponseProcessor getProcessor() {
return this.processor;
}
}
I am working on an application which has REST endpoints and for a Get-By-ID service, I am populating a resource (basically a POJO) by collecting data from the persistent store. Now, before sending the response back, I have to populate the HREF in the POJO resource. I want to do it in a generic way so that various other REST services (search etc.) can use it. I want to do this HREF population at a common place for reusability purpose. In a nutshell, my resource POJO can go through various massaging layers to have different state changed and finally sent back to the consumer.
Resource POJO --> Massager 1 --> Massager 2 --> Final Massaged POJO
Could someone help me to figure out a design pattern that can fit my problem.
I thought of Decorator pattern, but somehow it does not sail my ship.
~ NN
You could adapt Chain Of Responsability to your needs. Instead of having a series of processing objects which pass your POJO from one to another in case it cannot handle it, you could process your POJO and then pass it further.
abstract class Messager{
private Messager nextMessager;
void setNextMessager(Messager messager){
this.nextMessager = messager;
}
Messager getNextMessager(){
return this.nextMessager;
}
abstract void handle(Pojo pojo);
}
class FooMessager extends Messager{
void handle(Pojo pojo){
//operate on your pojo
if(pojo.getHref == null){
pojo.setHref("broken");
}
if(this.getNextMessager() != null){
this.getNextMessager().handle(pojo);
}
}
}
class BarMessager{
void handle(Pojo pojo){
//operate on your pojo
if(pojo.getHref().contains("broken")){
pojo.setHref(pojo.getHref().replace("broken","fixed"));
}
if(this.getNextMessager() != null){
this.getNextMessager().handle(pojo);
}
}
}
class Pojo{
private String href;
public Pojo() {
}
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
}
class Test{
public static void main(String[] args) {
Pojo pojo = new Pojo();
pojo.setHref(null);
Messager foo = new FooMessager();
Messager bar = new BarMessager();
foo.setNextMessager(bar);
foo.handle();
}
}
Even if the previous answers are good and does solve it, I want to propose you additional way if you want to go further. The communication between objects is very common, so a lot of concepts are out there and you can choose the one that fits best for your needs.
The Command pattern can help you with the encapsulation of a request as an object in
collecting data from the persistent store
It'll allow you to parameterize clients with queue or log requests.
The Mediator pattern can define your communication between the Massager 1 --> Massager 2 classes. By doing this it'll encapsulate your objects interaction. Also it promotes loose coupling by keeping objects from referring to each other explicitly, and it'll let you vary their interaction independently.
If you'll deal with how to notify change to Massager 1 --> Massager 2 classes
my resource POJO can go through various massaging layers to have different state changed
than the Observer pattern can define a dependency between your objects so that when one object changes state, all its dependents are notified and updated automatically.