if else condition in class constructor ... is it good practice? - java

I have written a constructor and passing one boolean flag to decide which value to set to class variable. Code is as follows
public PDFParagraph(PDFPhrase phrase,boolean isRtl) {
super(phrase);
if(isRtl)
this.setAlignment(Element.ALIGN_RIGHT);
else
this.setAlignment(Element.ALIGN_LEFT);
}
Now I am confused and not sure if I shall add if...else conditions in constructor. Is it good style to set the class varible value?
Thanks,
Hanumant.

Conditionals in constructors aren't problematic per se. However, in this instance, I'd be inclined to write your constructor like this:
public PDFParagraph(PDFPhrase phrase, boolean isRtl) {
super(phrase);
setAlignment(isRtl ? Element.ALIGN_RIGHT : Element.ALIGN_LEFT);
}

There is no style issue with using an if / else to do that. However:
You could write it more simply:
setAlignment(isRtl ? Element.ALIGN_RIGHT : Element.ALIGN_LEFT);
A lot of people (myself included) think that you should always put curly braces around the "then" and "else" statements.
On a related point: if you find yourself writing a constructor that looks like this:
public Thing(boolean cond, ...) {
super(...);
if (cond) {
// Lots of statements
} else {
// Lots of different statements
}
...
}
it is possibly an indication that you need to refactor your constructors. (Or possibly not ... it depends on the details.)

It might be more clear to users of your constructor if you just pass the initial alignment to set, especially if it's an Enum and those are the only possibilities. If however you're trying to restrict the initial alignment and it's something like a String, what you're doing seems fine. You still might want to consider an Enum for clarity though. It's easier to read than true or false being passed into a constructor.

Of course you can add if/else statements to the constructor.
It's usually best practice to keep methods as atomic (short and to-the-point) and clearly-defined as possible. This goes for the constructor also. You want the constructor to set up your object given the parameters you pass.
If you need an if/else, then you can put one in.
You can even go crazy and put a for loop in if you need to! ;)

I would recommend you use an enum and a switch statement instead of a boolean. What happens when you add another alignment?

Related

what's the best way to check if an object's attribute is empty?

For example, I use StringUtils.isEmpty(Object.attribute); to check if an attribute is empty. Should I put that code everytime I need to check if this attribute is empty. Or is it better to wrap it in a method Object.isAttributeEmpty() then call the StringUtils.isEmpty() inside isAttributeEmpty().
Which way is the best practice or preferred way.
If "attribute being empty" has special significance, then you're better off creating a boolean getter to name it and have as its implementation to call to the utility method:
class MyClass {
String attribute;
boolean isIncomplete() {
return isEmpty(attribute);
}
// other stuff
}
there is also the opportunity to name it in the opposite sense, eg taking my example above:
boolean isComplete() {
return !isEmpty(attribute);
}
I think it can really be a matter of style, and the rest is up to having a little vigilance in the code right before either of these is called to make sure that Object itself isn't null.
Personally I've done ways where I would write a static method in a Utility class that would then provide a method like ObjectUtility.isAttributeEmpty(Object object) and let the black box internals figure it out safely.
And at other times, it can be comfortable to have the object itself know. It depends on if the style dictates that you should be writing simple Java objects or if you allow for more complex methods to be inherent in the objects.
The even worse question becomes how do you answer a true/false question when the third answer is "it's null".

work a function using dynamic strings?

I would like to save some work on my app, is it possible to get the string, for example "level1" and then use the corresponding function, which would be level1();? my main point is not to make a huge switch-case statement, but only make a few level functions in a storage class, and whenever you level up, the string would change to "level" + number where number is the int, so lets say that right now you are in level 10, the function that would run is level10();
I hope i explained it clearly.. sorry if not.. hope you get the idea!
Thanks!
I believe you want to call a method at runtime using its name as a string.
You can do it via reflection.
Class.getMethod(String methodName, Class... parameterTypes)
Don't think of this in terms of method names, unless you want to muck around with reflection (you don't want to, and it's not necessary).
If you really do need to convert strings to method calls – and that's a big "if" – create a Map<String, Foo> where Foo implements some "callable"-like interface. Then a string-to-method lookup is simply:
Map<String, Foo> commands = /* ... */;
Foo foo = commands.get("level42");
foo.bar();
It really sounds like you should just have a
void setLevel(int level)
call. That can feel free to ignore (say) levels 11-14 or whatever... but it would be very ugly to have separate methods and invoke them by name. You can do so with reflection, but you should think about other options first.
Please see the top answer to this post:
Java dynamic function calling
I would also recommend following their advice regarding structure, to create a more object-oriented solution instead of using reflection.

