Hi, a quick question on good or bad practices when write Java applications
I'm writing a class which takes a file name as a parameter when initialising it. But I don't want the full file name, I only want the file name minus the file extension. So I have a private String variable with getters and setters. During the object initialisation, I call this private method to set the String variable. Is it bad practice to do this, to call a class method in the constructor? Would I be better to have as part of the constructor this code which sets the file name?
It is a total of 1 line of code - this.fileName = file.substring(0, 4); so it wouldn't really bulk up the constructor, but I have a preference for methods which do one thing, and methods for everything (I learned to program with smalltalk and this was the norm AFAIR - you never touch a variable, except through getter/setter methods)
Depends. Getters and setters are able to do a bit more than only getting/setting. With that form of encapsulation you have full control over what to do with the values when called from outside the class. Imagine that your setter actually does a bit more than setting the value, e.g. doing some checks or changing it a bit, then you probably need to call the setter in the constructor as well. But that can also depend on what the constructor is expected to do. If a setter does nothing more than plain dumb setting a property, then you could also just do the same in the constuctor. Again, it depends. Just document the methods properly so that you won´t cause surprises in the future.
Joined: Sep 30, 2008
aye, it does do a tiny bit more, it takes in a filename.txt and sets the fileName to be fileName (minus the extension)
It is generally permissible to call a method from the constructor, but that method should be labelled "final" or "private." Are you passing the file name as a command-line parameter? If so, it is a good idea to print an error message if the file name is not available: a bit like this.
Campbell Ritchie wrote:It is generally permissible to call a method from the constructor, but that method should be labelled "final" or "private."
This is the key point. If you don't do that, then you could write a subclass of your class and override that method. When you do that, all of a sudden things are initialized in an unexpected order and you can find yourself with errors that are very hard to debug and fix. It happened to me.