0

I would like to know if there are cons or pros of using static fields or attributes in a model class.

For instance I have a model class called Book

public class Book{

private int id;
private static int id; //this one
private Category category;

//setters and getters

}

I understand that static variable values remain active while programming is running and remain unchanged if not set to a new value using setters.

What are the best practices and when should I use static fields in a Model class?

heisenberg
  • 1,784
  • 4
  • 33
  • 62
  • 1
    *I understand that static variable values remain active while programming is running and remain unchanged if not set to a new value using setters.* This is not only for static variables, that's what a regular variable/field does. The particularity about static variables is that they are **shared** across all object of the given class. So all your `Book` instances will have the exact same id. You change it once, it gets changed in all your `Book` instances. The question is: is this what you need? Is a non-unique id useful? – BackSlash Jun 30 '17 at 13:00
  • I'm not sure setters with static variables really make sense – OneCricketeer Jun 30 '17 at 13:01
  • 1
    Use `static` if its value is common to all `Book` instances. The main (only?) dangers are if it is mutable: any instance of `Book` can change its value, is that desirable? And if you do want the field to change, and the code is used by multiple threads, you need to make sure that appropriate steps are taken to ensure synchronization of the updates (which is true of non-static fields too; but it's way worse for static fields). – Andy Turner Jun 30 '17 at 13:01
  • @AndyTurner I've used static variables for username. Is that something considered to be a common practice? Thanks. – heisenberg Jun 30 '17 at 13:34
  • If the username is something that only has (and will only ever have) 1 value throughout the system... you could. I'd avoid it, though. – Andy Turner Jun 30 '17 at 13:36

1 Answers1

0

Well, if you want every instance of a Book to have the same id then make it static.

If that's absurd (and I think it is), then use a non-static field.

Willy Wonka
  • 155
  • 5
  • Nit: instances of `Book` don't "have" an `id` if it's a static field. Static fields belong to the class, not to its instances. – Andy Turner Jun 30 '17 at 13:09