How to fix the following PMD violations

I am using PMD to analyze code and it produces a few high priority warnings which I do not know how to fix.
1) Avoid if(x!=y)..; else...; But what should I do if I need this logic? That is, I do need to check if x!=y? How can I refactor it?
2) Use explicit scoping instead of the default package private level. But the class is indeed used only within the package. What access modifier should I use?
3) Parameter is not assigned and could be declared final. Should I add final keyword to all the places which PMD pointed out with this warning?
Avoid negation: Instead of if( x!=y ) doThis() else doThat(), check for the positive case first, because people/humans tend to like positive things more than negative. It twists the brain to have to reverse the logic in mind when reading the source code. So instead, write:
if ( x!=y ) doThis() else doThat() // Bad - negation first
if ( x==y ) doThat() else doThis() // Good - positive first
Explicit scoping: According to PMD website, it's a controversial rule. You may hate it, someone else likes it. What you should do is make all the fields within your classes private. There seems to be a field or method (not a class) with a package visibility, e.g. something like this:
class Foo {
/* private missing */ Object bar;
}
Final parameters: Method parameters should be final to avoid accidental reassignment. That's just a good practice. If you're using Eclipse, the content assist even provides a quickfix called "Change modifiers to final where possible". Just select all code in the editor with Ctrl-a and then press Ctrl-1.
You don't need to enable all rules. Choose some of the rules you agree to and refactor your code until all warnings are cleared.
1 - Refactor it to a if (x == y) ... else ... logic. Just avoid negative conditions in if statments, they make code harder to understand
2 - I wouldn't enable that rule.
3 - A lot of people declare a lot of fields and variables final. Especially when they want to make sure or express that the value of a variable shall not be changed in the method. If you don't like that, disable that rule.
These all seem like minor warnings that could be turned off.
1) It wants you to flip the logic
if(x==y) {
//old else clause
} else {
//old if clause
}
2) If package is really the correct access you want, there is no access modifier to add. I am not familiar enough to know if there is a way to suppress that specific warning.
3) A style issue. Some people want final on everything it could be on. Others thinks it adds too much clutter for to little information. If you are in the latter camp, turn that warning off.
Regarding the first item (the inequality) there are two issues:
1) Readability of double negation.
Say you have:
if(x!=y) { false clause } else { true clause }
The second clause is executed if "not x is not equal to y".
This can be rewritten as:
if (x==y) {true clause } else {false clause}.
2) Correctness: if x and y are not-primitives, using if(!x.equals(y)) is safer.
This is the equivalent of using == instead of .equals() and can lead to very serious bugs.
You can also use // NOPMD at the end of any line where you don't want PMD rules to be checked.
For example for the above given code you can suppress PMD check by giving,
class Foo {
/* private missing */ Object bar; // NOPMD
}
Please be aware that the above comment may silently suppress other warnings in the same line.

Why does java/javascript/python force the use of () after a method name, even if it takes no arguments?

