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 8 years ago.
Improve this question
I am currently a junior engineer and keen on learning best practices and expanding my experience. My question concerns any static programming language such as Java, C#, C++ etc.
When I am writing code, I like making it easy to read. In my opinion, reading code should be like reading a book. It should be fluent and elegant. Then, even if I do not need to use them, I like prepending this, super–base keywords whenever I can. Ditto for current class name when I want to use constants or static variables/methods.
Consequently, another developer can quickly have a long shot. He knows this method or var is in the current class or in mother class without needed to move to declaration. You may say to me it is really easy to do that with recent IDE. However, I know a bunch of guys who are still working with Vim, Emacs or other editors without these fancy features.
When explaining it, I like comparing my practices to a drama book. We have all read at least one of them, such as Macbeth from Shakespeare. Who has never felt frustrated to go back at the beginning of the book to know who is that character and what part he has in the plot? You did that so many times, right?
My question can be associated to literate programming practices. However, I assumed Donald Knuth's recommandations are more about commenting and adding macros to your code.
So I would like to know your opinions and feedbacks about these practices. Am I doing too much? Should I keep it simpler? Am I breaking OOP rules?
Here is a code sample:
class Bar {
protected int _motherVar;
public aBarMethod() { }
}
class Foo extends Bar {
private static List<String> _strings;
private int _myPrivateVar;
public void aMethod() {
super.aBarMethod();
this._myPrivateVar++;
super._motherVar -= 2;
}
public static String anotherMethod() {
String outcome = "";
for (String s : Foo._strings) {
outcome += s;
}
return outcome;
}
}
It's a very good thing that you care about this.
At the same time, every programmer has gripes about it.
One of mine is that while modern displays have oodles of pixels, you would think that would mean programmers could see more of their code on the screen.
What it seems to mean instead is that the code is so puffed up with whitespace that the content is pushed off the screen.
This makes the code seemingly more "readable" by giving you less to read :)
Another point of mine is that no amount of readability can make code understandable to someone who isn't where you're at in understanding concepts.
I think an important part of the programmer's job is to educate the reader in the basics of what is being done.
Without that, they just won't "get it".
That's not good, because they may very well decide to re-write it (and break it).
To make your code look nice, first thing you need to do is make correct tabs and spaces, so that the code is aligned just the way that is easy to see how the statements are grouped. Everything else, whether you name the variable 'myVariable' or 'my_variable', is just a matter of your preference. It's also a good practice to comment as much lines of your code as possible. That really helps when you return to your code after some time.
Related
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 3 years ago.
Improve this question
I'm fairly new to Java but love it so far. My question is, i'm a little unfamiliar with Classes. I know what they are, and generally how to work with them as I'm not brand new to programming, but I would like a professionals opinion.
I'm currently writing a small multi threading program to launch parallel power shell sessions by spawning cmdlines for target machines in a csv, capture the output and write to a csv.
Should I put everything into one class and breakup the logical operations to methods within the class and string them together? Or should I make a Thread executor class, cmdline powershell class, a csv operations class, etc (My thought behind that was to allow code reuse, but that'll be kindove time consuming and in my mind impractical since i'd have to specify the datatypes and return types for new situations in the future).
Any help would be appreciated!
There is no "way" so to speak,
It's all your preference.
But just don't cram everything into one class.
Generally, you want to be as neat as possible.
In the future, you will thank yourself for using different classes.
If your project grows, and a bug is born, you don't want to be looking through one very long class, but instead simple broken up pieces.
Let's say you have these classes:
GPS,
Main,
Search
And someone reports a bug with the GPS not working.
Instead of looking everywhere saying, where did I put the GPS code,
it's right in front of your eyes!
I've went to everyones links and found the info very helpful. So far I've come up with this.
Make a package that contains classes that perform a specific set of tasks (also don't make utility kits that are very general). The package in my case would be called com.jt.threads.powershell or something.
Keep classes small and breakup the program by conceptual types. (ie. data reading and writing operations on a filesystem should be in one class with the focus on helping the package perform a certain task or range of tasks.)
Methods within classes should focus on getting, setting, changing the objects attributes or adding logic.
The program entry point should join it all together, except in the case of large applications, in which case an interface should be used (still learning about them).
With true OOP, i don't think it's a good idea to create code for reuse, unless it's supporting a range of very very very similar tasks (that way if I have to change something, it won't break other classes outside of the package).
Thank you all! I feel a lot better knowing that I'm on the right track. I was worried that by NOT making code reusable in a lot of situations that I was doing something wrong. I started programming in Python 6 months ago for my job, but I totally ignored classes and I want to have good programming habits and apply OOP as best I can going forward! Python is definitely convenient and a great starter language, but I wish I learnt Java first so I can get a solid grasp on OOP.
There is no “The way” to organize or group classes. Anything goes as long as it works as expected and you understand what you write.
As a Programmer you only need to,
1. Know and understand what you write.
2. Know and understand what other Programmer as written.
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 3 years ago.
Improve this question
I am curious to know the current coding style for java. My team is forcing to use {} for one liner if statements. Although we used to have braces for one liners current java source code does not use braces for one liner if statements anymore and I myself am inclined towards the same.
Python dropped braces altogether.
However I do not see any particular style guide in 2019.. The oracle doc still refers to the 1997 coding style.
What would be correct coding or is it something more to do with developer's preference?
foo();
if (condition)
doSomething();
bar();
vs
foo();
if (condition) {
doSomething();
}
bar();
Edit 1: As Kartik mentioned we can write one liners like this as well:
if (condition) doSomething();
For me, it as a developers preference and I am ok with both the approaches but in my current team some developers are of opinion not using braces is a BAD coding practice. I saw the java source code and found in many places braces are omitted. So, I don't believe this to be true. As for google coding style, it was also there for many years and many people continue to use the same. But for new code are there any new guidelines?
Edit 2: This question is marked as opinion based and put on hold
I want to clarify that I am NOT looking for opinions. I am more looking for standard guidelines which Oracle (or java open source communities) might have put forward regarding best practices as of today (2019). Most practices java/google are very old dating back to 1996 and may not be relevant today. Even if there is some reference in some new books and some can share those details it will be very helfpul
I think one of the commonly used style guides for java is the one from Google, see here.
It says:
Braces are used with if, else, for, do and while statements, even when the body is empty or contains only a single statement.
But the real general answer here is: only use such input as hint what to do. For you: sit down with your peers, and check out what you like, and then write that down, and go with it. Like: our team decided to use the google style, but to make subtle changes to it here or there.
And then make sure that your tooling supports your preferred style. One of the reasons why we selected "google style" is the fact that you get formatting templates for eclipse, IntelliJ, and even SlickEdit.
I agree that there are no "prominent" style guides for Java8 (and newer) elements, such as lengthy stream statements. That is where "decide with your team what you want" comes in again. We decided for example that
stream()
.filter(...)
.whatver
each go on their own line (one reason for that is the fact that IntelliJ will then give you the return type of each line right there while editing, what I find extremely helpful when working with streams).
Write as you like. I prefer brackets.
They help navigate the code.
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 6 years ago.
Improve this question
which coding style is better and what are the types of people in image programmers will know
which is better as a good programmer?
First writing curly braces after if statements - or curly braces on new line after if statement?
if(condition){
}
if(condition)
{
}
Although this is very much a matter of style, the "Java way" of doing it has always been to put the opening brace on the same line as the statement it is attached to. So
if(condition) {
}
is the suggested way of doing it. Who suggests this? Well, Sun did (and now Oracle maintains that page, too). And Google does.
I'd say that it's up to you to decide, which one suits you best. Also, from what I know, some languages are encouraging to use specific style:
Java preffers camelCase and
if (true) {
}
C# PascalCase and
if (true)
{
}
However, it's important to keep style consistent in project. If you mix styles in single file / project, that's bad practice.
As other has written, there are certain standards that promote
if (whatever) {
}
as the "better" solution.
In that sense, "better" actually means:
the majority of Java programmers is used to this style
therefore, for the majority of programmers, it will be easier to read code that is following the common styles
or vice versa: if you deviate from the common standards, everybody reading your source code will burn unnecessary brain cpu cycles to accustom to that deviating style
(and keep in mind: normally, source code is written "once"; but read maybe hundreds or thousands of time. thus "wasting brain cpu" is a serious issue)
But, on the other hand, the answer is: it depends.
My personal experience is: if you are following a consistent style, then the details of that style do not matter too much. You see, if your company has its own style conventions; and everybody is following those ... then you have to adapt. Period. And honestly: it is not that hard. I was asked to use all kinds of style conventions. And you simply adapt. It might take some time, but in the end, you will have no problems reading/writing code that maybe says
if (whatever)
{
So, when your team says: for our own good reasons, everybody has to use that second style, then that's it.
But if you are working on open source, or you are the person defining the style to use - then simply stay close to the "official" conventions from Oracle.
And final note: code formatting is a tooling question. You make sure that you specify your style convention so that your IDE can enforce it. Then you are even free to use your very personal style - just reformat source upon checkout; and turn back into "other peoples style" prior checkin to you source code repository.
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 8 years ago.
Improve this question
I've been running through a lot of code reviews and keep running into a situation where I see conflicting coding standards regarding boolean variables and if statements.
Here is an example of one method(1):
boolean isXTrue = getBooleanValue(DataSetX);
if (isXTrue) {
//do code
}
Here is an example of the other method(2):
if (getBooleanValue(DataSetX)) {
//do code
}
Both do the same thing and function just fine. In some cases, method 1 is a lot more readable since the boolean variable can be named something meaningful, while method 2 saves more lines and unnecessary boolean variable creations.
Maybe I am reading too deep into a simple coding standard, but I'm rather curious that if we use method 1 more often, we could have unnecessary booleans being made.
Sorry if this is a stupid question, but I wanted to get some opinions anyway :)
It's likely that the compiler will optimize both cases so that either way is identical at run time. Of course, that depends on code outside the context that you've provided.
As for the question at large: it's something that you and your coworkers or group need to come to a consensus about. If you're looking for a definite answer about which one to choose, I don't think you're going to get anything convincing other than personal preferences of readability vs line count.
Discuss this with the others that maintain your code base and decide on which should be preferred. Clearly explain why. Then move on to more...err...important issues.
As for my preference? I like option 1. To me, it's more readable, the variable name can be something descriptive like isActive, which makes the code easier to read. Also, inspecting values during debugging is probably easier as you have a definite variable with which to reference prior to its use later in the chain. Again, that's my preference.
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 4 years ago.
Improve this question
If you read other people's source code, how do you approach the code? What patterns are you looking for (datatypes, loops, use of control flow, ... )? How long can you read other people's code without getting bored? What is the most exciting patterns that you have discovered so far?
At first, I ignore the urge to change the code. Which is sometimes hard to do. But understanding first and change later saves yourself a lot of nasty "learning experiences."
Next if the format is bad, reformat. Use a code formatter if you have one. This is because you tend to look at the indentation and if that is bad, your understanding of the code is also questionable.
Then, if there are complex datastructures, I like to draw a little diagram. The challenge here is keep it as simple as possible. Large diagrams are fun on the wall, but most of the time, they are to cumbersome to look at. So it is wasted time.
If you finally understand what a piece of code does, write a comment. This is essential, because else you won't understand it the next time you are here.
The following step is to create unit tests. Now you can not only test the code, but you can also test your understanding of the code.
Last, if you understand it al and you know it can (and need to be) better, change it. But be sure to run the tests. Unless you are paid by each solved bug.
A hip new term for this is Code Spelunking.
Aside from the obvious "work from the top down" general approach, it depends on why I'm reading it: code review, trying to understand a bit of avaialable code to adapt for my own use, trying to learn a new technique, etc.
It also depends heavily on the language. If it is an OOPL, I'll probably do something like this:
Look first for the primary class relationships and try to understand the primary responsibility of each class.
Look at the interactions between classes to see how they collaborate.
Look at the interfaces of the key classes to see what "services" they offer their collaborators.
Look inside the non-trivial methods if it's important to understand how they are working instead of what they are responsible for.
thanks, if I understand correctly, first step is to identify the context, second identify API's, and place the API's in context. I just realize it is a bit like looking at a building or piece of art, you could focus on the material used, or the function of parts, try different perspectives, judge how parts fit in the whole... there is a nice piece of the process of discovery: here - how mathematicans think
It all depends on what type of code you are reading. Is it a web app, a service, a desktop app? When I do start reading other's code I usually start looking for design patterns used. Or for the framework-specific things. But again this is if you are doing a review. If you are reading for your own interest and to learn something there really is no answer - you should read and understand the code thoroughly.
Pick an item you understand in the final product and see how it is put together. If you've got the unit tests then they are a great help.