Well, i hope you understand me. I have two classes, A and B. B is subclass of A. They have the same public methods and means the same thing, but B does some things a little different, so it has additional methods and attributes that only uses itself. Let say, class A implements a method newFromWizard that interactively creates an object. Can I implement logic for, depending on the user input, create an object A or and object B in the newFromWizard method of A. I mean, can i create a B object from that method of A? Or i need to implement that elsewhere? How is the best way to do it? In practice, i can. But, it is correct for OOP?

By the way, if that matters, i'm using Smalltalk.

有帮助吗?

解决方案 3

I would say that it's not intuitive way of doing things. Let's simplify it and say that you just redefine new. Then in some point you do A new and get an instance of B. The thing that they are similar makes it not so bad. But imagine that someone else starts working with your code. And hew knows that message new should result in creation of the instance of the receiver. And then something goes different. I'd say that conceptually it's wrong. Why now to implements some builder class? And have there something like

createInstanceOfAB
  |className|
  className := "do what you need".
  ^ className asClass new.

This is a more clear way.

Once again you can make new… method to do whatever you want, even shoot fireworks, but most of the people will expect it to create instance of the same class

其他提示

Yes, this is a well-known pattern in OO. In the Objective-C Cocoa libraries you'll find it applied systematically, and is known as class clusters. The result is that the Cocoa libraries are much easier to understand than the equivalent c# or java ones. It allows the hiding of a inheritance hierarchy behind an abstract class that has class side creation methods that return subclasses.

public class A{

    public B method(){
        B b = new B();
        return b;
    }
}

class B extends A{

}

If this is what you're talking about, it's valid.

I think you shouldn't worry too much about whether it is "clean OO" to return an instance of a subclass. It's being used and done so often because it is very helpful and makes your code very readable compared to somme kind of factories and stuff.

My biggest concern here would be that you should name your class method carefully. Don't use #new is probably the most important rule, but you should always use a name that already says: give me an instance of what is appropriate right now.

I'd say this is not limited to subclasses, such a method can even return objects that do not inherit from the class. In a dynamically typed language, this is okay. Remember, we're in a dynamically typed language, so as long as you have polymorphic interfaces, the class of an object is not really important to its users as long as it responds to your message sends...

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top