Is two way 1-n relationship between classes acceptable? - oop

I met a problem like this.
class A have a list of class B. A have choose one of B, and call its method. So A depends on B.
But when a timer ( not a real timer, just a mimic clock ) fires, B have to tell A that "I am done", so A can choose another B to work, which means B has to know A also.
This is a "two way 1-n relationship" and I think A and B are not well seperated.
Of course I can use Observer Pattern and make A an observer and B a subject, but this is not a typical case where observer pattern make sense because there is only one observer.
What do u think about it?

A knows about the available Bs. B only knows about the A currently using him. I don't think that's 1-n is it?
But B doesn't depend upon A as such, he does not care it's an A. He just needs to use the "finished()" method of his temprary associate. There's no real dependency there.
Class A implements ClientOfB {
Collection<B> myBees;
public beNottified() { ...}
public employeeBee () {
myBees.getRandomBee().buzz(this);
}
}
Class B {
public void buzz(ClientOfB client) {
client.beNotified();
}
}
I don't see unreasonable dependencies. A needs to know about buzz and to expose an interface. B only knows about the interface.

I agree with n8wrl that an event is probably a cleaner solution.
Original answer:
Does B need to know about all possible A's or just the one that called it (the one it tells "I am Done")? If so, then A can have the list of All B's, and B can have a reference to only the one A that matters.
Here's how I'd do it. Yes there's a cyclic association, but there's some control in how it's used. And this can eventually be refactored to a purer observer pattern if required.
class A
{
List<B> bObj = new List<B>();
public void callB(/*Params*/)
{
B bThatMatters = //Find Appropriate B ...
bThatMatters.DoStuff(this);
}
public void isDone()
{
//Handle being done with the last B
}
}
class B
{
A _callerA;
public void DoStuff(A callerA)
{
_callerA = callerA;
//... DO STUFF
}
public void WhenDone()
{
_callerA.isDone()
}
}

There is only one observer NOW, but who knows in the future?
A gets a B. B exposes an event that A (or anyone else for that matter) subscribes to. B fires the event, A gets the message.
B does not know about A it only knows about its own event.

Related

How can I achieve this via oops concepts

I am facing a design problem. This must only be solved by applying oops concepts. I am describing the problem below.
Problem: Suppose You have a class called X . It has two Paid (Chargeable) methods like m, n. Their may be many consumers classes of these methods. Someone pays for m, someone pays for n and someone pays for both m, n.
Now I have to design my X class in such a way that consumers can only see that method for which they make payment. How can we do this via OOPS concepts? I can make appropriate changes in my X class to achieve this design. Sample class is written below.
class X { // service class
public m(){ // do some stuff
}
public n(){ // do some stuff
}
}
Create 3 interfaces: one containing the m method, one containing n and a third containing both (the third interface can extend the two others). Then make your class X implement those interfaces.
You will then be able to expose the appropriate interface to your consumers, depending on their needs, while still using the same X class.
interface M { // exposed to customers paying for m
void m();
}
interface N { // exposed to customers paying for n
void n();
}
interface Mn extends M, N {} // exposed to customers paying for both
class X implements Mn {
#Override
public m(){ // do some stuff
}
#Override
public n(){ // do some stuff
}
}
I think you are not taking advantage of the class state. Class can store information in its instance fields about the user, and change its behavior accordingly.
One possible option would be:
class Payment {
int paymentType = 0; // fill with constructor for i.e.
public pay(int sum){
// some common behavior
switch(this.paymentType){
case 1:
// pay 1 logic
break;
case 2:
// pay 2 logic
break;
}
// some other common behavior
}
}
In another design you might use the Strategy pattern to have family of decoupled algorithms.
In the above code I assumed we are talking about some logically related code. If the code has nothing in common, you might even split it into other classes.
Update: I wouldn't advice on using it, but you can implement the Template Method pattern. The problem is you are going to overuse inheritance.
abstract class Payment {
public Pay(int sum){
// some common code
this.doPay(sum);
}
abstract protected doPay(int sum);
}
class PaymentOne : Payment {
protected doPay(int sum){
// pay 1 logic
}
}
class PaymentTwo : Payment {
protected doPay(int sum){
// pay 2 logic
}
}
You'd better use polymorphism concept
As example, based on assumption that m and n has different types:
class X{ // service class
public Pay(NType n){ // do some stuff
}
public Pay(MType m){ // do some stuff
}
public Pay(NType n, MType m){ // do some stuff
Pay(n);
Pay(m);
}
}