One of my most common bugs is that I can never remember whether something is a method or a property, so I'm constantly adding or removing parentheses.
So I was wondering if there was good logic behind making the difference between calling on an object's properties and methods explicit.
Obviously, it allows you to have properties and methods that share the same name, but I don't think that comes up much.
The only big benefit I can come up with is readability. Sometimes you might want to know whether something is a method or a property while you're looking at code, but I'm having trouble coming up with specific examples when that would be really helpful. But I am a n00b, so I probably just haven't encountered such a situation yet. I'd appreciate examples of such a situation.
Also, are there other languages where the difference isn't explicit?
Anyways, if you could answer, it will help me be less annoyed every time I make this mistake ^-^.
UPDATE:
Thanks everyone for the awesome answers so far! I only have about a week's worth of js, and 1 day of python, so I had no idea you could reference functions without calling them. That's awesome. I have a little more experience with java, so that's where I was mostly coming from... can anyone come up with an equally compelling argument for that to be the case in java, where you can't reference functions? Aside from it being a very explicit language, with all the benefits that entails :).
All modern languages require this because referencing a function and calling a function are separate actions.
For example,
def func():
print "hello"
return 10
a = func
a()
Clearly, a = func and a = func() have very different meanings.
Ruby--the most likely language you're thinking of in contrast--doesn't require the parentheses; it can do this because it doesn't support taking references to functions.
In languages like Python and JavaScript, functions are first–class objects. This means that you can pass functions around, just like you can pass around any other value. The parentheses after the function name (the () in myfunc()) actually constitute an operator, just like + or *. Instead of meaning "add this number to another number" (in the case of +), () means "execute the preceding function". This is necessary because it is possible to use a function without executing it. For example, you may wish to compare it to another function using ==, or you may wish to pass it into another function, such as in this JavaScript example:
function alertSomething(message) {
alert(message);
}
function myOtherFunction(someFunction, someArg) {
someFunction(someArg);
}
// here we are using the alertSomething function without calling it directly
myOtherFunction(alertSomething, "Hello, araneae!");
In short: it is important to be able to refer to a function without calling it — this is why the distinction is necessary.
At least in JS, its because you can pass functions around.
var func = new Function();
you can then so something like
var f = func
f()
so 'f' and 'func' are references to the function, and f() or func() is the invocation of the function.
which is not the same as
var val = f();
which assigns the result of the invocation to a var.
For Java, you cannot pass functions around, at least like you can in JS, so there is no reason the language needs to require a () to invoke a method. But it is what it is.
I can't speak at all for python.
But the main point is different languages might have reasons why syntax may be necessary, and sometimes syntax is just syntax.
I think you answered it yourself:
One of my most common bugs is that I can never remember whether something is a method or a property, so I'm constantly adding or removing parentheses.
Consider the following:
if (colorOfTheSky == 'blue')
vs:
if (colorOfTheSky() == 'blue')
We can tell just by looking that the first checks for a variable called colorOfTheSky, and we want to know if its value is blue. In the second, we know that colorOfTheSky() calls a function (method) and we want to know if its return value is blue.
If we didn't have this distinction it would be extremely ambiguous in situations like this.
To answer your last question, I don't know of any languages that don't have this distinction.
Also, you probably have a design problem if you can't tell the difference between your methods and your properties; as another answer points out, methods and properties have different roles to play. Furthermore it is good practice for your method names to be actions, e.g. getPageTitle, getUserId, etc., and for your properties to be nouns, e.g., pageTitle, userId. These should be easily decipherable in your code for both you and anyone who comes along later and reads your code.
If you're having troubles, distinguishing between your properties and methods, you're probably not naming them very well.
In general, your methods should have a verb in them: i.e. write, print, echo, open, close, get, set, and property names should be nouns or adjectives: name, color, filled, loaded.
It's very important to use meaningful method and property names, without it, you'll find that you'll have difficulty reading your own code.
In Java, I can think of two reasons why the () is required:
1) Java had a specific design goal to have a "C/C++ like" syntax, to make it easy for C and C++ programmers to learn the language. Both C and C++ require the parentheses.
2) The Java syntax specifically requires the parentheses to disambiguate a reference to an attribute or local from a call to a method. This is because method names and attribute / local names are declared in different namespaces. So the following is legal Java:
public class SomeClass {
private int name;
private int name() { ... }
...
int norm = name; // this one
}
If the () was not required for a method call, the compiler would not be able to tell if the labeled statement ("this one") was assigning the value of the name attribute or the result of calling the name() method.
The difference isn't always explicit in VBA. This is a call to a Sub (i.e. a method with no return value) which takes no parameters (all examples are from Excel):
Worksheets("Sheet1").UsedRange.Columns.AutoFit
whereas this is accessing an attribute then passing it as a parameter:
MsgBox Application.Creator
As in the previous example, parentheses are also optional around parameters if there is no need to deal with the return value:
Application.Goto Worksheets("Sheet2").Range("A1")
but are needed if the return value is used:
iRows = Len("hello world")
Because referencing and calling a method are two different things. Consider X.method being the method of class X and x being an instance of X, so x.method == 'blue' would'nt ever be able to be true because methods are not strings.
You can try this: print a method of an object:
>>> class X(object):
... def a(self):
... print 'a'
...
>>> x=X()
>>> print x.a
<bound method X.a of <__main__.X object at 0x0235A910>>
Typically properties are accessors, and methods perform some sort of action. Going on this assumption, it's cheap to use a property, expensive to use a method.
Foo.Bar, for example, would indicate to me that it would return a value, like a string, without lots of overhead.
Foo.Bar() (or more likely, Foo.GetBar()), on the other hand, implies needing to retrieve the value for "Bar", perhaps from a database.
Properties and methods have different purposes and different implications, so they should be differentiated in code as well.
By the way, in all languages I know of the difference in syntax is explicit, but behind the scenes properties are often treated as simply special method calls.

