I find reading coding style guidelines to be the best way to get to know a language and its peculiarities. I've been trying to find a good document for Java, and get some questions answered immediately.
Firstly, what is the convention for very long lines? Writing in both Java and C/C++ leads me to have a great deal of confusion on this point.
Secondly, what is the guideline for creating custom exception classes? I typically end up throwing an existing exception rather than creating my own. Is custom exception creation typically enforced?
Take a look at the official Code Conventions for the Java TM Programming Language.
JavaRanch Java Programming Style Guide
Code Conventions for the Java Programming Language
Java Programming Style Guidelines
I'd start with the Sun/Oracle Java coding standards.
There isn't a 100% hard and fast standard for character width of lines. I'd say somewhere between 80-120 characters. Larger, wider screens would make me less concerned about this.
I would agree that the standard exceptions are usually good enough for me. I might a custom exception subclass for special business significance, but those are few and far between. I'd say that latest style for Java would be to prefer unchecked exceptions, more like C#.
http://www.oracle.com/technetwork/java/codeconv-138413.html
Wrap to 80 - 110 chars
It is great to throw existing. You should only create custom, when
existing exception doesn't quite
match the exceptional case (
usually a business rule )
As a brief for the coding conventions:
class SomeClassName { //<-- Class with upper case, camel case
public static final int CONSTANT_SOMETIHNG = 0x2A; // constants all upper case
private int secretVariable; // variables start with lowercase
public void someMethod() { // methods too
// opening brace goes in the same line
if( cond ) {
...
} else {
...
}
for( .. ) {
}
while( ... ) {
}
try {
} catch() {
} finally {
}
// closing brace aligned to the element start
}
}
}
Etc. etc.
"Effective Java" by Joshua Bloch is vital reading. It goes beyond the syntactic guidelines offered by Oracle.
Item 60 is "Favor the use of standard exceptions," but item 61 is "Throw exceptions appropriate to the abstraction." Sometimes custom exceptions are called for, and sometimes not.
Possible duplicate question. You can find the answer here: https://stackoverflow.com/questions/1334204/official-java-code-guidelines-conventions
However, the documentation on Sun/Oracle's website is older than 12 years. Although the core language hasn't changed, technology changes rapidly, which means the way we work with that technology changes.
I would suggest using what works best for you and your team. As long as there is some agreed-upon standard within your organization that is considered mainstream, you should be okay.
Line lengths used to be much more of an issue when people used 80 character wide text editors. Today most developers have large high resolution wide screens so wrapping at 80 characters in Java might actually be a disservice if it forces others to scroll down more and have whitespace on the right. Take note of who might be looking at the code you write and wrap it at an appropriate length.
My view for Custom Exception classes is to use whatever already exists as far as it makes sense. However, there are times that you need an exception class that does not exist, so if it makes sense don't hesitate to create one.
Related
I have been looking at Java streams and functional programming.
Figured a way to rewrite a small "user login" code.
Here is my login methods;
If the user from query is null, null pointer exception is handled on a filter.
public ResponseEntity login(User request) {
User dbUser = userRepo.findByEmail(request.getEmail());
if (!aes.matches(request.getPassword(), dbUser.getPassword()))
return ResponseEntity.status(403).build();
return logUserIn(dbUser);
}
private ResponseEntity logUserIn(User dbUser) {
dbUser.setPassword(null);
jwtHandler.setJwtCookie(dbUser);
return ResponseEntity.ok(dbUser);
}
And via using streams;
public ResponseEntity login(User request) {
return Stream.of(userRepo.findByEmail(request.getEmail()))
.filter(dbUser -> aes.matches(request.getPassword(), dbUser.getPassword()))
.map(this::logUserIn)
.findFirst()
.orElse(ResponseEntity.status(403).build());
}
private ResponseEntity logUserIn(User dbUser) {
dbUser.setPassword(null);
jwtHandler.setJwtCookie(dbUser);
return ResponseEntity.ok(dbUser);
}
I dont know if streams are meant to be used this way. Are they?
If i use similar kind of logic on more important parts of the project will I get in trouble later?
You might feel better about the if-else if you use it in a more functional style rather than short-circuiting:
if (!aes.matches(request.getPassword(), dbUser.getPassword())) {
return ResponseEntity.status(403).build();
}
else {
return logUserIn(dbUser);
}
Doing equivalent in one statement with Stream/Optional is harder to read and less performant.
You might consider the possibility of making findByEmail return Optional<User>, which is more idiomatic for any "find" method. Then you could combine the two approaches like
return userRepo.findByEmail(request.getEmail()).map(dbUser -> {
if (!aes.matches(request.getPassword(), dbUser.getPassword())) {
return ResponseEntity.status(403).build();
}
else {
return logUserIn(dbUser);
}
})... // .orElse(null) / .orElseThrow(...)
You'll get into trouble, mostly. The 'root' problem is that both ways of writing it are defensible as the 'best choice', and the java community, by and large, strongly prefers the second form. For the same reason it is a bad idea to name_variables_like_this (the community decided that the convention is to nameThemLikeThis). Breaking the mold will mean your code is harder to read by others and code written by others is harder to read for you. Also, you'll probably get friction when you try to interact with other code.
For example, right now (and for the foreseeable future), 'lambdas' (those things with the :: and the ->) are NOT exception transparent, NOT control flow transparent, and NOT mutable local variable transparent.
There are only 3 feasible options here:
Somehow write all code such that these 3 transparencies are never relevant regardless of what you're writing. That sounds impossible to me. Even if you somehow you manage, there are other libraries out there. Starting with java.*, which isn't designed for that kind of code style.
Mix code styles, going with lambda style when you don't immediately foresee the transparencies being relevant, otherwise going with the more imperative style if it is or you think it might be. This sounds silly to me; why mix 2 styles when a single style would have covered all the use cases?
Stick with lambda style, bending over backwards to account for the lack of these 3 transparencies where it bothers you, 'downgrading' variables to AtomicX variants, using such constructs to transmit exceptions and boolean flags to carry break and continue control flow outside, etectera. This is just writing ugly code just because you are particularly eneamoured of your fancy new shiny hammer and are just insisting on treating all problems as a nail, no?
That's.. trying to guess at what's going to happen when you interact with other code and other programmers. This snippet, in a vacuum, with just you? Eh, both work fine. Whatever you prefer, if community, friction with other code, and having a consistent style doesn't matter.
I have used Java 8 streams in live code and the biggest drawback for me is the stacktrace you get when an exception goes unhandled in the pipeline.
Sure they are nice to write and give you a sense of writing code in a functional style, but the truth is that streams are just a facade because underneath the fancy API, you are dealing with a monstrous abstraction layer over plain, ugly Java iterators, and this becomes painfully obvious when something goes awry such as an exception not being handled.
So the answer to your question is yes you might get in trouble, but it depends on how good you are at reading stacktraces, where 70% of the trace has nothing to do with code you've written but rather with the magic stuff used to turn iterators into streams.
As much as possible, prefer using if-else, for-loops, etc, unless you are confident that streams will be more efficient or easier to read. On that note, readability is quite important and part of the reason the Stream api exists is to improve readability, but moderation and good judgement are virtues worth exercising when making use of the full potential of the Streams API.
I am looking at quizzes and tests at various sites (like blackbeltfactory, etc..) about java. I come across with questions which have choices like "doesn't compile" or "throws exception at runtime".
Are there any way to guess which will occur, at first look? Or is it a matter of getting familiar with java?
I think this is an important point on how java works.
Thanks in advance,
Bugra
For a human, you have to "get familiar with Java".
For a machine ( or a program that is ) it has to follow the rules the language specifies.
For instance the given class:
class Main {
String s;
}
What would be the result of invoking:
Main m = new Main();
m.s.length();
A) doesn't compile?
B) throws exception at runtime?
To answer this specific question you have to know, how classes are defined in Java ( to know if the one I show is a valid class definition or not ) , also you have to know how attributes are defined and default values etc, so you have to get familiar with the language.
When you know all these concepts, you can easily answer with a quick view.
BTW, the famous Sun Certified Java Programmer certification, is all about know this kind of stuff, rather than knowing how to develop an application. It is about converting your self in a "human compiler"
Obviously, knowing Java better will help. However, there are some general rules.
"Doesn't compile" means that the compiler literally could not understand the syntax of the code. This can happen as the result of misplaced or missing brackets or parentheses, methods with the wrong number of arguments, and other such things:
int a = (3 + 2) - 1);
"Throws exception at runtime" means that the written code makes sense syntactically, but that when it is actually executed it tells the machine to do something that is, for whatever reason, impossible. some exceptions are built into the language, such as if you try to divide by zero, but many are also explicitly defined and thrown in the code. Programmers use such exceptions to create programs which visibly break when they try to do something they shouldn't, rather than breaking silently and then causing other problems down the road:
int a = b / c; // very bad if c == 0
Generally speaking, compiler errors will look more like typos (and often will result from typos), whereas runtime exceptions will result from lines which fail under specific conditions (e.g. some variable is equal to zero). Once again, though, there is no real substitute for truly knowing the language.
In my honest opinion is a matter of getting familiar with java but some compiling errors are clear at first sight and they are very similar to other languages.
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.
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
C# has syntax for declaring and using properties. For example, one can declare a simple property, like this:
public int Size { get; set; }
One can also put a bit of logic into the property, like this:
public string SizeHex
{
get
{
return String.Format("{0:X}", Size);
}
set
{
Size = int.Parse(value, NumberStyles.HexNumber);
}
}
Regardless of whether it has logic or not, a property is used in the same way as a field:
int fileSize = myFile.Size;
I'm no stranger to either Java or C# -- I've used both quite a lot and I've always missed having property syntax in Java. I've read in this question that "it's highly unlikely that property support will be added in Java 7 or perhaps ever", but frankly I find it too much work to dig around in discussions, forums, blogs, comments and JSRs to find out why.
So my question is: can anyone sum up why Java isn't likely to get property syntax?
Is it because it's not deemed important enough when compared to other possible improvements?
Are there technical (e.g. JVM-related) limitations?
Is it a matter of politics? (e.g. "I've been coding in Java for 50 years now and I say we don't need no steenkin' properties!")
Is it a case of bikeshedding?
I think it's just Java's general philosophy towards things. Properties are somewhat "magical", and Java's philosophy is to keep the core language as simple as possible and avoid magic like the plague. This enables Java to be a lingua franca that can be understood by just about any programmer. It also makes it very easy to reason about what an arbitrary isolated piece of code is doing, and enables better tool support. The downside is that it makes the language more verbose and less expressive. This is not necessarily the right way or the wrong way to design a language, it's just a tradeoff.
For 10 years or so, sun has resisted any significant changes to the language as hard as they could. In the same period C# has been trough a riveting development, adding a host of new cool features with every release.
I think the train left on properties in java a long time ago, they would have been nice, but we have the java-bean specification. Adding properties now would just make the language even more confusing. While the javabean specification IMO is nowhere near as good, it'll have to do. And in the grander scheme of things I think properties are not really that relevant. The bloat in java code is caused by other things than getters and setters.
There are far more important things to focus on, such as getting a decent closure standard.
Property syntax in C# is nothing more than syntactic sugar. You don't need it, it's only there as a convenience. The Java people don't like syntactic sugar. That seems to be reason enough for its absence.
Possible arguments based on nothing more than my uninformed opinion
the property syntax in C# is an ugly
hack in that it mixes an
implementation pattern with the
language syntax
It's not really necessary, as it's fairly trivial.
It would adversly affect anyone paid based on lines of code.
I'd actually like there to be some sort of syntactical sugar for properties, as the whole syntax tends to clutter up code that's conceptually extremely simple. Ruby for one seems to do this without much fuss.
On a side note, I've actually tried to write some medium-sized systems (a few dozen classes) without property access, just because of the reduction in clutter and the size of the codebase. Aside from the unsafe design issues (which I was willing to fudge in that case) this is nearly impossible, as every framework, every library, every everything in java auto-discovers properties by get and set methods.They are with us until the very end of time, sort of like little syntactical training wheels.
I would say that it reflects the slowness of change in the language. As a previous commenter mentioned, with most IDEs now, it really is not that big of a deal. But there are no JVM specific reasons for it not to be there.
Might be useful to add to Java, but it's probably not as high on the list as closures.
Personally, I find that a decent IDE makes this a moot point. IntelliJ can generate all the getters/setters for me; all I have to do is embed the behavior that you did into the methods. I don't find it to be a deal breaker.
I'll admit that I'm not knowledgeable about C#, so perhaps those who are will overrule me. This is just my opinion.
If I had to guess, I'd say it has less to do with a philosophical objection to syntactic sugar (they added autoboxing, enhanced for loops, static import, etc - all sugar) than with an issue with backwards compatibility. So far at least, the Java folks have tried very hard to design the new language features in such a way that source-level backwards compatibility is preserved (i.e. code written for 1.4 will still compile, and function, without modification in 5 or 6 or beyond).
Suppose they introduce the properties syntax. What, then does the following mean:
myObj.attr = 5;
It would depend on whether you're talking about code written before or after the addition of the properties feature, and possibly on the definition of the class itself.
I'm not saying these issues couldn't be resolved, but I'm skeptical they could be resolved in a way that led to a clean, unambiguous syntax, while preserving source compatibility with previous versions.
The python folks may be able to get away with breaking old code, but that's not Java's way...
According to Volume 2 of Core Java (Forgotten the authors, but it's a very popular book), the language designers thought it was a poor idea to hide a method call behind field access syntax, and so left it out.
It's the same reason that they don't change anything else in Java - backwards-compatibility.
- Is it because it's not deemed important enough when compared to other possible improvements?
That's my guess.
- Are there technical (e.g. JVM-related) limitations?
No
- Is it a matter of politics? (e.g. "I've been coding in Java for 50 years now and I say: we don't need no steenkin' properties!")
Most likely.
- Is it a case of bikeshedding?
Uh?
One of the main goals of Java was to keep the language simple.
From the: Wikipedia
Java suppresses several features [...] for classes in order to simplify the language and to prevent possible errors and anti-pattern design.
Here are a few little bits of logic that, for me, lead up to not liking properties in a language:
Some programming structures get used because they are there, even if they support bad programming practices.
Setters imply mutable objects. Something to use sparsely.
Good OO design you ask an object to do some business logic. Properties imply that you are asking it for data and manipulating the data yourself.
Although you CAN override the methods in setters and getters, few ever do; also a final public variable is EXACTLY the same as a getter. So if you don't have mutable objects, it's kind of a moot point.
If your variable has business logic associated with it, the logic should GENERALLY be in the class with the variable. IF it does not, why in the world is it a variable??? it should be "Data" and be in a data structure so it can be manipulated by generic code.
I believe Jon Skeet pointed out that C# has a new method for handling this kind of data, Data that should be compile-time typed but should not really be variables, but being that my world has very little interaction with the C# world, I'll just take his word that it's pretty cool.
Also, I fully accept that depending on your style and the code you interact with, you just HAVE to have a set/get situation every now and then. I still average one setter/getter every class or two, but not enough to make me feel that a new programming structure is justified.
And note that I have very different requirements for work and for home programming. For work where my code must interact with the code of 20 other people I believe the more structured and explicit, the better. At home Groovy/Ruby is fine, and properties would be great, etc.
You may not need for "get" and "set" prefixes, to make it look more like properties, you may do it like this:
public class Person {
private String firstName = "";
private Integer age = 0;
public String firstName() { return firstName; } // getter
public void firstName(String val) { firstName = val; } // setter
public Integer age() { return age; } // getter
public void age(Integer val) { age = val; } //setter
public static void main(String[] args) {
Person p = new Person();
//set
p.firstName("Lemuel");
p.age(40);
//get
System.out.println(String.format("I'm %s, %d yearsold",
p.firstName(),
p.age());
}
}