state design pattern from Java to Ruby - java

I have a working solution in java using a classic state design pattern and facing some difficulties translating it to ruby. I am new in ruby, but the diffuclty I believe lies in the differences on how patterns can be implemented in dynamic languages.
My interface is describing the actions the model can execute in every state:
public interface State {
public void doTask1(Model a_model);
public void doTask2(Model a_model);
public boolean doTask3(Model a_model, Helper a_helper);
}
Next, I implement the state interface and create concrete states of my logic:
public class LogicState1 implements State {
public void doTask1(Model a_model) {
a_model.implementTask1();
}
public void doTask2(Model a_model) {
a_model.implementTask2();
}
public boolean doTask3(Model a_model, Helper a_helper) {
a_model.useHelper();
return a_model.setState(a_model.getALogicstate(a_key));
}
As you can see, each concrete state can reach into the model and change its State. To avoid encapsulation issues, I instantiate my concrete states within the Model class, which has also a reference to the current State:
public class Model {
private State currentState;
public void setState(State state){
this.currentState = state;
}
public State getState(){
return currentState;
}
private final Map<String, State> everyState = new HashMap<String, State>();
public Model(String initialStateKey){
everyState.put("key1", new LogicState1());
everyState.put("key2", new LogicState2());
//...etc, instantiate and store all business logic states
this.currentState = everyState.get(initialStateKey);
}
public State getALogicState(String key){
return everyState.get(key);
}
public void useHelper(){...}
A client would use the Model like this:
public void run(Model a_model) {
a_model.getState().doTask1(a_model);
}
I think all of the above Java is straightforward, but now I am attempting to port this design into Ruby. I am aware of the differences in type-checking, and how modules and mixins are supposed to work in Ruby in contrast to Java's interfaces.
I have also found out about the State design pattern in Ruby in the pickaxe book.
Now I am a bit confused about which is the best way to try such conversion. I am still thinking inside the Java box, and wondering if I should have my concrete implementation of each state in a different .rb file and then require it in the client class?
Is there a way to implement the above without using the delegate.rb library?
Any suggestions on how to start with my conversion will be enthusiastically appreciated.

To translate this to ruby you can just leave out the interface and keep everything else as is. I.e. each state is a class that defines the methods do_task_N and doesn't otherwise have a connection to the other state classes (meaning you don't have to "emulate" the common interface by mixing-in a module or anything, you simply don't need it at all).
I am still thinking inside the Java
box, and wondering if I should have my
concrete implementation of each state
in a different .rb file and then
require it in the client class?
That sounds fine, yes.

I you trying to port a specific program from Java to Ruby or are you trying to learn to write Ruby?
If #1, why?
If #2, I would recommend that you work with existing Ruby code in order to learn the Ruby style. I highly recommend Ruby on Rails for this, since it is a very well written framework.
I learned a lot of lessons from Rails, which I can use even when I write other kinds of programs and in other languages.

Related

Identification of a service

Service interface:
public interface UserInterface {
void present();
void onStart();
void onStop();
}
I have two implementations: TextUserInterface and GraphicalUserInterface.
How can I identify the one I want to use when I launch my program? Source
private static void main(String[] args) {
ServiceLoader<UserInterface> uiLoader = ServiceLoader.load(UserInterface.class);
UserInterface ui = uiLoader.? //what to do to identify the one I want to use?
}
I was thinking of introducing an enum with the type of UI, so I could just iterate through all services and pick the one I'd like to, but isn't this approach just a misuse of services? In this case when I want to pick GraphicalUserInterface I could just skip the ServiceLoader part and just instantiate one. The only difference I see is fact that without services, I'd have to require the GraphicalUserInterface module, which "kind of" breaks the encapsulation.
I don't actually think that it would be a misuse of it. As a matter of fact, what you get from ServiceLoader.load(...) method is an Iteratable object, and if you need for a specific service, you will have to iterate through all the available instances.
The idea of the enum is not that bad, but I suggest that you take advantage of the Java stream and filter for the instance you need. For example, you might have something like that:
enum UserInterfaceType {
TEXT_UI, GRAPH_UI;
}
public interface UserInterface {
UserInterfaceType getTypeUI();
...
}
// In your main method
ServiceLoader<UserInterface> uiLoader = ServiceLoader.load(UserInterface.class);
UserInterface ui = uiLoader.steam()
.filter(p -> p->getTypeUI() == <TypeUIyouNeed> )
.findFirst()
.get();
That is open to a number of possibilities, for example you can put this is a separated method, which receives in input a UserInterfaceType value, and it can retrieve the service implementation based on the type enum value you passed.
As I said, that is just the main idea, but definitely you are not doing any misuse of the ServiceLoader.

How to add functionality of Java implementation which changing existing code?

Let's say I've an implementation of fund transfer. Now I want to add authentication functionality which should be done before fund transfer (considering we are already receiving username and password in existing request). Which pattern should we use and how we can achieve this without modifying calling class and existing implementation?
What I can think of at this moment is using decorator pattern after extending implementation class, but I believe still we will be required to modify the calling class.
Please find existing Interface and classes.
package sb.test.demo.fundtransfer;
public interface FundTransferService {
public boolean makeTransfer(TransferRequest request) throws Exception;
}
package sb.test.demo.fundtransfer;
public class FundTransferServiceImpl implements FundTransferService {
#Override
public boolean makeTransfer(TransferRequest request) throws Exception {
//Dummy Code
System.out.println("TransferDone");
return true;
}
}
package sb.test.demo.fundtransfer;
public class TestTransfer {
public static void main(String[] args) throws Exception {
TransferRequest request = new TransferRequest();
request.setSourceAccount(123456);
request.setDestinationAccount(654321);
request.setTranserAmount(1000);
request.setUserName("user1");
request.setPassword("pass1");
FundTransferService fts = new FundTransferServiceImpl();
fts.makeTransfer(request);
}
}
Now, I want want extend FundTransferServiceImpl to createFundTransferServiceNEWImpl which will add authentication.
package sb.test.demo.fundtransfer;
public class FundTransferServiceNEWImpl extends FundTransferServiceImpl {
#Override
public boolean makeTransfer(TransferRequest request) throws Exception {
//Dummy Code
System.out.println("Authenticating..");
super.makeTransfer(request);
System.out.println("TransferDone from NEW..");
return true;
}
}
Now, without changing TestTransfer.java and FundTransferServiceImpl.java how can I invoke makeTransfer of FundTransferServiceNEWImpl to add authentication? Or, is there any other way to achieve the same?
Please can anyone help me on this?
Thanks in advance!
you can make "FundTransferServiceNEWImpl" also implement the interface "FundTransferService" and provide the implementation that you wish in this only, if this was what you asked for!!
Now, without changing TestTransfer.java and FundTransferServiceImpl.java how can I invoke makeTransfer of FundTransferServiceNEWImpl to add authentication?
You can't without changing the bytecode of either TestTransfer (the caller) or FundTransferServiceImpl (the callee).
There are two ways to change the bytecode.
You can
edit the source file and compile
edit the bytecode before the class is loaded
Edit the source file
I would suggest to edit the TestTransfer class. The problematic line is
FundTransferService fts = new FundTransferServiceImpl();
because this line introduces the dependency from TestTransfer to FundTransferServiceImpl.
I would also suggest to implement the decorator by composition and not inheritence. E.g.
public class AuthenticationFundTransferServiceWrapper implements FundTransferService {
private FundTransferService fundTransferService;
public AuthenticationFundTransferServiceWrapper(FundTransferService fundTransferService){
this.fundTransferService = fundTransferService;
}
public boolean makeTransfer(TransferRequest request) throws Exception {
//Dummy Code
System.out.println("Authenticating..");
fundTransferService.makeTransfer(request);
System.out.println("TransferDone from NEW..");
return true;
}
}
The advantage is that the AuthenticationFundTransferServiceWrapper does only depend on the interface FundTransferService and not the implementation. This reduces dependencies and makes the class more flexible.
Editing the byte code
Editing the bytecode before the class is loaded is possible.
Take a look at
AOP (aspect oriented programming)
AspectJ
ASM (bytecode manipulation)
cglib
So you've identified decorator pattern and this answer implemented decorator correctly, but as this is a SOLID principles question I'm going to point out the flaw in that option.
To see the flaw in either inheritance or decorator, consider what happens when the authorization fails. If it throws a new exception type, that is a Liskov Substitution Principle Violation. If it changes the behavior by silently not transferring the funds, that is also an LSP violation. If you're going to rely on the boolean returned, you're not going to get a useful failure message back to the user or system admin.
As I see it, there is no way the client code can avoid knowing that the new implementation is checking authorized as it needs to handle either a new exception, or different return values.
Given that, I would recommend you add a new class, like this:
public final class TransactionAuthorizationService {
private final FundTransferService fundTransferService;
public AuthenticationFundTransferServiceWrapper(FundTransferService fundTransferService){
this.fundTransferService = fundTransferService;
}
public boolean authorizeAndMakeAndTransfer(TransferRequest request) throws Exception {
//Dummy Code
System.out.println("Authenticating..");
fundTransferService.makeTransfer(request);
System.out.println("TransferDone from NEW..");
return true;
}
}
Advantages:
Where before client code dealt with the interface FundTransferService you would have no idea until runtime which implementation they had and whether they would be authorizing transactions, now the client code now deals with the TransactionAuthorizationService and they call authorizeAndMakeAndTransfer so it is very clear.
As our new class is not implementing an existing interface, there is no Liskov Substitution Violation and is free to return different values or throw different exceptions.
Other tips:
Stop decorating methods with throw alls: throws Exception
Don't use InterfaceImpl as class names, look for what makes them concrete over the abstract interface.

Create a library for new built-ins Jena

I have made some new built-ins for Jena. I would like to create a library where I can put all of them.
How can I do that ? And how can I create my rules in this case ? Need I to import some files in the rule file?
Please note that, as this question is extremely broad, my answer is merely a set of suggestions towards an overall design. First, we'll begin with how Jena does it.
Apache Jena stores its rule files as classpath resources within its distribution jars. jena-core has a package (directory) called etc in which it stores several rules files. The reasoners that Jena has implemented are effectively just the GenericRuleReasoner with a specific rule set. For example, FBRuleReasoner#loadRules() method is used to retrieve the ruleset that this reasoner will utilize. You should look at where it is called from in order to figure out how you would use such a paradigm.
In your system, I'd suggest constructing your own implementation of ReasonerFactory (let's call it MyReasonerFactory). In MyReasonerFactory, you could have a static initialization block that will register the Builtins for your domain-specific reasoner. When someone calls ReasonerFactory#create(Resource), you can load your rules from the classpath and then create a GenericRuleReasoner that utilizes those rules.
Some pseudo-code (that may not compile) follows:
public class MyReasonerFactory implements ReasonerFactory
private static final String RULE_LOC = "/some/directory/in/my/jar/filename.extensiondoesntmatter";
static {
// register your builtins
}
#Override
public RuleReasoner create(Resource r) {
final GenericRuleReasoner reasoner = new GenericRuleReasoner(this, r);
reasoner.setRules(FBRuleReasoner.loadRules(RULE_LOC));
return reasoner;
}
#Override
public String getUri() {
return "urn:ex:yourReasoner";
}
#Override
public Model getCapabilities() {
// Your capabilities are identical to GenericRuleReasoner's
return GenericRuleReasonerFactory.theInstance().getCapabilities();
}
}

