tags:

views:

557

answers:

7

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.

+2  A: 

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.

paxdiablo
I Googled singleton, it seems a singleton is a single object that maintains state for the system. In my case there will be many of these "Change" objects at any given time representing recent changes. Is there a name for such a pattern?
Ankur
See my update re how I would design it (a separate changelist and change class). The way you have it has every change knowing about every other change, which seems to stretch the boundaries of encapsulation a little too much for my liking. By all means, do it if you're comfortable, but I wouldn't.
paxdiablo
Yes I like the idea of the ChangeList class. Thanks
Ankur
A: 

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.

Joshua
+3  A: 

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();
quixoto
Would there be a problem if I did call it from an instance of the class rather than the Class itself
Ankur
There wouldn't be a problem, per se, but if a Change is used to model one single change (whatever that is) to the system, then it would seem surprising for that change to also know about lots of other changes. That's why you'd typically make it a static method on Change, where it makes sense to have more global smarts than what a single Change would know about.
quixoto
Surprised this is the only answer with the word "factory" +1
annakata
+1  A: 

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");
benPearce
+1  A: 

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);
    }
}
Scott Ferguson
A: 

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.

DSO
+3  A: 

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.

Mark Rushakoff