Is Java's printf() a bad practice? [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Advantages and Disadvantages of using System.out.printf();
In a discussion in an online forum, I was told that using printf method (like in System.out.printf()) was a bad practice and that I should use println instead, although the user couldn't give a clear explanation for that, it was something that "he was told". Is this true?

If you need the formatting capabilities of printf, then there's no question as println isn't an acceptable alternative.
If on the other hand you're just outputting a normal string, e.g.:
System.out.printf("All work completed.\n");
then it would be more canonical to use println for this. In terms of program correctness it doesn't really matter - printf will probably be marginally more expensive to run but in reality this is not going to be relevant.
However, I did see some example code that used printf for simple output and I'll admit I found it confusing. So I'd stick to println for that reason alone, that it will make your code more familiar and easier to understand for other developers.
(ETA: Even reviewing my own post now, I instinctively feel that the code sample is wrong and want to correct it to println. So my earlier opinion definitely still holds.)

No it is not true.
The only possible rationale I can think of is that printf with a literal \n and/or \n in the format string is going to produce platform specific line breaks ... which is a portability issue. But the simple solution is to use %n in the format string.
Of course, using printf when no arguments need to be substituted into the format string is less than optimal. I wouldn't say that this makes it Bad Practice though.

printf can do things which println can't, so saying that you should always use println rather than printf obviously doesn't make sense.
For people who don't know the formatting specifiers used in printf control strings, they can be hard to read -- that might be the reason the person you talked to advised you not to use printf.
Some more general advice for next time: Remember there are a lot of people who will happily give you advice despite not knowing what they're talking about, and even among those who do know what they're talking about, there are as many opinions about programming as there are programmers. So you should never take anything as gospel just because someone told you or because you read it in a book. Always try to understand the reasons for the advice, and remember that there are exceptions to every rule. Understand that virtually every decision you make when designing or implementing a program has both pros and cons, so usually there is no one option which is unconditionally "right"; you have to use your experience and judgement to determine what is the "right" way to do things in your current situation, even if it might be "wrong" in most other cases.

Using either one is "bad" practice if you are doing it for debug logging.
If that is the case using a proper logging framework is the "best" practice. Java has plenty to pick from.

Related

What is the preferred way to write boolean expressions in Java

I have always written my boolean expressions like this:
if (!isValid) {
// code
}
But my new employer insists on the following style:
if (false == isValid) {
// code
}
Is one style preferred, or standard?
I prefer the first style because it is more natural for me to read. It's very unusual to see the second style.
One reason why some people might prefer the second over another alternative:
if (isValid == false) { ... }
is that with the latter you accidentally write a single = instead of == then you are assigning to isValid instead of testing it but with the constant first you will get a compile error.
But with your first suggestion this issue isn't even a problem, so this is another reason to prefer the first.
Absolutely the first. The second betrays a lack of understanding of the nature of expressions and values, and as part of the coding standard, it implies that the employer expects to hire very incompetent programmers - not a good omen.
Everybody recognizes this snippet:
if (isValid.toString().lenght() > 4) {
//code
}
I think your second example looks at the same direction.
It was discussed for C# several hours ago.
The false == isValid construct is a leftover from C-world, where compiler would allow you to do assignments in if statement. I believe Java compilers will warn you in such case.
Overall, second option is too verbose.
IMO the first one is much more readable while the second one more verbose.
I would surely go for the 1st one
You are evaluating the variable, not false so the latter is not correct from a readability perspective. So I would personally stick with the first option.
I'm going to attempt a comprehensive answer here that incorporates all the above answers.
The first style is definitely to be preferred for the following reasons:
it's shorter
it is more readable, and hence easier to understand
it is more widely used, which means that readers will recognize the pattern more quickly
"false==..." rather than "...==false" is yet another violation of natural order,which makes the reader think "is there something strange going on that I need to pay attention to", when there isn't.
The only exception to this is when the variable is a Boolean rather than a boolean. In that case the second is a different expression from the first, evaluating to false when isValid is null as well as when it is Boolean.FALSE. If this is the case there are good arguments for using the second.
The second style doesn't require you to negate the expression yourself (which might be far more complicated than just "isValid"). But writing "isValid == false" may lead to an unintended assignment if you forget to type two ='s, hence the idiom is to put on the right side what can't be an rvalue.
The first style seems to be preferred among people who know what they're doing.
I just want to say I learned C twenty years ago in school and have moving onto Perl and Java and now C# which all have the same syntax and...
I think (!myvar) is the most popular
I think (myvar==false) is just fine too
in 20 years i have NEVER EVEN SEEN
(false==myvar)
I think your boss is smoking something-- I'm sorry but I'd take this as a sign your boss is some kind of control freak or numbskull.

