I'm currently in the process of making a pretty large Akka based Java application and I'm running into a couple issues that bug me to no end.
My current package layout looks kinda like this:
My Mobile class serving as the supervisor of the actors inside the actors package.
Since I don't want to create a new set of Actors for every HttpClient and Account, I pass those around in message objects, which are stored in the messages package, together with the endpoint ActorRef that receives the final result. This does however create a very cluttered messages package with a different message for each actor. Eg. MobileForActor1, Actor1ForMobile, MobileForActor2 etc. Now my question is, is there a Convention to use for this sort of stuff that deals with this problem and is my structure (Mobile->Actor1->Mobile->Actor2->etc.) the way Akka wants it to be or do I have to just sort of waterfall the messages (Mobile->Actor1->Actor2->etc.)?
Right now I'm sending a ConnectMessage to my Mobile actor which then sends it to Actor1, Actor1 processes it and sends a new message back to Mobile, Mobile sends that response then to Actor2 and the cycle continues with a new message being created based on the old message. Eg. new Message2(message1.foo, message1.bar, message1.baz, newComputatedResult, newComputatedResult2, etc);
Is this good practice or should I include the old instance (which may contain info that isn't useful anymore) and include the new stuff? Eg. new Message2(message1, newComputatedResult, newComputatedResult2, etc);
Or should I do something completely different?
I thought about using TypedActors but those require the use of a waterfall pattern and I don't know how I would pass on the ActorRef of the listener that wants to receive the final result.
I hope I made myself understandable enough because English is not my maiden languages and that the question is clear to everyone.
I'm a beginning Akka developer and love the idea but since the documentation doesn't cover this very well, I figured this would be the best place to ask. Thanks for reading!
I will venture a few comments in response to this because I've dealt with the same issues in my learning curve of Akka. I think you're asking for some rules of thumb so mine are contained herein.
First, creating actors is incredibly cheap; they are very lightweight. So, why not create one for each HttpClient and Account and give them suitable names derived from their identity? This also avoids you having to pass them around as much, probably, decluttering your code.
Second, keep your message names short, focused and starting with a verb. Each message should tell the actor to do something so you want the name to reflect that by using a verb.
Third, sets of messages go with the actor. I usually declare them in the actor class's companion object so that using them is like ActorClass.MessageName unless it is within ActorClass and then it is just MessageName.
Fourth, append a counter to the name of an actor. I often just combine a counter (use AtomicInteger) with the name of the type (Car-1, Car-2, etc.).
If the hierarchy is important to you, I would recommend only appending the parent actor to the name. Something like Phone-1-in-Car-7 meaning Phone-1 is contained within Car-7. You can then assemble the hierarchy both programmatically and manually by following the parent links.
I think "Message" in ConnectMessage is redundant. Just make the message name be "Connect" or even better "ConnectToThing" (whatever Thing is, if that's relevant).
I wouldn't compound your message names too much like you're suggesting with Message2. Use the minimal amount of information to be useful to whomever is going to read those names. I think the lack of response to this may have resulted from this part of your question. I found it confusing as a lot of detail is missing.
Hope this helps.
Related
dear stackoverflow community.
Currently, I am working on a project. This project shall have a server and clients connecting to it. Because of their simplicity, I'd like to use Java's integrated ServerSockets and Sockets.
In my project, data shall be sent from the client to the server and opposite.
My initial idea is to just send JSON and then parse it as receiver and get the data from that.
I'm a little unsure about that though, since JSON isn't something that's integrated into Java, but comes from Java script. Also, I'm currently using a Multithreaded-Socket-Server, so I have a ClientHandler Thread class. In that class, the messages were received, parsed and the "action" parameter was read out of the JSON and then I did a switch statement with multiple actions and their functions. I don't think that's a good way of doing that either.
So, my question is:
How can I do that better, and maybe do I have to use something else?
Thanks in advance.
It is true that JSON grew out of JavaScript, but it is a reasonable definition language on its own and I don't see any reason you shouldn't use it. There are libraries for parsing it so you don't have to.
Assuming your JSON structures are different for different purposes, and complex enough to need different classes to represent them, I like the idea of the JSON having a parameter that identifies the class to which it belongs, after which you can hand off parsing to a class that understands the designated output. Then a class can read the JSON, get the type, and some the specific parsing routine can go from there to an object created for the purpose.
I don't see anything wrong with an action string, either; it's served well enough for Swing and some other UIs, after all. Instead of branching out to a function, depending on complexity again, you could have action classes that all implemented an interface, and the action 'verb' could tell you which one (out of a map, say?) to get and execute the 'performAction()' method on or whatever you want to call it.
I don't know how clear this is from a quick description; would be willing to chat about it in an SO chat room if you care about it.
I am reading the headfirst design patterns book.
I observe that the client is shown analogous to a hotel customer, who creates an order(command) object, the waitress(invoker) picks it and calls its execute() method which in turn calls the chef's cook() method(chef=receiver)
In the command pattern class diagram, I can see client is associated with Receiver as well as the ConcreteCommand class. I am unable to get the example because in real world, a customer is not supposed to know about the cook and set the instructions for him. Other concern is that in the command pattern class diagram, I observe that Client is not shown associated with Invoker, but in the attached java program I can see the Invoker reference in the Client class.
Totally confused about what Client module does in the command pattern. Clear about the rest 4 modules.
Read this: http://www.oodesign.com/command-pattern.html
Client creates a ConcreteCommand object and sets its receiver [...] The Client asks for a command to be executed.
It even has sample code that show what the client does:
The client creates some orders for buying and selling stocks (ConcreteCommands). Then the orders are sent to the agent (Invoker). [...]
public class Client {
public static void main(String[] args) {
StockTrade stock = new StockTrade();
BuyStockOrder bsc = new BuyStockOrder (stock);
SellStockOrder ssc = new SellStockOrder (stock);
Agent agent = new Agent();
agent.placeOrder(bsc); // Buy Shares
agent.placeOrder(ssc); // Sell Shares
}
}
You've stumbled upon the challenge with demonstrating design patterns with analogy, by a single concrete example, or with object diagrams. Except for very simple patterns, the concepts and examples usually don't map perfectly to all useful instances of the pattern.
I highly recommend that you pick several sources to learn any of the more complex design patterns. Every explanation is going to have strengths and weaknesses, and you'll probably get a more accurate picture if you take several viewpoints into account. There are plenty of free sources available on the Internet, so you probably don't need to buy additional books (except, eventually, the original Design Patterns book, for reference purposes).
What isn't clear in the diagram is that the Client, the Invoker, and the Receiver are abstract concepts, and don't have a single form that always applies in every case. In any particular implementation of the command pattern, most of these roles are going to be present (except maybe the Receiver - it is possible that the command is self-contained). You may even be able to point out a specific bit of code that maps to each of these roles, but it's going to map differently in every application. It may even map differently in separate parts of the same application.
There are parts of the diagram you shared that I have problems with, because they are not always true. The Client might not directly access or even know about the Receiver. The Client might also not know about specific ConcreteCommand objects. The Client might know how to ask for an instance of a command, and it might know some information that helps pick the right command. However, the client might in some cases be oblivious to which ConcreteCommand object was executed, especially if you combine the command pattern with the AbstractFactory pattern.
in real world, a customer is not supposed to know about the cook and set the instructions for him
Analogies and models tend to break down or become confusing when you compare them strictly to reality. It is best to try to figure out what the model is trying to accomplish, and which possible interpretation of reality that the model is trying to account for.
Also, not all models/analogies are any good :) Sometimes they don't actually get the job done.
I observe that Client is not shown associated with Invoker
This is perfectly valid in some implementations of the pattern. The code that eventually calls execute() may not be the same code that is capable of accepting actions.
The diagram may show a single box, but in the restaurant analogy, the waiter, the cooks, the busboys, the host, the cashier, etc, are all a part of that Invoker role.
The problem with the diagram is that the client eventually has to pass the command off to the invoker. The invoker itself might have a way to accomplish this, or there may be some sort of system in between (like a command queue). Either way, in their explanation, the invoker role handles both things, and the client must therefore know about the invoker.
Finally:
What does the client do in Command Pattern?
The Client is responsible for knowing that it wants a command to be done
The Client is responsible for knowing how to pick which command gets done, and get an instance of it (even if the client delegates the actual construction of that ConcreteCommand to some other part of the system)
The Client is responsible for knowing how to pass off a command so that it will eventually be invoked (passing it to some object in the Invoker role, even if that command eventually gets passed off to some other object that actually calls execute())
The Client is responsible for actually handing off the command to the Invoker (whether it is directly handed off, or passed off to some intermediate part of the system first)
So the idea of a client is in opposition to the idea of a server. (for get the restaurant metaphor for a minute). The server is the centralized application, the client is the interface presented on a users machine. The client machine or GUI signals wither a receiver (middle man) or your program directly to make things happen.
I hope this makes things a little clearer.
Within Java you can create an Observer-Observable set of classes in which the Observable can call the Observer. You can also in java explicitly reference an owning class instance in a child instance of another class and call the owning class instance's public functions.
Which is the better approach to take? Which is more beneficial in different scenarios, one example being Multi-Threading?
The Observer Pattern should be used whenever you don't know or don't care who is observing you. This is the key-concept in event-driven programming. You don't have any control of who is observing or what they do when you broadcast your events. Like you already mentioned in your comments, this is great for decoupling classes.
An example of a usage could be in a plugin-architecture:
You write a basic mail-server that broadcasts whenever a mail is received. You could then have a spam-plugin that validates the incoming mail, an auto-reply service that sends a reply, a forward service that redirects the mail and so on. Your plain mail server (the observable) doesn't know anything about spam, replies or forwarding. It just shouts out "Hey, a new mail is here" not knowing if anyone is listening. Then each of the plugins (the observers) does their own special thing, not knowing anything about each other. This system is very flexible and could easily be extended.
But the flexibility provided by the Observer Pattern is a two-edged sword. In the mail-server example, each plugin handles the incoming mail in total isolation from each other. This makes it impossible to setup rules like "don't reply or forward spam" because the observers doesn't know about each other - and even if they did, they wouldn't know in what order they are executed or has completed. So for the basic mail-server to solve this problem, It'll need to have references to the instances that does the spam/reply/forward actions.
So the Observer Pattern provides flexibility. You could easily add a new anti-virus plugin later, without having to modify your plain mail server code. The cost of this flexibility is loss of control of the flow of actions.
The reference approach gives you total control of the flow of actions. However you would need to modify your plain mail server code if you ever need to add support for an anti-virus plugin.
I hope this example gives you some ideas of the pros and cons of each approach.
In regards to multi-threading, one approach isn't favorable over the other.
I am trying to design a simple FIX message encoder and decoder to encode (convert to FIX) and decode (convert from FIX) my business domain Order objects. I have designed something, but I am not able to achieve the beautiful design I want. Wanted to see if others who have experience building this kind of things have any better design ideas.
This is what I roughly have: a business Object Order, QuickFIX object Message.
I need to generate NewOrder/Cancel/Replace messages and the message could be different for different exchanges.
I can have ReplaceEncoder --> NewOrderEncoder --> AbstractEncoder, CancelEncoder --> AbstractEncoder.
But if I want another dimension to this, like having custom message generation for different exchanges, then it results in too many combinations of hierarchies.
Is my only bet is to mundanely write different code for different exchanges? How others achieve this? Thanks.
I think you will probably come across a similar problem that we have. That is that each FIX implementation is different. Some use 4.2 others 4.4, some use some tags others ignore them, some use many of their own tags others use very few. What we have done is created general FIX sessions with subclasses for FIX 4.2 and 4.4 and then subclasses for each specific sessions (ie individual brokers). That gives us a reasonable amount of reuse of code for sending and receiving FIX messages. With just the specifics changed for things like handling account names and passwords etc.
For message generation we have a factory method that returns and adapter. All the adapters have the same API which will convert our Business order object in to a FIX Message object. Of course each adapter is specific to the API of the broker. I guess we could probably reuse some code between the adapters but currently we don't.
Is my only bet is to mundanely write different code for different exchanges?
Certainly not. In a FIX message there are compulsory and non compulsory fields. You cannot negotiate on the required fields because then you could not guarantee the authenticity and completeness of the messages. Now I am not saying this is impossible, many counter parties have their own specific user level agreements with exchanges for their own specific messages.
With Quickfix, the XML data dictionary from where the engines confirms the completeness of the messages, is in your hand. Tweak it for your own requirements. You would certainly have multiple sessions. I am not sure if this is possible, haven't tried it myself, does different sessions allow different data dictionaries ? If yes, then use them for different counter parties. If that isn't possible, one way which crosses my mind is add extra code for processing your specific fields, not the whole message, in messages expected from certain counter parties.
One place where I had worked, we were using something on these lines. Receive whatever version you may, but once the message is received convert it into a specific version of FIX message, which only exists inside your system. So your engine basically reads only 1 FIX version of messages. But the added complexity is you have to code a converter. I am not sure how feasible is that for you.
FIX is an extraordinarily slippery protocol when it comes to message definitions.
In practice, every institution that offers a FIX interface has made modifications to the default message set. That means, for instance, a FIX4.4 NewOrderSingle message from counterparty A may have different fields than one from counterparty B.
In fact, counterparty A may have made up some fields whole-cloth and added them in. For any new counterparty, there's a chance you'll encounter fields that you've never seen before.
I've written a few adapters for a few different exchanges, and unfortunately, you're really forced to handle them individually. You may be able to capitalize on some commonalities, but you can't make any assumptions on that until you've reviewed their FIX interface's specs.
So, short answer to your question:
Is my only bet is to mundanely write different code for different exchanges?
Yep, pretty much.
What we ended up doing was writing a base fix layer that applies only the required fix tags. In the fix spec certain tags are flagged as required for each message type.
Once this message had been created we apply a filter to the message that is specific to a broker and instrument type.
ie if you trade options and equities with Goldman and JPMorgan you'd write the following filters:
Goldman-equity
Goldman-option
JPMorgan-Equity
JPMorgan-option
Each would apply vendor and instrument specific fields to the base message.
I have an existing Protocol I'd like to write a java Client for. The Protocol consists of messages that have a header containing message type and message length, and then the announced number of bytes which is the payload.
I'm having some trouble modeling it, since creating a Class for each message type seems a bit excessive to me (that would turn out to be 20+ classes just to represent the messages that go over the wire) I was thinking about alternative models. But I can't come up with one that works.
I don't want anything fancy to work on the messages aside from notifying via publish subscribe when a message comes in and in some instances reply back.
Any pointers as to where to look?
A class for each message type is the natural OO way to model this. The fact that there are 20 classes should not put you off. (Depending on the relationship between the messages, you can probably implement common featues in superclasses.)
My advice is to not worry too much about efficiency to start with. Just focus on getting clean APIs that provide the required functionality. Once you've got things working, profile the code and see if the protocol classes are a significant bottleneck. If they are ... then think about how to make the code more efficient.