Access class (or object) parent in a correct way using OOP

I need know if this is inside the normal OOP behavior, or if not, what is the most common way to do it (without being specific to a language).
I had a class instanced on the main, called A , which inside had instanced the class B as a variable. When A calls methods inside B, B needs some methods from A for work.
For that, I must bypass the A reference itself via arguments or I must use always the tools specific for the language? OOP give some reference to this or it's out from their scope?
Thank you.
I had a class instanced on the main, called A , which inside had
instanced the class B as a variable. When A calls methods inside B, B
needs some methods from A for work.
The problem here is that, your class A knows too much - it knows how to instantiate another class with its arguments, therefore it becomes also responsible for a factory responsibility. Thus you end up breaking the Single-Responsibility Principle.
So, let's take a look at your current class hierarchy
class A
{
private b;
public void A()
{
b = new B();
}
}
a = new A();
Since you didn't inject an instance of B, this one also becomes bound to the class A.
Since B is tightly-coupled to A, It makes unit-testing very very hard (because you cannot inject a mocked instance of B) i.e you cannot test class A in isolation
It introduces another form of global state, since B comes from global scope
A proper way of doing this would be as (by adhering to the Dependency Injection):
class A
{
private b;
public void A(B bInstance)
{
b = bInstance;
}
}
b = new B();
a = new A(b);

Design Pattern for late binding class (without switch case for class assignment)