As a Java programmer learning Python, what should I look out for? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Much of my programming background is in Java, and I'm still doing most of my programming in Java. However, I'm starting to learn Python for some side projects at work, and I'd like to learn it as independent of my Java background as possible - i.e. I don't want to just program Java in Python. What are some things I should look out for?
A quick example - when looking through the Python tutorial, I came across the fact that defaulted mutable parameters of a function (such as a list) are persisted (remembered from call to call). This was counter-intuitive to me as a Java programmer and hard to get my head around. (See here and here if you don't understand the example.)
Someone also provided me with this list, which I found helpful, but short. Anyone have any other examples of how a Java programmer might tend to misuse Python...? Or things a Java programmer would falsely assume or have trouble understanding?
Edit: Ok, a brief overview of the reasons addressed by the article I linked to to prevent duplicates in the answers (as suggested by Bill the Lizard). (Please let me know if I make a mistake in phrasing, I've only just started with Python so I may not understand all the concepts fully. And a disclaimer - these are going to be very brief, so if you don't understand what it's getting at check out the link.)
A static method in Java does not translate to a Python classmethod
A switch statement in Java translates to a hash table in Python
Don't use XML
Getters and setters are evil (hey, I'm just quoting :) )
Code duplication is often a necessary evil in Java (e.g. method overloading), but not in Python
(And if you find this question at all interesting, check out the link anyway. :) It's quite good.)
Don't put everything into classes. Python's built-in list and dictionaries will take you far.
Don't worry about keeping one class per module. Divide modules by purpose, not by class.
Use inheritance for behavior, not interfaces. Don't create an "Animal" class for "Dog" and "Cat" to inherit from, just so you can have a generic "make_sound" method.
Just do this:
class Dog(object):
def make_sound(self):
return "woof!"
class Cat(object):
def make_sound(self):
return "meow!"
class LolCat(object):
def make_sound(self):
return "i can has cheezburger?"
The referenced article has some good advice that can easily be misquoted and misunderstood. And some bad advice.
Leave Java behind. Start fresh. "do not trust your [Java-based] instincts". Saying things are "counter-intuitive" is a bad habit in any programming discipline. When learning a new language, start fresh, and drop your habits. Your intuition must be wrong.
Languages are different. Otherwise, they'd be the same language with different syntax, and there'd be simple translators. Because there are not simple translators, there's no simple mapping. That means that intuition is unhelpful and dangerous.
"A static method in Java does not translate to a Python classmethod." This kind of thing is really limited and unhelpful. Python has a staticmethod decorator. It also has a classmethod decorator, for which Java has no equivalent.
This point, BTW, also included the much more helpful advice on not needlessly wrapping everything in a class. "The idiomatic translation of a Java static method is usually a module-level function".
The Java switch statement in Java can be implemented several ways. First, and foremost, it's usually an if elif elif elif construct. The article is unhelpful in this respect. If you're absolutely sure this is too slow (and can prove it) you can use a Python dictionary as a slightly faster mapping from value to block of code. Blindly translating switch to dictionary (without thinking) is really bad advice.
Don't use XML. Doesn't make sense when taken out of context. In context it means don't rely on XML to add flexibility. Java relies on describing stuff in XML; WSDL files, for example, repeat information that's obvious from inspecting the code. Python relies on introspection instead of restating everything in XML.
But Python has excellent XML processing libraries. Several.
Getters and setters are not required in Python they way they're required in Java. First, you have better introspection in Python, so you don't need getters and setters to help make dynamic bean objects. (For that, you use collections.namedtuple).
However, you have the property decorator which will bundle getters (and setters) into an attribute-like construct. The point is that Python prefers naked attributes; when necessary, we can bundle getters and setters to appear as if there's a simple attribute.
Also, Python has descriptor classes if properties aren't sophisticated enough.
Code duplication is often a necessary evil in Java (e.g. method overloading), but not in Python. Correct. Python uses optional arguments instead of method overloading.
The bullet point went on to talk about closure; that isn't as helpful as the simple advice to use default argument values wisely.
One thing you might be used to in Java that you won't find in Python is strict privacy. This is not so much something to look out for as it is something not to look for (I am embarrassed by how long I searched for a Python equivalent to 'private' when I started out!). Instead, Python has much more transparency and easier introspection than Java. This falls under what is sometimes described as the "we're all consenting adults here" philosophy. There are a few conventions and language mechanisms to help prevent accidental use of "unpublic" methods and so forth, but the whole mindset of information hiding is virtually absent in Python.
The biggest one I can think of is not understanding or not fully utilizing duck typing. In Java you're required to specify very explicit and detailed type information upfront. In Python typing is both dynamic and largely implicit. The philosophy is that you should be thinking about your program at a higher level than nominal types. For example, in Python, you don't use inheritance to model substitutability. Substitutability comes by default as a result of duck typing. Inheritance is only a programmer convenience for reusing implementation.
Similarly, the Pythonic idiom is "beg forgiveness, don't ask permission". Explicit typing is considered evil. Don't check whether a parameter is a certain type upfront. Just try to do whatever you need to do with the parameter. If it doesn't conform to the proper interface, it will throw a very clear exception and you will be able to find the problem very quickly. If someone passes a parameter of a type that was nominally unexpected but has the same interface as what you expected, then you've gained flexibility for free.
The most important thing, from a Java POV, is that it's perfectly ok to not make classes for everything. There are many situations where a procedural approach is simpler and shorter.
The next most important thing is that you will have to get over the notion that the type of an object controls what it may do; rather, the code controls what objects must be able to support at runtime (this is by virtue of duck-typing).
Oh, and use native lists and dicts (not customized descendants) as far as possible.
The way exceptions are treated in Python is different from
how they are treated in Java. While in Java the advice
is to use exceptions only for exceptional conditions this is not
so with Python.
In Python things like Iterator makes use of exception mechanism to signal that there are no more items.But such a design is not considered as good practice in Java.
As Alex Martelli puts in his book Python in a Nutshell
the exception mechanism with other languages (and applicable to Java)
is LBYL (Look Before You Leap) :
is to check in advance, before attempting an operation, for all circumstances that might make the operation invalid.
Where as with Python the approach is EAFP (it's easier to Ask for forgiveness than permission)
A corrollary to "Don't use classes for everything": callbacks.
The Java way for doing callbacks relies on passing objects that implement the callback interface (for example ActionListener with its actionPerformed() method). Nothing of this sort is necessary in Python, you can directly pass methods or even locally defined functions:
def handler():
print("click!")
button.onclick(handler)
Or even lambdas:
button.onclick(lambda: print("click!\n"))

Python readability hints for a Java programmer

I'm a java programmer, but now entering the "realm of python" for some stuff for which Python works better. I'm quite sure a good portion of my code would look weird for a Python programmer (e.g. using parenthesis on every if).
I know each language has its own conventions and set of "habits". So, from a readability standpoint what are conventions and practices which is "the way to go" in Java, but are not really the "pythonic way" to do stuff?
There's no simple answer to that question. It takes time for your code to be "Pythonic". Don't try and recreate Java idioms in Python. It will just take time to learn Python idioms.
Take a look at Code Like a Pythonista: Idiomatic Python, Style Guide for Python Code and Python for Java Programmers (archived).
Jacob Hallén once observed that the best Python style follows Tufte's rejection of decoration (though Tufte's field is not programming languages, but visual display of information): don't waste "ink" (pixels) or "paper" (space) for mere decoration.
A lot follows from this principle: no redundant parentheses, no semicolons, no silly "ascii boxes" in comments and docstrings, no wasted space to "align" things on different rows, single quotes unless you specifically need double quotes, no \ to continue lines except when mandatory, no comments that merely remind the reader of the language's rules (if the reader does not know the language you're in trouble anyway;-), and so forth.
I should point out that some of these consequences of the "Tufte spirit of Python" are more controversial than others, within the Python community. But the language sure respects "Tufte's Spirit" pretty well...
Moving to "more controversial" (but sanctioned by the Zen of Python -- import this at an interpreter prompt): "flat is better than nested", so "get out as soon as sensible" rather than nesting. Let me explain:
if foo:
return bar
else:
baz = fie(fum)
return baz + blab
this isn't terrible, but neither is it optimal: since "return" ``gets out'', you can save the nesting:
if foo:
return bar
baz = fie(fum)
return baz + blab
A sharper example:
for item in container:
if interesting(item):
dothis(item)
dothat(item)
theother(item)
that large block being double-nested is not neat... consider the flatter style:
for item in container:
if not interesting(item):
continue
dothis(item)
dothat(item)
theother(item)
BTW, and an aside that's not specifically of Python-exclusive style -- one of my pet peeves (in any language, but in Python Tufte's Spirit supports me;-):
if not something:
this()
that()
theother()
else:
blih()
bluh()
blah()
"if not ... else" is contorted! Swap the two halves and lose the not:
if something:
blih()
bluh()
blah()
else:
this()
that()
theother()
The best place to start is probably PEP-8, which is the official Python style guide. It covers a lot of the basics for what is considered standard.
In addition, some previous stackoverflow questions:
What are the important language features idioms of python to learn early on?
What does pythonic mean?
What defines “pythonian” or “pythonic”?
Python: Am I missing something?
Zen of python
"Everything is a class" is a Java idiom that's specifically not a Python idiom. (Almost) everything can be a class in Python, and if that's more comfortable for you then go for it, but Python doesn't require such a thing. Python is not a purely object-oriented language, and in my (limited) experience it's good to take that to heart.
Syntax is only the tip of an iceberg. There are a number of different language construct that Java programmers should be aware of, e.g. Python do not need to use interface
Creating an interface and swappable implementations in python - Stack Overflow
The other really useful idiom is everything can be convert to a boolean value with an intuitive meaning in Python. For example, to check for an empty array, you simply do
if not my_array:
return
...process my_array...
The first condition is equivalent to Java's
if ((my_array == null) || (my_array.length == 0)) {
return
}
This is a godsend in Python. Not only is it more concise, it also avoid a Java pitfall where many people do not check for both conditions consistently. Countless NullPointerException are averted as a result.

How can I write code without "needing" comments for readability? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Is it possible to write good and understandable code without any comments?
When coding often I hear that if comments are needed then it means that the code is too hard to understand. I agree that code should be readable but often the language itself makes the code hard to follow, because of "plumbing" and strange syntax. The languages I use most often are:
Java
Mootools
Ruby
Erlang
Any tips would be appreciated?
Thanks
Recommended reading: Clean Code by Robert C. Martin.
In brief, you should
use meaningful variable/method/class names,
keep your functions/methods short,
have each class and method do only one thing,
have the code in each method be on the same level of abstraction.
Don't fear of extracting even moderately complex expressions from if statements; which one is clearer to read, this
if (i >= 0 && (v.size() < u || d == e)) ...
or
if (foundNewLocalMaximum()) ...
(Don't try to find any meaning in the first code snippet, I just made it up :-)
Comments in clean code are almost never needed. The only exceptions I can think of is if you are using some obscure language feature (e.g. C++ template metaprogramming) or algorithm, and you give a reference to the source of the method/algorithm and its implementation details in a comment.
The main reason why any other kind of comments is not very useful in the long run is that code changes, and comments tend to not be updated alongside the changes in the corresponding code. So after a while the comment is not simply useless, but it is misleading: it tells you something (implementation notes, reasoning about design choices, bug fixes etc.) which refers to a version of the code which is long gone, and you have no idea whether it is relevant anymore for the current version of the code.
Another reason why I think that "why I chose this solution" is most often not worth documenting in the code, is that the brief version of such a comment would almost always be like either "because I think this is the best way", or a reference to e.g. "The C++ Programming Language, ch. 5.2.1", and the long version would be a three-page essay. I think that an experienced programmer most often sees and understands why the code is written like this without much explanation, and a beginner may not understand even the explanation itself - it's not worth trying to cover everyone.
Last but not least, IMO unit tests are almost always a better way of documentation than code comments: your unit tests do document your understanding, assumptions and reasoning about the code quite efficiently, moreover you are automatically reminded to keep them in sync with the code whenever you break them (well, provided you actually run them with your build...).
I don't think you can normally write code without comments.
Briefly, the code documents how. The comments document why.
I would expect the comments to indicate the conditions why the code has been written like that, limitations imposed by requirements or externalities, the impact that would result from changing the code, and other gotchas. The comments contain information that isn't contained within the code itself.
Comments along the code are supposed to tell you why you initially did something a certain way. It shouldn't mean the code is too hard to understand.
The most important things to follow are:
give your variables, methods, classes... meaningful names
write classes/ modules with a clean responsibility
don't mix up different levels of code (don't do bit shifting and high level logic inside of one method)
I think it is useful to write comments for USERS of your code - what the classes/methods/functions do, when an how to call it etc. In other words document the API.
If you need to comment how a method works for the benefit of maintainers then I think the code is probably too complex. In that case refactor it into simpler functions, as others have said.
I personally feel that having no comments at all is about as bad as having excessive commenting. You just need to find the right balance. About using long descriptive names for things this about sums it up for me: read this Also read Kernighan & Pike on long names.
You need to follow certain rules.
Give the entities (variable, classes, etc) readable and meaningful names.
Use design patterns extensively and name them accordingly, e.g. if it is a Factory name it FooFactory.
Have the code formatted properly, etc.

Is defining a "ProbableBugException" code smell, paranoia or good practice?

In my Java code, I occasionally run into situations where I have to catch a checked exception from a library function that I'm pretty sure can't occur in my use case.
Also, when coding, I sometimes notice that I'm relying on certain inputs from other modules (my own) to have or not have particular features. For example, I might expect a string to be in a certain format etc. In these situations, I would often put in a verification step, although I control the code that send the input myself.
At the moment, I'm working on a quite complex product that I want to be very reliable. Among other things, I want it to collect information from caught exceptions and automatically file bug reports. For the above two scenarios, I therefore defined an (unchecked) "ProbableBugException", that tells me I made a mistake in the code delivering the input data.
Is that a) stupid, b) paranoid or c) good practice? This is going to be subjective, I'll put up three wiki answers so we can vote away without rep warping.
ETA:
Thanks to Svend for pointing out that Java has assertions, I didn't realize that. Assertions are actuall pretty much what my question was about, but I only knew them from C and have never used them there.
I'm thinking that using an assert is what you really want there ("probably bug").
It's stupid, because:
the exception should be much more specific, like InvalidInputException
you should think harder about the input side, it's likely that it's shaky if you feel you need that kind of exception
It's good practice, because:
you might have a coworker coding on the input side and the two of you might have misunderstood each other
if you make a mistake, fixing it becomes trivial
in situations where the input side is a plugin of some sort, it helps the plugin developers (who might be external) to deliver correct input.
I always expect the unexecpected.
I often have code like this : ( $div will never be 0 into my code )
if( $div != 0 ) {
$var = $var2 / $div;
} else {
/*
* It should never happen
*/
throw Exception( 'relevant message' );
}
I always protect myself from me and the others

Categories