Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

10
  • 15
    The only problem with this is that there is no validation. Any logic as to what a valid Bottle is should be in the Bottle class. However, using your proposed implementation, I can have a bottle with a negative height and diameter - there's no way to enforce any business rules on the object without validating every time the object is used. By using the second method, I can ensure that if I have a Bottle object, it was, is, and always will be a valid Bottle object according to my contract. Commented Dec 27, 2010 at 20:35
  • 7
    That's one area where .NET has a slight edge over properties, since you can add a property accessor with validation logic, with the same syntax as if you were accessing a field. You can also define a property where classes can get the property value, but not set it. Commented Dec 27, 2010 at 22:04
  • 3
    @user9521 If you are sure that your code will not cause a fatal error with "bad" values, then go for your method. However, if you need further validation, or the ability to use lazy loading, or other checks when data is read or written, then using explicit getters and setters. Personally I tend to keep my variables private and use getters and setters for consistency. This way all my variables are treated the same, regardless of validation and/or other "advanced" techniques. Commented Dec 28, 2010 at 4:29
  • 2
    The advantage of using the constructor is that it makes it much easier to make the class immutable. This is essential if you wish to write multi-threaded code. Commented Dec 29, 2010 at 17:36
  • 8
    I would make the fields final whenever possible. IMHO I would have preferred fields to be final by default and have a keyword for mutable fields. e.g. var Commented Dec 30, 2010 at 1:08