Java Registry Class?

I'm fairly new to Java. I'm coming from PHP and I used to create registry classes in php using the magic __get and __set methods. So that other parts of the system can easily do:
registry.foo = new Foo();
I should mention I'm trying to create game engine. Here is my registry in Java atm:
class Registry {
private static Map<String, Object> box = new HashMap<String, Object>();
public static Object get(String key) {
if (Registry.box.get(key) != null) {
return Registry.box.get(key);
}else {
return null;
}
}
public static void set(String key, Object o) {
Registry.box.put(key, o);
}
}
Then for the other parts of the system to access the registry, I currently need this whole thing:
((Object) Registry.get("Object")).doSomething();
Which is really a lot of code. In php this would be accomplished by simply:
Registry.foo.doSomething();
Any way to make this a bit more simpler? I guess I could make public fields, but then the regsitry class would need to implicitly create these fields as the possibility of new objects may need to be added which are unknown to the registry class itself, which is.. annoying :P
Thanks in advance!
This is a two pronged problem:
Java is a statically type language, and does not offer in-language flexibility for defining objects at runtime (you can use a library to synthesize classes at runtime, but, see #2)
A global registry for objects defeats a lot of safeties in a type-safe language. If your entire application centers around getting and putting objects into a global Map, there likely safer and less-coupled designs.
How can this be solved?
Redesign your application structure to not need a global map.
Use a dynamic language subset for Java (such as Groovy).
Use Scala 2.10 (JVM compatible) which features a Dynamic type which does exactly what you want.
First of all this method is too verbose:
public static Object get(String key) {
if (Registry.box.get(key) != null) {
return Registry.box.get(key);
}else {
return null;
}
}
It could be just:
public static Object get(String key) {
return Registry.box.get(key);
}
But second, this is definitely a bad design. Global repository - doesn't sound reasonable. A storage of objects of all types by string key - it's terrible.
Any way to make this a bit more simpler?
Not in any practical way. Java is a statically typed language, and the structure of objects has to be known up front. The very idea of an equivalent of PHP's __get and __set is antithetical to the language.
For what it's worth, your "registry" looks like bad design anyway. (Admittedly making some pretty wild assumptions from the little code you've shown.) You shouldn't need a global repository of what appear to be unrelated objects. You should consider some sort of dependency injection instead.
Based on your comment, instead of structuring your code like this:
class World implements GameSystem {
public void update() {
Registry.get("game").doSomething();
}
}
you should do:
class World implements GameSystem {
Game game;
public World(Game game) { // and other dependencies
this.game = game;
}
public void update() {
this.game.doSomething();
}
}
The idea is that components of your program don't really have any business knowing how to find the other components. It also makes dependencies between the components explicit, and helps you avoid circular dependencies.