I have a base class where all common functions are written. I many classes which override this functions by virtual keyword. Like,
public class Base
{
public virtual void sample()
{
..............
}
}
public class a : Base
{
public override sample()
{
}
}
public class implement
{
public void ToSample()
{
Base baseclass = new Base();
Switch(test)
{
case a: baseclass = a();
break;
case b: baseclass = b();
break;
}
baseclass.sample();
}
}
This perfect code for current situation but now I have more class to be assign in switch case. It is not good practice for adding huge amount of cases so I want something that automatically assign child class.
Is anybody know something to be implement ?
As stated in the comment, you can decouple the implementation by using dependency injection. Note however, that in some cases you have no choice but doing that kind of switch (e.g. when you need to create a class based on a text received in a socket). In such cases the important thing is to always keep the switch statement encapsulated in one method and make your objects rely on it (or, in other words, don't copy-and-paste it everywhere :)). The idea here is too keep your system isolated from a potentially harmful code. Of course that if you add a new class you will have to go and modify that method, however you will only have to do it in one time and in one specific place.
Another approach that I have seen (and sometimes used) is to build a mapping between values an classes. So, if your class-creation switch depends on an integer code, you basically create a mapping between codes and classes. What you are doing here is turning a "static" switch into a dynamic behavior, since you can change the mappings contents at any time and thus alter the way your program behaves. A typical implementation would be something like (sorry for the pseudocode, I'm not familiar with C#):
public class implement
{
public void ToSample()
{
class = this.mapping.valueForKey(test);
Base baseclass = new class();
baseclass.sample();
}
}
Note however that for this example to work you need reflection support, which varies according to the language you are using (again, sorry but I don't know the C# specifics).
Finally, you can also check the creational family of patterns for inspiration regarding object creation issues and some well known forms of solving them.
HTH

Object References basics

I a new at OO programming and trying to clear up a few things.
When you instatiate a class and create an object, Ive seen the following:
class Program
{
static void Main(string[] args)
{
MyClassA a = new MyClassA();
MyClassA b = a;
MyClassA c = b;
c.DoSomething();
Console.ReadLine();
}
}
public class MyClassA
{
public void DoSomething()
{
Console.WriteLine("I am from Class A");
}
}
This may be a bad example, but the question I am trying to get answered is:
Why is pointing one object reference to another important or why\where is it used? Why not use the object you created in the first place?
This is more Java than generically "object-oriented" -- C++ would be completely different (if you need to "refer" to objects, and change to what object a certain variable "refers" to, you need to use explicit pointers -- references in C++ cannot be "reseated").
Anyway, unconditionally creating synonyms like in your example has no point nor purpose. Much more typical uses would be, for example,
MyClass a = ...whatever...;
MyClass b = ...whatever else...;
MyClass c;
if(something()) {
c = a;
} else {
c = b;
}
c.dosomething();
c.blahblah();
c.andmore();
i.e., having a "synonym" that can refer to one object, or to another one, depending on circumstances, so that following operations can always be coded as being "on the synonym" and they'll be on the "right" object either way (alternatives such as duplicating the whole blocks of "following operations" are, at the very least, very bad and repetitious style, and, e.g. when some of the "following operations" are in other methods and the "synonym" is an instance variable rather than a local variable, can be extremely hard to code, too).
This is just the simplest example, of course. But, do you really need other, more complicated ones?-)

Can a class return an object of itself

Can a class return an object of itself.
In my example I have a class called "Change" which represents a change to the system, and I am wondering if it is in anyway against design principles to return an object of type Change or an ArrayList which is populated with all the recent Change objects.
Yes, a class can have a method that returns an instance of itself. This is quite a common scenario.
In C#, an example might be:
public class Change
{
public int ChangeID { get; set; }
private Change(int changeId)
{
ChangeID = changeId;
LoadFromDatabase();
}
private void LoadFromDatabase()
{
// TODO Perform Database load here.
}
public static Change GetChange(int changeId)
{
return new Change(changeId);
}
}
Yes it can. In fact, that's exactly what a singleton class does. The first time you call its class-level getInstance() method, it constructs an instance of itself and returns that. Then subsequent calls to getInstance() return the already-constructed instance.
Your particular case could use a similar method but you need some way of deciding the list of recent changes. As such it will need to maintain its own list of such changes. You could do this with a static array or list of the changes. Just be certain that the underlying information in the list doesn't disappear - this could happen in C++ (for example) if you maintained pointers to the objects and those objects were freed by your clients.
Less of an issue in an automatic garbage collection environment like Java since the object wouldn't disappear whilst there was still a reference to it.
However, you don't have to use this method. My preference with what you describe would be to have two clases, changelist and change. When you create an instance of the change class, pass a changelist object (null if you don't want it associated with a changelist) with the constructor and add the change to that list before returning it.
Alternatively, have a changelist method which creates a change itself and returns it, remembering the change for its own purposes.
Then you can query the changelist to get recent changes (however you define recent). That would be more flexible since it allows multiple lists.
You could even go overboard and allow a change to be associated with multiple changelists if so desired.
Another reason to return this is so that you can do function chaining:
class foo
{
private int x;
public foo()
{
this.x = 0;
}
public foo Add(int a)
{
this.x += a;
return this;
}
public foo Subtract(int a)
{
this.x -= a;
return this;
}
public int Value
{
get { return this.x; }
}
public static void Main()
{
foo f = new foo();
f.Add(10).Add(20).Subtract(1);
System.Console.WriteLine(f.Value);
}
}
$ ./foo.exe
29
There's a time and a place to do function chaining, and it's not "anytime and everywhere." But, LINQ is a good example of a place that hugely benefits from function chaining.
A class will often return an instance of itself from what is sometimes called a "factory" method. In Java or C++ (etc) this would usually be a public static method, e.g. you would call it directly on the class rather than on an instance of a class.
In your case, in Java, it might look something like this:
List<Change> changes = Change.getRecentChanges();
This assumes that the Change class itself knows how to track changes itself, rather than that job being the responsibility of some other object in the system.
A class can also return an instance of itself in the singleton pattern, where you want to ensure that only one instance of a class exists in the world:
Foo foo = Foo.getInstance();
The fluent interface methods work on the principal of returning an instance of itself, e.g.
StringBuilder sb = new StringBuilder("123");
sb.Append("456").Append("789");
You need to think about what you're trying to model. In your case, I would have a ChangeList class that contains one or more Change objects.
On the other hand, if you were modeling a hierarchical structure where a class can reference other instances of the class, then what you're doing makes sense. E.g. a tree node, which can contain other tree nodes.
Another common scenario is having the class implement a static method which returns an instance of it. That should be used when creating a new instance of the class.
I don't know of any design rule that says that's bad. So if in your model a single change can be composed of multiple changes go for it.