What do curly braces in Java mean by themselves?

I have some Java code that uses curly braces in two ways
// Curly braces attached to an 'if' statement:
if(node.getId() != null)
{
node.getId().apply(this);
}
// Curly braces by themselves:
{
List<PExp> copy = new ArrayList<PExp>(node.getArgs());
for(PExp e : copy)
{
e.apply(this);
}
}
outAMethodExp(node);
What do those stand-alone curly braces after the first if statement mean?
The only purpose of the extra braces is to provide scope-limit. The List<PExp> copy will only exist within those braces, and will have no scope outside of them.
If this is generated code, I assume the code-generator does this so it can insert some code (such as this) without having to worry about how many times it has inserted a List<PExp> copy and without having to worry about possibly renaming the variables if this snippet is inserted into the same method more than once.
I second what matt b wrote, and I'll add that another use I've seen of anonymous braces is to declare an implicit constructor in anonymous classes. For example:
List<String> names = new ArrayList<String>() {
// I want to initialize this ArrayList instace in-line,
// but I can't define a constructor for an anonymous class:
{
add("Adam");
add("Eve");
}
};
Some unit-testing frameworks have taken this syntax to another level, which does allow some slick things which look totally uncompilable to work. Since they look unfamiliar, I am not such a big fan myself, but it is worthwhile to at least recognize what is going on if you run across this use.
I agree with the scope limit answer, but would add one thing.
Sometimes you see a construct like that in the code of people who like to fold sections of their code and have editors that will fold braces automatically. They use it to fold up their code in logical sections that don't fall into a function, class, loop, etc. that would usually be folded up.
I'd actually guess that someone forgot an else statement.
There's rarely a good reason to even bother with creating additional block scopes. In this, and most cases, it's far more likely someone may have forgotten to type their control statement than it is that they were doing something clever.
They make an inner scope. Variable declared inside these braces is not visible outside of them. This also applies to C/C++.
Braces are also useful to reduce the scope in switch/case statements.
switch(foo) {
case BAR:
int i = ...
...
case BAZ:
int i = ... // error, "i" already defined in scope
}
But you can write
switch(foo) {
case BAR:{
int i = ...
...
}
case BAZ:{
int i = ... // OK
}
}
It is also used for initialization blocks.
They define a new scope which means that everything declared in this scope is not visible outside the curly braces.
As an interesting note: the braces actually enable a class of statements: declarations.
This is illegal: if(a) int f;
but this is legal: if(a) { int f; }
I think they just define an unnamed level of scope.
The bring a scope, copy will not be visible outside of it, so you can declare another variable with same name later. And it can be gathered by the garbage collector right after you exit that scope. In this case copy serves as a temporary variable, so it is a good example.

Categories

Resources