Abstraction or Inheritance use case? - oop

I'm modeling a UDP communication server in VisualBasic.NET.
In my system I have 3 types of messages: basic, advanced and full messages.
Basic message is composed of: ID, Version and Serial Number.
Advanced message is composed of: basic message + NSeq, IDMsg, Size and CRC.
Full message is composed of: advanced message + Timestamp.
Each message have it own set of methods, but there are some method that are common to all kinds of messages.
In this case I should use inheritance since advanced and full messages all have the same proprieties of basic message or should I go for an abstraction?
I think these too concepts are not very clear after all.
Thanks for all help!!!

If the implementation of the common functionality is the same, use inheritence.
If you have common operations among objects but each has its own implementation then you can use Interfaces to treat the instances polymorphicly.

Related

What is the exact difference between 'Adapter' and 'Mediator" patterns?

I know that Adapter is a structural pattern and Mediator is a behavioral one. But as far I understood, what both of them are doing, is connecting two (or more) other classes which are potentially incompatible (not so maintainable) for direct communication.
Can some one give a close comparison between these two and point out the exact difference?
These are the links for Adapter and Mediator explanations in TutorialsPoint.
And these are sourcemaking explanations. Adapter, Mediator.
They don't have much in common, IMO.
A mediator is used to avoid coupling several components together. Instead of each component "talking" with each other directly (and thus having to know each other and to know how to communicate all with each other), each component talks to a single object: the mediator. The name is chosen on purpose: when you're fighting with your neighbor and can't communicate with him, you go see a mediator and instead of talking to each other, you both talk with the mediator, who tries fixing the issue.
An adapter is used to "transform" an object with an interface into an object with an other interface. Just like, for example, an electrical adapter which transforms a european power outlet into an american one, so that you can use your American shaver in Europe.
Simple example: you need to store a Runnable into a list of Callables. Runnable has a method run(). Callable has a method call(). You thus create an Adapter:
public class RunnableAdapter implements Callable {
private Runnable runnable;
public RunnableAdapter(Runnable runnable) {
this.runnable = runnable;
}
public void call() {
runnable.run();
}
}
JB Nizet already wrote a good answer. I just want to explain the differences in simpler words:
Mediator should be used when you don't know how to communicate with other objects or you aren't allowed to
Adapter should be used when you know exactly how to communicate with objects, but these objects might not support some communication methods or differ
Adapter Pattern is useful when we already have two code base one consumer code and other producer code but the format in which Consumer wish the product to be in is different from what Producer code is producing. Here as Producing code is already there in place and we do not wish to modify the existing code [ code closed for modification, open for extension ]. Adapter class can transform the product produced by Producer into format as expected by Consumer code. Format may be the APIs whose return type is different as per what Producer code and expectation of the consumer code. Adapter class uses the API of the producer code and transforms them as per the expectation of the consumer.
Now Mediator pattern is useful when we are in process of designing the architecture or while refactoring. It helps in easy and loosely coupled interaction of objects. Define an object [Mediator] that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
Can some one give a close comparison between these two and point out the exact difference?
The intent and checklist in sourcemaking links, which have been quoted in your question provides good insight.
Adapter convert the interface of a class into another interface clients expect
Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
isn't there something that implicitly means that mediator is an adapter that supports for than 2 classes. Due to this reason, Mediator can't act as an Adapter.
Mediator does not transform incompatible interface to compatible interface, what client expects unlike Adapter.
Mediator interacts with Collegues of same interface.
Mediator abstracts/centralizes arbitrary communication between Colleague objects
Related posts with code examples:
Mediator Vs Observer Object-Oriented Design Patterns
Difference between Bridge pattern and Adapter pattern

Deciding extent of coupling

