0

I have a GUI class and the Logic class, which is the better choice:

  1. make the logic class methods static and access them LogicClass.method() from the gui class.

  2. make the logic class regular and make 1 static object from this logic class

    private static LogicClass logic;

  3. make it non-static which is a little of a problem because i want to access some methods from the Main function in the GuiClass so it has to be static(i can access them through the constructor but I don't know if that's ok, something like connecting the server).

Community
  • 1
  • 1
  • Do not use a static context if possible. The DI option is preferred (option 3). – mr mcwolf Oct 08 '17 at 11:53
  • could you elaborate more? why are you so against it ? thanks – likesLowLevel Oct 08 '17 at 11:54
  • Possible duplicate of [*Java GUI architecture for larger project*](https://stackoverflow.com/q/25317268/230513); see [_item 1_](https://stackoverflow.com/a/25317943/230513). for [example](https://stackoverflow.com/a/23450604/230513). – trashgod Oct 08 '17 at 15:37
  • Instead of static use : `private LogicClass logic = new LogicClass();` – c0der Oct 08 '17 at 17:12

1 Answers1

0

Static things are best avoided, because sooner or later, you'll want to separate different things, or have more than one instance of something, and then you'll be faced with a horrible refactoring.

It's like salt and water. It's easy to mix the two, but much more difficult to take them apart.

I would suggest you make all your stuff non-static. Just use the "new" and you'll be good to go. You might have to pass around some additional parameters, or introduce some additional fields, but it'll make your code much better in the long run. Only when you know in advance that you'll never have more than one instance of a class, go for "singleton" pattern (it can be achieved by combination of static field + private constructor).

jurez
  • 4,436
  • 2
  • 12
  • 20
  • ok i understand, but for example gui components like a button, shouldn't they be static? plus how am i supposed to start the class from main thread if it isn't static? – likesLowLevel Oct 08 '17 at 12:24
  • Check out the Inversion of Control and Dependency Injection design patterns for methods on how to handle that. – M. le Rutte Oct 08 '17 at 13:56
  • No, you shouldn't make them static. Use `new` to make an instance of the class, then you can call non-static methods on it. Check out the [Swing tutorial](https://docs.oracle.com/javase/tutorial/uiswing/components/button.html#abstractbutton) and see the **ButtonDemo.java** there for complete example. – jurez Oct 08 '17 at 17:57