Until now I wrote my programs by using only static methods. I haven't abused the principles of OOP at all. My question is, when should I start working with objects instead of using static methods? Because it seems to me that using static methods makes my life easier, but I might be wrong.
- If you posted some code examples of your code, maybe we could see how your code could benefit from using objects.Hein Andre Grønnestad– Hein Andre Grønnestad2014-03-25 21:43:11 +00:00Commented Mar 25, 2014 at 21:43
- 1Keep on going with static methods if they make your life easier. I always start my design the same way and wait for a real concern to force objects on me. It usually does happen, though.Marko Topolnik– Marko Topolnik2014-03-25 21:43:33 +00:00Commented Mar 25, 2014 at 21:43
- Well it seems to me that everything can be written using static methods. But I might be wrong, as I said. @MarkoTopolnik In what case do you get forced to use objects?George Irimiciuc– George Irimiciuc2014-03-25 21:44:19 +00:00Commented Mar 25, 2014 at 21:44
- 1a program made up of static methods is going to be very tightly coupled and hard to test parts in isolationMatthew Mcveigh– Matthew Mcveigh2014-03-25 21:47:19 +00:00Commented Mar 25, 2014 at 21:47
- 1A third, very important reason is leveraging dynamic dispatch, which can make your code much cleaner.Marko Topolnik– Marko Topolnik2014-03-25 21:50:07 +00:00Commented Mar 25, 2014 at 21:50
3 Answers
Static Methods make your live easier, because you dont have to worry about Accessability in different scopes (not talking about private/public Methods - static methods are ALWAYS there, no matter in which context you are). Basically every OOP Method can be converted to a static method, using the object as one of the parameters. Also each Static method, having an object as a parameter could be converted to a method on the object instance.
People have been developing Apps, before any sort of "OOP" was known, so its not a "musst have".
General speaking: Does your method require "Object Properties"? Use an Object/instance method. Does your method NOT require Object Properties? Use a static method.
OOP makes your live easier, when you have coupled data (like a person has a certain fore- and surename and an email adress -> create an object with those 3 attributes). Instead of passing 3 Parameters to a method, you could implement a method without parameters on the object, and have access to all 3 values.
You would not run into trouble, swapping forenames or email adresses somewhere. Your Object clearly keeps track of data relation.
Comments
You can't write everything using static methods. Just as one example, if you create a JFrame and want to use a control that custom paints itself, you must create a subclass of at least JComponent and override the paint methods.
2 Comments
JFrame is already an object. You should instead prove that it is impossible to design a GUI framework without objects.