class with only one instantiation

Posted 05 September 2013 - 12:11 AM

Lately I encountered a case where a piece of my code involves some procedural steps, which does not need to remember its state every time it runs. Basically it just routinely checks all objects that are already on screen, if there is any redundancy, then clean up, that's it. Then I realized it does not even need to run many times, only once in the end of a session will satisfy. So the whole class turned out to be just gluing together several methods running themselves step by step, and it only needs ONE instantiation.

I'm not very experienced in this, is it considered bad pattern if a class only has one instantiation? Should I use functions instead and passing around arguments? Many thanks.

Replies To: class with only one instantiation

Re: class with only one instantiation

Posted 05 September 2013 - 03:45 AM

It is hard to answer this question without specific details, but there is nothing intrinsically wrong with a single instance of a class. It is even possible, although not always necessary, to replicate the singleton pattern in Python so that there will only ever be one instance of the Class.

In general terms, Python is an Object-Oriented Programming language, so IMO if you already have a Class then there is no reason to break it out to a function (or functions) UNLESS you can see a specific, long-term, benefit to doing this.

Re: class with only one instantiation

Posted 05 September 2013 - 12:48 PM

As andrewsw has said, this is a design question. There are design advantages to classes which only become apparent later on. If you think you might encounter such advantages, then it might make sense to prepare to reap them now. Later on, it'll be a lot harder or at least more annoying to rejigger your code.

On the other hand, if you feel that the code is more clear and easier to maintain if this is left as procedural code, well, python can do that too.

Quote

it feels like a waste when you spend so much time and energy to build a factory and it only produce one product and then become dormant.

This is not a convincing reason to me. Build for the long term, make your decisions based on what the maintainer of this code (or your future self) will thank you for.

What I'm wondering about here is why this code would be in an object of its own. It really sounds to me like this code should be part of the GUI mechanism. Maybe I'm not understanding your design, but it sounds like you wrote a CleanerUpper class, which then goes to work on your GUI object. Should this not be part of your GUI class?