I'm creating a cell editor, but I've done (and seen) this in other code. I'm creating an object and then dropping it on the floor like this:
ButtonCellEditor buttonColumn = new ButtonCellEditor(table, 2);
This class takes the table and sets a TableColumnModel and custom cell renderers to it. Then, the method ends and I don't reference the buttonColumn object anymore.
So, is there a difference between doing the above and doing this (which also works)?
new ButtonCellEditor(table, 2);
Anything really wrong with doing this?
You shouldn't have unused variables in your code, that makes it less clear. Also, a constructor is (as its name states) a method for initialize the object, this in your case is not done.
I suggest you to have a static method instead:
ButtonCellEditor.niceNameHere(table, 2);
The only case I can think in which a constructor would be adequate is when it takes params to initialize itself and then perform some actions later, but not for doing the action inside and this is not like yours.
There's nothing wrong with either of those way of creating a ButtonCellEditor. However, if you later want to reference that object, with method two you have no way of doing so. With method 1 you can at least say buttonColumn.method().
No tangible difference, as far as I know.
Nothing wrong either -- I would prefer shorter form, if the only reason really is to get side effects of constructing the object (which is not necessarily a very good API design in itself, IMO, but that's irrelevant here).
There is no real difference between the two cases. In the second case an anonymous variable will be created that will be normally garbage collected. The second case will also save you some typing and is somewhat more readable. A reader may expect to find a reference at the created object (if you choose the first version) and be surprised if he doesn't find one.
In any case, a static method may be more suitable for such cases.
they are the same, but a comment about why you are doing it might be in order. otherwise someone might come along and delete it, thinking it is a no-op without investigating.
you could also be more explict and call
table.getColumn(2).setCellEditor(new ButtonCellEditor());
Related
I have always thought that I have to initialize a class, before I can call it's non-static method, however, I came across a solution which had a method like this in it:
public String someStringMethod(){
return new MyClass().toString();
}
So I may be new in development, but is it a good practice? Is this a better way to call a method than the "classic" (see below) way?
public String classicStringMethod(){
MyClass cl = new MyClass();
return cl.toString();
}
Do they have any performance difference? Does the first way has a "special name"?
No significant difference
As the comments explained, both approaches are semantically the same; both ways achieve the exact same result and the choice is really just a stylistic difference.
The second approach assigns the new object to a reference variable. The first approach skips the use of a reference variable. But in both cases the class was used as a definition for instantiating an object, and then the toString method was called on that object.
Semantically, first (chained/fluent) syntax usually informs you that the created object will be used only for a single chain of operations, and discarded afterwards. Since there's no explicit reference exported, it also signals that the scope of life of the object is limited to that very statement. The second (explicit) one hints that the object is/was/will be used for additional operations, be it another method calls, setting a field to it, returning it, or even just debugging. Still, the general notion of using (or not) temporary helper variables is just a stylistic one.
Keep in mind that the variable is not the object. For example, the line Dog hershey = new Dog( "Australian Shepard" , "red", "Hershey" ); uses two chunks of memory. In one chunk is the new object, holding the state data for the breed and color and name. In the other separate chunk is the reference variable hershey holding a pointer to the memory location of the memory chunk of the Dog object. The reference variable lets us later refer to the object.
Java syntax makes this jump from reference variable to object so seamlessly that we usually think of hershey as the Dog object “Hershey”, but in fact they are separate and distinct.
As for performance, any difference would be insignificant. Indeed, the compiler or JVM may well collapse the second approach’s two lines into the first approach‘s single line. I don't know for sure, and I don't really care. Neither should you. Our job is to write clear readable code. The job of the compiler and JVM is to run that code reliably, efficiently, and fast. Attempting micro-optimizations has been shown many times to be futile (or even counter-productive) as the JVM implementations are extremely sophisticated pieces of software engineering, highly-tuned for making such optimizations. You can best assist the compilers and JVMs by writing simple straight-forward code without “cleverness”.
Note that the second approach can make debugging easier, because your debugger can inspect the instantiated object by accessing the object via the reference variable, and because you can set a line breakpoint on that particular constructor call explicitly.
Java primitives always have a default value in the memory of O (booleans are false = 0). So why is it considered as a bad practise to not initialize them, if they even have a predefined value because of this mechanic? And in arrays, even with initialization of a new int[8], all the values in it arent really initialized, but that isnt frowned upon...
By explicitly defining a value, it's clear that you intended that value at that point of execution. If not, another reader might interpret it as if you either forgot to initialize this variable or you don't care at that point (and will set it somewhere else later).
In other words, it's some kind of implicit documentation. Generally, it's considered better practice to write verbose code for better readability; i.e. never use abbreviations for methods names, write them out!
Also, if you have to write line comments (//), you can almost always replace them by wrapping the following code into a well-named method. Implicit documentation ftw! :)
ALL instance variables are initialized. If you don't specify a value, the default value is used.
Who says it's bad practice to not initialize instance variables? I tend not to initialize them unless it's to a non-default value, but it's not a big deal either way. It's about readability and reducing "code noise" improves readability. Useless initializing is code noise IMHO.
Say i am writing a small game and every single entity (enemy, player etc) starts with 100 health, there is no point in using a sethealth(100) method every time a new entity is created.
So basically, imo unless you need to use a certain value other than zero, I would not initialize them. Same goes for booleans, unless you need something to be true right off the bat, no point in touching it.
Its not bad practice, and Ive seen experienced developers who do initialise, and those who dont.
My preference is to initialise as it shows the developer has taken time to consider what the values should be on start up, and is not just relying on the compiler using defaults
It is not bad practice to initialize instance variable of class. But it is bot necessory to initialize it, because if you forgot or not initialize it, default value is assign to it.
Initialization required when we want that class instance variable/s must have some value at the time of initialization of class object.
E.g. 2 method invocations:
myMethod(getHtmlFileName());
or
String htmlFileName=getHtmlFileName();
myMethod(htmlFileName);
which is better way, exclude less typing in first case ?
If you are going to use a return value of a method in more than one place, storing it in a variable and using that variable in your code could be more practical, readable and easily debuggable rather than calling the method every time:
String htmlFileName = getHtmlFileName();
myMethod(htmlFileName);
....
myMethod(htmlFileName + "...");
The second approach would help you debug the return value of getHtmlFileName(), but other than that, neither approach is better than the other in an absolute sense. It's a matter of preference, and perhaps context, I would say. In this particular case I'd go for the first approach, but if you were combining several methods, I'd go for the second, for sake of readability, e.g.:
String first = firstMethod();
String second = secondMethod(first);
String third = thirdMethod(second);
rather than
thirdMethod(secondMethod(firstMethod()));
EDIT: As others have pointed out, if you're going to use the value in more than one place, then obviously you'd use the second approach and keep a reference to the value for later use.
It will probably depend on the context.
If you are going to use htmlFileName variable elsewhere in you code block you probably what to store it local variable like (especially true for some heavy method calls) :
String htmlFileName=getHtmlFileName();
myMethod(htmlFileName);
if it is one-off call the
myMethod(getHtmlFileName());
is probably more elegant and easy to read.
If you use the getHtmlFileName() returned value later on, and if the returned value is fixed, you will want to use the first form, i.e. assign a local variable and reuse it, and thereby avoid redundant calls / object creations.
Otherwise (e.g. if you only call the getHtmlFileName method once, you will want to use the first form which is more concise, and which avoid a useless local variable assignment, but there is no real harm if you still use the second form (e.g. for debugging).
Let's say I've got a type called Superstar. Now I want to have a method that does some work and edits some properties of a Superstar object.
Here are two ways of how I could implement this. Way 1 would be the following:
private Superstar editSuperstar(Superstar superstar){
....
superstar.setEdited(true);
return superstar;
}
...
superstar = editSuperstar(superstar);
And way 2 would be this:
private void editSuperstar(Superstar superstar){
....
superstar.setEdited(true);
}
...
editSuperstar(superstar);
Which one of these two possible ways is considered "best practice"? The first one, or the second pseudo "by reference" one?
In your case, the second form is preferrable, as you directly change one of you superstar properties (edited). However, if you have a method that use a superstar object and returns an updated version of it (without changing the initial one) the first form will have my favor.
Finally, since both of this examples only use Superstar object, they should be member methods of the Superstar class.
Use way 2 unless you are creating a "builder" class where you intend to chain invocations. Ex:
MyClass c = (new MyClassBuilder()).setX(blah).setY(blah).build();
The first form is deceptive. It gives the impression that one object is being passed in, which is copied and the copy then altered and returned.
"Best practice" would be to use the first form, but to actually do what is implied (apply the change to a copy, which is then returned). Immutable objects should generally be preferred over mutable objects unless they are big chunky things that are expensive to copy, in which case, you should then favor the second form.
The problem you have here with first method is if you use it like that:
Superstar edited = editSuperstar(originalSuperstar);
This will also modify the originalSuperstar which is, in my opinion, counterintuitive...
Thus prefer the second one if you modify the passed object or the first one if you return a new copy of the object.
For this peculiar example you could simply add an edit method to the Superstar class...
The first form would be surprising for the API clients if you return the same instance having only changed some fields. One would expect to get a modified copy back without having the original instance changed.
So use the second form if you don't return a copy and use the first if you do (and think about making Superstar immutable in that case).
I overheard two of my colleagues arguing about whether or not to create a new data model class which only contains one string field and a setter and a getter for it. A program will then create a few objects of the class and put them in an array list. The guy who is storing them argue that there should be a new type while the guy who is getting the data said there is not point going through all this trouble while you can simple store string.
Personally I prefer creating a new type so we know what's being stored in the array list, but I don't have strong arguments to persuade the 'getting' data guy. Do you?
Sarah
... a new data model class which only contains one string field and a setter and a getter for it.
If it was just a getter, then it is not possible to say in general whether a String or a custom class is better. It depends on things like:
consistency with the rest of your data model,
anticipating whether you might want to change the representation,
anticipating whether you might want to implement validation when creating an instance, add helper methods, etc,
implications for memory usage or persistence (if they are even relevant).
(Personally, I would be inclined to use a plain String by default, and only use a custom class if for example, I knew that it was likely that a future representation change / refinement would be needed. In most situations, it is not a huge problem to change a String into custom class later ... if the need arises.)
However, the fact that there is proposed to be a setter for the field changes things significantly. Instances of the class will be mutable, where instances of String are not. On the one hand this could possibly be useful; e.g. where you actually need mutability. On the other hand, mutability would make the class somewhat risky for use in certain contexts; e.g. in sets and as keys in maps. And in other contexts you may need to copy the instances. (This would be unnecessary for an immutable wrapper class or a bare String.)
(The simple answer is to get rid of the setter, unless you really need it.)
There is also the issue that the semantics of equals will be different for a String and a custom wrapper. You may therefore need to override equals and hashCode to get a more intuitive semantic in the custom wrapper case. (And that relates back to the issue of a setter, and use of the class in collections.)
Wrap it in a class, if it matches the rest of your data model's design.
It gives you a label for the string so that you can tell what it represents at run time.
It makes it easier to take your entity and add additional fields, and behavior. (Which can be a likely occurrence>)
That said, the key is if it matches the rest of your data model's design... be consistent with what you already have.
Counterpoint to mschaef's answer:
Keep it as a string, if it matches the rest of your data model's design. (See how the opening sounds so important, even if I temper it with a sentence that basically says we don't know the answer?)
If you need a label saying what it is, add a comment. Cost = one line, total. Heck, for that matter, you need a line (or three) to comment your new class, anyway, so what's the class declaration for?
If you need to add additional fields later, you can refactor it then. You can't design for everything, and if you tried, you'd end up with a horrible mess.
As Yegge says, "the worst thing that can happen to a code base is size". Add a class declaration, a getter, a setter, now call those from everywhere that touches it, and you've added size to your code without an actual (i.e., non-hypothetical) purpose.
I disagree with the other answers:
It depends whether there's any real possibility of adding behavior to the type later [Matthew Flaschen]
No, it doesn’t. …
Never hurts to future-proof the design [Alex]
True, but not relevant here …
Personally, I would be inclined to use a plain String by default [Stephen C]
But this isn’t a matter of opinion. It’s a matter of design decisions:
Is the entity you store logically a string, a piece of text? If yes, then store a string (ignoring the setter issue).
If not – then do not store a string. That data may be stored as a string is an implementation detail, it should not be reflected in your code.
For the second point it’s irrelevant whether you might want to add behaviour later on. All that matters is that in a strongly typed language, the data type should describe the logical entity. If you handle things that are not text (but may be represented by text, may contain text …) then use a class that internally stores said text. Do not store the text directly.
This is the whole point of abstraction and strong typing: let the types represent the semantics of your code.
And finally:
As Yegge says, "the worst thing that can happen to a code base is size". [Ken]
Well, this is so ironic. Have you read any of Steve Yegge’s blog posts? I haven’t, they’re just too damn long.
It depends whether there's any real possibility of adding behavior to the type later. Even if the getters and setters are trivial now, a type makes sense if there is a real chance they could do something later. Otherwise, clear variable names should be sufficient.
In the time spent discussing whether to wrap it in a class, it could be wrapped and done with. Never hurts to future-proof the design, especially when it only takes minimal effort.
I see no reason why the String should be wrapped in a class. The basic perception behind the discussion is, the need of time is a String object. If it gets augmented later, get it refactored then. Why add unnecessary code in the name of future proofing.
Wrapping it in a class provides you with more type safety - in your model you can then only use instances of the wrapper class, and you can't easily make a mistake where you put a string that contains something different into the model.
However, it does add overhead, extra complexity and verbosity to your code.