Java Design Patterns: Facade

I'm trying to make a simple ordering system, and because it's an assignment it is a delimitation that I shouldn't make DB and GUI, but I need to implement at least 4 design patterns. One of my decisions was to use Facade. As far as I understand the Facade class is kind of controller and this is what i have so far:
package model;
import java.util.ArrayList;
public class Facade {
ClientsList clients;
OrdersList orders;
ProductsList products;
ArrayList<Orders> orderlist;
public Facade() {
clients = new ClientsList();
orderlist=new ArrayList<Orders>();
orders = new OrdersList(orderlist);
products = new ProductsList();
}
public int ClientsSize() {
return clients.size();
}
public int OrdersSize() {
return orders.size();
}
public void addClients(Clients client) {
clients.add(client);
}
public void addOrders(Orders order) {
orders.add(order);
}
public void removeClients() {
clients.remove();
}
public void removeOrders() {
orders.remove();
}
public String next() {
return orders.it();
}
}
The other classes in my model package are Orders, OrdersList, Clients, Clientslist, Products and ProductsList and in the *List classes I'm holding the infromation in ArrayList. So my question is: is this code a Facade?
A facade is supposed to shield me from knowing about certain classes and the operations they implement. In your example, I may not need to know about ClientList but I do need to know about Client, Product and Order. It would be better if those classes were hidden away from me so I just need to talk to the facade.
Write an additional interface so developers dont have to work with the implementation of your facade:
public interface OrderService {
//methods your co-developers should be able to use
}
public class Facade implements OrderService {
//methods your co-developers dont want to know about
}
In your code use the interface and not the impl.
The goal of a facade is to shield the implementation of functionality in a certain component. A facade normally provides an interface to 'the outside world'. I don't know the rest of your code, but the above example could be a facade.
Say you are building a component which fetches message from social media. You could build a facade with a method 'GetMessage(string keyword)' which (obviously) returns a list of messages, regardless of the social media source. The client of this component doesn't care how the component gets data from social media, he just wants messages. Methods like 'SearchFacebook' or 'SearchTwitter' can be hidden, as the client has no interest in calling these methods. However, 'GetMessages' can use them to search Facebook and Twitter, build a list of the results of those two and return it to the client.
For another good example, check the wiki page: http://en.wikipedia.org/wiki/Facade_pattern
Intent of facade:
Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.
Wrap a complicated subsystem with a simpler interface.
The functionality you are providing are matching with above points, so from my view It is a Facade.
In your example you are exposing sub-system(OrdersList, ProductsList) functionality though Facade.
To get more knowledge about facade design pattern, read "Head First Design Patterns"

Categories

Resources