public class Foo
{
public string Bar { get; set;}
}
var foo = new Foo { Bar = "Hey there" }; case class Foo(bar: String, foo: String = "hello")
new Foo(bar = "Hey there")
new Foo(foo = "Hey there", bar = "Hello")
new Foo("Hey there") case class Foo(bar: String, foo: String = "hello")
val f1 = Foo(bar = "Hey there")
val f2 = Foo(foo = "Hey there", bar = "Hello")
val f3 = Foo("Hey there")Providing a getter at least is sometimes practically unavoidable, so there's 1 repetition, but with a good IDE that's just a quick key combination over the variable name.
I'm curious, could you please elaborate on this point? If a class has any dependency, i usually find it better to require that dependency to be passed in the constructor, so the constructed instance can always be in a valid initialized state. Why do you find nullary constructors to be good OO?
About the nullary constructor + init() method for deserializing purposes, i don't have any strong opinion really, as long as consistency is kept throughout the code base/module that relies on that. Using Java's reflection API though, you can extract all necessary type information from non-nullary constructors in order to call them with the required dependencies, which is not essentially more complicated than instantiating the class and then setting its properties thought setter methods.
Is there a preferred way on HN to address a "duplicate" reply?
- the attribute has a different name
- an attribute is set whose value is a function of more than one argument
- an attribute is set to a constant value independent of constructor arguments
In languages requiring attribute declarations the minimum number of occurrences is 2 (declaration and initialization in a constructor). When declarations aren't required then it's just initialization.How often such circumstances occur is another issue. The form of initialization that you mentioned is probably the most common so languages can provide shortcuts in this case.
Because Java, C++, and C# suck at this. I'm trying to see the relevance to the OP, which is about Python, which rather decidedly lacks this problem. To add a new instance variable in a class, you need to mention it once, or twice if your using a __slots__-based class for compact memory footprint (because then you have to add it to __slots__ and then actually assign it a value somewhere.)
in java, c++, or c#, to add a variable to a class, you have to repeat its name 4 times. once to declare, once in the constructor parameters, and once on each side of the assignment. why am i writing the same thing 4 times for what should be a core part of the language?
in haskell, you write it once (i'm not saying haskell's records are nice, but they got that part right). same with rust.
and with a function, you write it once.