I have a Component which has API exposed with some 10 functionality in all. I can think of two ways to achieve it:
Give out all these functionality as separate functions.
Expose only one function which takes an XML as input. Based on request_Type specified and the parameters passed in the XML, I internally call one of the respective functions.
Q1. Will the second design be more loosely coupled than the first ?
I always read about how I should try my components to be loosely coupled, should I really go to this extent to achieve lose coupling ?
Q2. Which one of these would be a better design in terms of OOP and why?
Edit:
If I am exposing this API over D-Bus for others to use, will type checking still be a consideration to compare the two approaches? From what I understand type checking is done at compile time, but in case when this function is exposed over some IPC, issue of type checking comes into picture ?
The two alternatives you propose do not differ in the (obviously quite large) number of "functions" you want to offer from your API. However, the second seems to have many disadvantages because you are loosing any strong type checking, it will become much harder to document the functionality etc. (The only advantage I see is that you don't need to change your API if you add functionality. But at the disadvantage that users will not be able to figure out API changes like deleted functions until run-time.)
What is more related with this question is the Single Responsiblity Principle (http://en.wikipedia.org/wiki/Single_responsibility_principle). As you are talking about OOP, you should not expose your tens of functions within one class but split them among different classes, each with a single responsibility. Defining good "responsibilities" and roles requires some practice, but following some basic guidelines will help you to get started quickly. See Are there any rules for OOP? for a good starting point.
Reply to the question edit
I haven't used D-Bus, so this might be totally wrong. But from a quick look at the tutorial I read
Each object supports one or more interfaces. Think of an interface as
a named group of methods and signals, just as it is in GLib or Qt or
Java. Interfaces define the type of an object instance.
DBus identifies interfaces with a simple namespaced string, something
like org.freedesktop.Introspectable. Most bindings will map these
interface names directly to the appropriate programming language
construct, for example to Java interfaces or C++ pure virtual classes.
As far as I understand, D-Bus has the concept of differnt objects which provide interfaces consisting of several methods. This means (to me) that my answer above still applies. The "D-Bus native" way of specifying your API would mean to exhibit interfaces and I don't see any reason why good OOP design guidelines shouldn't be valid, here. As D-Bus seems to map these even to native language constructs, this is even more likely.
Of course, nobody keeps you from just building your own API description language in XML. However, things like are some kind of abuse of underlying techniques. You should have good reasons for doing such things.

Using NSStringFromSelector to send method over a network

I'm currently making a client-client approach on some simulation with objective-c with two computers (mac1 and mac2).
I have a class Client, and every computer has a instance of the "Client" on it (client1,client2). I expect that both clients will be synchronized: they will both be equal apart from memory locations.
When a user presses a key on mac1, I want both client1 and client2 to receive a given method from class Client (so that they are synchronized, i.e. they are the same apart from it's memory location on each mac).
To this approach, my current idea is to make 2 methods:
- (void) sendSelector:(Client*)toClient,...;
- (void) receiveSelector:(Client*)fromClient,...;
sendSelector: uses NSStringFromSelector() to transform the method to a NSString, and send it over the network (let's not worry about sending strings over net now).
On the other hand, receiveSelector: uses NSSelectorFromString() to transform a NSString back to a selector.
My first question/issue is: to what extent is this approach "standard" on networking with objective-c?
My second question:
And the method's arguments? Is there any way of "packing" a given class instance and send it over the network? I understand the pointer's problem when packing, but every instance on my program as an unique identity, so that should be no problem since both clients will know how to retrieve the object from its identity.
Thanks for your help
Let me address your second question first:
And the method's arguments? Is there any way of "packing" a given
class instance and send it over the network?
Many Cocoa classes implement/adopt the NSCoding #protocol. This means they support some default implementation for serializing to a byte stream, which you could then send over the network. You would be well advised to use the NSCoding approach unless it's fundamentally not suited to your needs for some reason. (i.e. use the highest level of abstraction that gets the job done)
Now for the more philosophical side of your first question; I'll rephrase your question as "is it a good approach to use serialized method invocations as a means of communication between two clients over a network?"
First, you should know that Objective-C has a not-often-used-any-more, but reasonably complete, implementation for handling remote invocations between machines with a high level of abstraction. It was called Distributed Objects. Apple appears to be shoving it under the rug to some degree (with good reason -- keep reading), but I was able to find an old cached copy of the Distributed Objects Programming Topics guide. You may find it informative. AFAIK, all the underpinnings of Distributed Objects still ship in the Objective-C runtime/frameworks, so if you wanted to use it, if only to prototype, you probably could.
I can't speculate as to the exact reasons that you can't seem to find this document on developer.apple.com these days, but I think it's fair to say that, in general, you don't want to be using a remote invocation approach like this in production, or over insecure network channels (for instance: over the Internet.) It's a huge potential attack vector. Just think of it: If I can modify, or spoof, your network messages, I can induce your client application to call arbitrary selectors with arbitrary arguments. It's not hard to see how this could go very wrong.
At a high level, let me recommend coming up with some sort of protocol for your application, with some arbitrary wire format (another person mentioned JSON -- It's got a lot of support these days -- but using NSCoding will probably bootstrap you the quickest), and when your client receives such a message, it should read the message as data and make a decision about what action to take, without actually deriving at runtime what is, in effect, code from the message itself.
From a "getting things done" perspective, I like to share a maxim I learned a while ago: "Make it work; Make it work right; Make it work fast. In that order."
For prototyping, maybe you don't care about security. Maybe when you're just trying to "make it work" you use Distributed Objects, or maybe you roll your own remote invocation protocol, as it appears you've been thinking of doing. Just remember: you really need to "make it work right" before releasing it into the wild, or those decisions you made for prototyping expedience could cost you dearly. The best approach here will be to create a class or group of classes that abstracts away the network protocol and wire format from the rest of your code, so you can swap out networking implementations later without having to touch all your code.
One more suggestion: I read in your initial question a desire to 'keep an object (or perhaps an object graph) in sync across multiple clients.' This is a complex topic, but you may wish to employ a "Command Pattern" (see the Gang of Four book, or any number of other treatments in the wild.) Taking such an approach may also inherently bring structure to your networking protocol. In other words, once you've broken down all your model mutation operations into "commands" maybe your protocol is as simple as serializing those commands using NSCoding and shipping them over the wire to the other client and executing them again there.
Hopefully this helps, or at least gives you some starting points and things to consider.
These days it would seem that the most standard way is to package everything up on JSON.

sending data between server and client in twisted

I'm trying to transport data between server and client implemented with twisted. As far as I know, using self.transport.write([data]) will work only if data is a string. Is there any other way I can send an object of other type? Thank you!
Sockets carry bytes. That's the only kind of thing they carry. Any two endpoints of a TCP connection can only convey bytes to each other.
Bytes aren't the most useful data structure for every form of communication. So on top of this byte transport, we invent schemes for formatting and interpreting bytes. These are protocols.
Twisted represents protocols as classes, almsot always subclasses of twisted.internet.protocol.Protocol, which implement a particular scheme.
These classes have methods for turning something which isn't pure bytes into something which is pure bytes. For example, twisted.protocols.basic.NetstringReceiver is an implementation of the netstring protocol. It turns a particular number of bytes into bytes which represent both the number of bytes and the bytes themselves. This is a rather subtle protocol, since it's not instantly obvious that the byte count is information that needs to be conveyed as well.
These classes also interpret bytes received from the network, in their dataReceived method, according to the protocol they implement, and turn the resulting information into something more structured. NetstringReceiver uses the length information to accept exactly the right number of bytes from the network and then deliver them to its stringReceived callback as a single Python str instance.
Other protocols do more than NetstringReceiver. For example, twisted.protocols.ftp includes an implementation of the FTP protocol. FTP is a protocol geared towards passing file listings and files over a socket (or several sockets, actually). twisted.mail.pop3 implements POP3, a protocol for transferring email over sockets.
There are lots and lots of different protocols because there are lots and lots of different things you might want to do. Depending on exactly what you're trying to do, there are probably different ways to convert to and from bytes to make things easier or faster or more robust (and so on). So there's no single protocol that is ideal for the general case. That includes the case of "sending an object", since objects can take many different forms, and there may be many different reasons you want to send them, and many different ways you might want to handle things like mutation of an object you'd previously sent, and so on.
You probably want to spend a little time thinking about what kind of communication you need. This should suggest certain things about the protocol you'll select to do the communication.
For example, if you want to be able to call methods on Python objects that exist on the other side of a connection, then Twisted Spread might be interesting.
If you want something cross-language instead, and only need to convey simple types, like integers, strings, and lists, then XML-RPC (Twisted How-To) might be a better fit.
If you need a protocol that's more space efficient than XML-RPC and supports serialization of more complicated types, then AMP might be more appropriate.
And the list goes on. :)

Should I avoid message inheritance in WCF?

Generally, I try and avoid using inheritance in WCF contracts, preferring composition.
But in the following situation...
I have a service operation that can result in one of two things: ResultA and ResultB.
There is a boolean/enum in the response message to report this outcome.
There are a number of other properties in the response message. Some of these are only relevant in the event of ResultA and some are only relevant in the event of ResultB.
I see my options as being:
Have a single response message contract that contains everything and when properties are not relevant, they are left as null. The client then has to look at the bool/enum to see if its ResultA or ResultB and ignore properties accordingly.
Have 2 response messages contracts, both inheriting from a shared base. One representing ResultA and its relevant properties and one representing ResultB and its relevant properties.
I much prefer option 2 for a number of reasons, but it breaks the composition over inheritance rule.
What do people think?
My gut feeling here is "redesign your interface". Having methods with dubious return types is generally not a sign of good design. This leads to a lot of unnecessary and error-prone logic in every caller of the method.
So I would suggest "secret option number 3": refactor the interface into two separate methods.
All rules are meant to be broken. If you are reusing objects and the systems allows you to use inheritance... why not use it? As Phil Haack puts it... think for yourself.
Limiting yourself by a set of artificial rules is a great way to make you work much more difficult. There is a reason we can use inheritance, and I say this is one of them.
Prefer Composition Over Inheritance (Steve Rowe) Here is another angle. But if you read it he is talking about the reuse of function, not data.
Prefer composition over inheritance != Never use inheritance :-)