Coding conventions poll
This is a cross post from a thread in the Java Programming Forum. If you haven't read this there, read it here and please reply if you have a minute.
I'm conducting a personal study about some stuff, just
out of curiousity.
Who writes code like this:
public void method ()
for (...)
}What about this:
public void method () {
for (...) {
}Who puts semicolons after }'s:
public void method ()
for (...)
public void method () {
for (...) {
};I'd like to know how you usually format your code.
Additionally:
1) How old are you?
2) Where do you work/go to school?
3) What (if any) was your primary programming language
before Java?
4) How did you primarily learn how to program in Java
(book, school, examples, etc...)?
I'm just curious. I have some theories that I don't
want to share until I get a decent amount of replies.
Cheers,
Jason
I do it like this:
public void method ()
for (...)
}I like to use white space very liberally. To find a matching brace just look straight up. I have enough hard drive space to handle an extra byte here and there. The semicolons are superfluous.
Age 26.
Went to University of Waterloo, I prefer to keep my employer private information.
I was writing code in Basic, Pascal, C, and VB before I started Java.
I learned the theoretical aspect of how to program in University.
I learned everything practical at work or on my own. I continue buying books and writing software on my own time to learn new things. I taught myself Java. Been a forum member since '97.
Similar Messages
-
Java style and coding conventions
Hello All,
Most of my programming experience is in Java, and as such, I try to conform to the style and coding conventions that are used in all of the Sun tutorials, and to my understanding, the specification. I'm enrolled in my final semester of a bachelor's of computer science and engineering, and one of my courses is "Software Engineering". Our course assignment is to make a website, written in PHP. I don't really care for PHP, so I volunteered for the Code Quality Assurance team, thinking, I'm fairly consistent when it comes to adhering to the Java conventions, it should be reasonable to determine similar conventions for this project, and give my classmates pointers on how to improve the readability and layout of their source listings.
The problem is, my professor, absolutely, whole-heartedly hates Java. He despises everything about it. For example, I sent him a source listing that I felt was well written, readable, and adequately documented. Some of the things that I was "doing wrong" were:
1. Naming Conventions
All of the Classes were first-letter capitalized, subsequent first-letter of each word capitalized. FormLayoutManager was one particular example. All instance or primitive identifiers were first-letter lowercase, subsequent first-letter capitalized, so an instance of FormLayoutManager could be formLayoutManager, or menuLayoutManager, etc. All constants were all capitals, with underscores separating each word. MAXIMUM_POWER. All methods were first-letter lowercase, subsequent first-letter capitalized, showLoginComponents().
My Professor insists that the convention I (and most of the Java community as far as I can see) is terribly unreadable, and that all instances variables and method names be first-letter capitalized. I tried explaining that this sacrifices the ability to easily distinguish between a class type or interface, and an instance, and was ignored.
2. Declaration and Initialization
Also, supposedly declaring a local identifier and initializing it in the same line is some sort of abomination of everything sacred in programming. So I found myself constantly doing things like
public String info() {
StringBuilder info;
info = new StringBuilder(512);
// append a bunch of information to info
return info.toString();
}3. 80 Character line widths
He wants me to break any statement that is over 80 characters in width into multiple lines. I know a long statement wrapping around in your editor is a irritating, but 80 characters, seriously, who doesn't have an editor that can't handle more than 80 characters on a line?
4. this and argument names
In most of my constructors that accept arguments, I would usually do something like
public Student(String name, int age) {
this.name = name;
this.age = age;
}Which he thinks is horribly confusing, and should be
public Student(String n, int a) {
name = n;
age = a;
}5. singular collections / arrays identifiers
I had something like:
String[] keywords= new String[] { "new", "delete", "save", "quit" };
for (int i = 0; i < keywords.length; i++) {
System.out.println(keywords);
And he insisted that "keywords" be renamed "keyword", as in, the i-th keyword, which I think is kind of stupid because the array is an array of keywords, and having a singular identifier makes that less obvious.
It's driving me crazy. It's driving everyone else in the class crazy because they're all mostly used to Java style conventions as well. I've tried pleading my case and I can't even get him to acknowledge the benefits of the "alternative" styles that I've used in my programs up to this point.
Have any of you had to deal with either professors or bosses who have this type of attitude, whether it be towards Java or any other language? This guy has been involved with computer science for a while. I think he's used to Pascal (which I know nearly nothing about).You will find people who will disagree about this stuff all the time. I had a similar course and we read "Code Complete" which offers some style suggestions. Fortunately, my professor was intelligent enough to allow a discussion of these styles and I had a chance to argue against the "bracket every if statement" idea and other little things I didn't agree with. It was insightful conversation, rather than a "I'm the professor, you're a student, so listen to me".
Here's the important part: It doesn't matter what the standard is, only that there is one.
Unless I misunderstand, he allowed you to take on the responsibility of QA, so it is ultimately your decision. If the project suffers because of poor quality of code, it will be on your head. If, on the other hand, you give in to him and use a style that makes no sense and the project suffers because of poor code, it will still be on your head.
So he really has no position in this because he is not a stakeholder in this decision. Tell him that this is your responsibility and you need to make the choices that are right for your group, not right for him. If he's teaching you anything that can reasonably be called software engineering, he should understand that. Otherwise he's just teaching out of a book called "Software Engineering" and doesn't know anything (or so it seems from this small window you've given us).
caveat: If he's reviewing the code and he's particularly snarky about his "styles", you might want to consider giving in to his demands for the sake of your grade. Sad reality. -
What's up with the Sun Java coding convention
I thought Sun leading the Java development should also be a better example on the Java coding convention.
They do publish a coding convention guide, I believe. But looking at Java core library's source code, so long, coding convention! :(
Just looked at ArrayList.java source for the version 1.4.2. There are method names like RangeCheck(). Shouldn't a method start with lowercase? Shouldn't a method be verb first like checkRange() instead?
And there are statements like this all over the place:
if (foo)
bar();
shouldn't that be:
if (foo) {
bar();
man, I thought this golden version of the Java Foundation Library code should be almost perfect by this time now. :(
--if (foo)
bar();
// I think the most important part of the if statement
is the condition for executing the following
statement(s).
// Using this style the condition is separated from
the code by white space which I find easier to read
// It's also easier to maintain as you don't have to
remember to add {} if you need to add additional
statements.I follow camickr's example. I think it's more readable. Whitespace is a good thing, IMO, and not used enough. Putting the brace on the next line down not only makes it easier to associate opening and closing braces visually but it sets the block of code off visually from the rest. Personally, I get a gestalt effect from that.
I don't worry about a byte here or there. It might sound like heresy, but Moore's Law makes memory and disk space cheaper and more plentiful all the time. I think maintainability and readability trumps being miserly about bytes in my thinking these days. ;)
Spare me the "inefficiency" lectures. I know - performance matters. The 80/20 rule says that byte won't be killer.
It's too bad that Sun doesn't follow their own conventions. Don't they do code review there?
Joshua Bloch didn't follow the standard? Too bad - he did a great job on the collections design. Maybe he delegated it to a younger coder and missed that during the code review. Yeah, that's it! ;) -
Suns standard classes use of constants - bad coding convention
Wasn't sure where to post this, it didn't quite fit into Java Runtime Environment or Java Virtual Machine forums.
I was browsing through The Java Standard classes and was amazed by their use of constants. Throughout the codes there is inserted direct constants in the code without any use of global constant declarations.
Eg: java.lang.StringCoding:
All over the code is inserted "ISO-8859-1" (used as default encoding) directly instead of using a declared constant DEFAULTENCODING. What if Sun want to change default encoding?
Seems strange to me that such coding conventions are used by Sun. Any reason for this or just sloppy programing?
GilLooks like sloppy programming to me. I see no possible
reason for it. You're not the first person to
criticise Sun's source code. Maybe they outsourced it
to http://www.newtechusa.com/PPI/main.asp (I can never
remember how to format links, no matter how often
people tell me!)
RObinThere's logic in getting primates to program.
Based on the popular theory that an infinite number of monkeys could
randomly produce the works of Shakespeare, they could also produce the perfect software implementation of any given problem. The downside being that the printed documentation will be smeared liberally with faeces.
regards,
Owen -
Flex 2.0 Naming an Coding Conventions
Hello,
I'm new with Flex 2.0 and Actionscript 3.0.
They asked me to define naming and coding conventions for
Flex 2.0 and Actionscript 3.0 for our company.
I'm looking for documents for naming and coding conventions
for Flex 2.0 and Actionscript 3.0 so I can make conventions for our
company.
Who can help me?
Thanks in advance.
SimsonI think you could do one based on Sun's coding convention for
Java, since the syntax is similar. Take a look at the Java
convention and you'll get a pretty good idea -
JSP coding conventions document?
All,
I'm teaching a spring 2004 courses on JSP at Park University and I'd like to have a coding conventions document. I have one for my Java, HTML, and C++ courses and they're very helpful. In doing a Google search, I found this Sun article:
http://java.sun.com/developer/technicalArticles/javaserverpages/code_convention/
It looks very promising, but it suddenly stops after only 2 pages. The article says:
[We'll] address file names and organization, indentation, comments, directives, declarations, scriptlets, expressions, white space, naming conventions, and programming practices. As this is our first attempt at presenting a set of JSP coding conventions, we're quite interested in any feedback you may have on these recommendations. Please send all feedback to [email protected]
But the article stops after covering opening comments. I've sent an e-mail to the authors, but no reply yet.
Please help ASAP because I need to get squared away by the end of this coming week (1/9).
Thanks,
JohnThis article used to be much longer. I read it not long ago.
There was an original post about it here: http://forum.java.sun.com/thread.jsp?forum=45&thread=363196&tstart=540&trange=15
Don't know what happened to it. And after a quick google haven't managed to find it mirrored anywhere. -
Coding conventions for SERVLETS
Where to find coding conventions for Java Servlets ?
Why would they be any different from the coding conventions for all of Java?
http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html -
Java Coding Conventions - Debugging
I am developing a Coding Convention document for a group of folks that are doing some remote development for me and while I have reviewed the Java coding conventions provided by Sun, I haven't seen anything that talks specifically about debugging. I have been asked to include some recommendation concerning where (and when) to put debuggin messages within the code (i.e. when you enter a method, etc.) Are there any conventions around this? I have my own practices but I am looking to find a commonly used industry approach. Thanks
By debugging messages you mean comments? This is all I found in the doc:
"Use XXX in a comment to flag something that is bogus but works. Use FIXME to flag something that is bogus and broken."
I doubt that helps :P As far as an industry standard, not much out there that I could find. -
A poll of sorts... coding conventions
I'm conducting a personal study about some stuff, just out of curiousity.
Who writes code like this:
public void method ()
for (...)
}What about this:
public void method () {
for (...) {
}Who puts semicolons after }'s:
public void method ()
for (...)
public void method () {
for (...) {
};I'd like to know how you usually format your code. Additionally:
1) How old are you?
2) Where do you work/go to school?
3) What (if any) was your primary programming language before Java?
4) How did you primarily learn how to program in Java (book, school, examples, etc...)?
I'm just curious. I have some theories that I don't want to share until I get a decent amount of replies.
Cheers,
Jasonvacode said:
I've been trying to do both, but
the 80 characters on a line is kind of a pain.
Anybody else ever heard of this?I've never read it anywhere or been explicitly instructed to do it, but I have been bitched at by coworkers before for 120+ character lines, hehe.
Geez, I must be the only person who puts semicolons after the brackets. Old habits die hard, I guess. The only time I run into problems is if I do something like this...
public boolean method () {
try {
return true;
} catch (...) {
return false;
}; // <-- XXX
};...I get an "unreachable statement" error on line XXX. So I never put ;'s after try...catch blocks like that. So sue me.
Jason -
Poll... coding conventions
This is a cross post from a thread in the Java Programming Forum. If you haven't read this there, read it here and please reply if you have a minute.
I'm conducting a personal study about some stuff, just
out of curiousity.
Who writes code like this:
public void method ()
for (...)
}What about this:
public void method () {
for (...) {
}Who puts semicolons after }'s:
public void method ()
for (...)
public void method () {
for (...) {
};I'd like to know how you usually format your code.
Additionally:
1) How old are you?
2) Where do you work/go to school?
3) What (if any) was your primary programming language
before Java?
4) How did you primarily learn how to program in Java
(book, school, examples, etc...)?
I'm just curious. I have some theories that I don't
want to share until I get a decent amount of replies.
Cheers,
Jason> if (expr) {
doSomething();
} else {
doSomethingElse();
}> I agree with you in that I use that sameconvention for brackets. But I don't agree with your
justification for it. In fact I don't agree with
anybody's justification for why brackets should be
done one way or another.
My belief is that none of them are correct. It's like
trying to explain why you should put on your right
shoe before your left.I disagree.
Things should be consistent. So, if you write do {
// stuff
}while (a);instead of do {
// stuff
while (a);then you should also write if (a) {
// stuff
}else if (b) {
// stuff
}instead of if (a) {
// stuff
else if (b) {
// stuff
}However, if you write a do-while loop like do {
// stuff
while (a);then you cannot distinguish it from the following while loop if only the last line is visible (the rest might be e.g. outside the viewport of your editor): while (a);and this is clearly a Bad Thing™, so therefore you should write it the other way.
- Marcus Sundman -
Sun coding conventions for documentation are horribly outdated!
Seriously I have seen 10 different formats on searching that look way better and the fact the conventions on display from sun date to 1999 is very confusing.
Can I ask which is preferred (I am doing the SCJD and here is an example of format vs format)....
For beginning class comments.
* @(#)Contractor.java
* Version 1.0.0
* Date 27/03/2009
*/vs
* @(#)Contractor.java Version 1.0.0 Date 27/03/2009
Methods
* Sets the record number for the Contractor record.
* @param recNo A <code>Integer</code> containing the record number to be
* set.
*/vs
* Sets the record number for the Contractor record.
* @param recNo A <code>Integer</code> containing the record number to be set.
*/Edited by: Yucca on Apr 5, 2009 7:12 PM
Edited by: Yucca on Apr 5, 2009 7:14 PM
Edited by: Yucca on Apr 5, 2009 7:17 PM* Returns an Image object that can then be painted on the screen.
* The url argument must specify an absolute {@link URL}. The name
* argument is a specifier that is relative to the url argument.
* <p>
* This method always returns immediately, whether or not the
* image exists. When this applet attempts to draw the image on
* the screen, the data will be loaded. The graphics primitives
* that draw the image will incrementally paint on the screen.
* @param url an absolute URL giving the base location of the image
* @param name the location of the image, relative to the url argument
* @return the image at the specified URL
* @see Image
public Image getImage(URL url, String name) {
try {
return getImage(new URL(url, name));
} catch (MalformedURLException e) {
return null;
}This was taken from... [http://java.sun.com/j2se/javadoc/writingdoccomments/#format]
And this...
* ...method doSomethingElse documentation comment...
* @param someParam description
public void doSomethingElse(Object someParam) {
// ...implementation goes here...
}from [http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html] Notice how the @param docs differ and both are from sun! So Jwentling Mr. know it all which one must I follow? And this is not THE ONLY ONE WHERE SUN contradict their own conventions, leaving people like me asking here! Go moan at them for not being precise. -
When creating web applications in jdeveloper, am I to assume
that most web applications will have an application module? If
this is true how does one decide where to write his/her methods
and custom logic. It can be done in the application module, or
any of the view objects. Is there a standard one should follow.
Thanks,
BretteHi,
Your canned and custom logic should be put into your Entity
Objects when using BC4J. This allows for more efficient reuse
of you business logic because your different views will
automatically pick up validation rules and default values for
attributes, etc. You can do this by either using the Entity
Object editor. Right-click on the entity in the system
navigator and choose edit . . . and then go to the validation
tab.
You can create custom java code in your <entityname>Impl.java.
For example you could populate default values using a sequence
with code in a create method. See the following thread for
several examples of adding this kind of custom code at
http://forums.oracle.com/forums/message.jsp?id=647590
For a broad and detailed conceptual white paper on BC4J and
how it designed to take care of many of the J2EE design
patterns, see
[url=http://otn.oracle.com/products/jdev/htdocs/j2ee_with_bc4j/j2
ee_with_bc4j.html]Using J2EE and EJB Development with BC4J
Hope this helps. -
When my Start button is clicked it changes a member variable from false to true.
Here is a simplified version of my code:
public class gdvdhomevideo
private boolean blnBegin;
public static void main(String[] args)
while(blnBegin == false){}
//perform operations
public void actionPerformed(ActionEvent e)
String command = e.getActionCommand();
if(command.equals("Start"))
blnBegin = true;
}So when the user clicks start it exits the while loop and the program starts performing other functions. The problem is that this approach is 100% CPU intensive and I know that there must be a better way?1) Code executed in the main() is NOT running on the event thread. Don't do any GUI code from the main thread... You know, stuff like showing windows, attaching event listeners etc.. You need to wrap all that stuff in a Runnable and pass that Runnable to SwingUtilities.invokeLater().
2) Assuming the stuff you're doing in the main() is actually thread safe and doesn't touch the GUI, you can simply startup a new Thread and put your code in there. (see below)
3) You class name is named badly. Please check out sun's java coding conventions. It is very nice to have coding conventions. Use them! ;-)
4) if you want to setup your program as a loop rather than simply relying on user actions to fire events, then I'd suggest you use a timer that notifies on the event thread every X where X is a non-zero polling interval. I think there's a class is called SwingTimer that does this sort of thing for you.
What you're attempting to do is non-trivial.. so.. ummm.. have fun..
public class gdvdhomevideo
private boolean blnBegin;
public static void main(String[] args) throws Exception
SwingUtilities.invokeLater( new Runnable() {
public void run() {
//setup stuff in here.
public void actionPerformed(ActionEvent e)
String command = e.getActionCommand();
if(command.equals("Start"))
new Thread(new Runnable() {
public void run() {
//perform operations but don't touch the GUI.
}.start();
} -
Where to find coding best practices for j2se 5 specific features?
The Coding conventions page seems to be out of date (http://java.sun.com/docs/codeconv/) since it was last updated in 1999. Where can I find the new dos and don'ts for the new J2se 5 features,
Maybe
Thinking InJava would be a nice place to start.I just checked my library to see whether I own Effective Java (just
changed that). My first reaction was: "WTF? I have a J2ME book? And
JDBC, of all things!?" :)lol! In a way I like the idea of a j2me technology stack; I just find the
realization thereof a totally, dumb mess. Those telecom drones don't
really want to be compliant so nor will their implementations they
provide either.
JDBC is just a necessary evil, no more no less. xml is an invention of
the devil's bad and nasty sister though ;-)
kind regards,
Jos -
i having this kind of error:
sendMail.java:89: illegal start of type
return true;
^
sendMail.java:89: <identifier> expected
return true;
^
sendMail.java:92: 'class' or 'interface' expected
^
sendMail.java:93: 'class' or 'interface' expected
^
4 errors
and my application coding are:
package common;
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.sql.*;
import java.lang.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class sendMail{
public void sending(String Address,String content,String subject,String attachment,String from_address, String host){
// Get system properties
Properties props = System.getProperties();
// Setup mail server
props.put("mail.smtp.host", host);
// Get session
Session session = Session.getDefaultInstance(props, null);
// Define message
MimeMessage message = new MimeMessage(session);
try
message.setFrom(new InternetAddress(from_address));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(Address));
message.setSubject(subject);
message.setText(content);
// Send message
Transport.send(message);
catch (MessagingException e)
System.err.println("Caught Exception: "
+ e.getMessage());
boolean retryFlag = true;
// Log the error
synchronized (logger) {
errorHandler.error("[COULDNT_SEND_MESSAGE]", e);
if (e instanceof SendFailedException) {
SendFailedException sfe = (SendFailedException) e;
Address[] invalid = sfe.getInvalidAddresses();
addressWarning("[INVALID_ADDRESSES]", invalid);
Address[] validUnsent = sfe.getValidUnsentAddresses();
addressWarning("[VALID_UNSENT_ADDRESSES]", validUnsent);
Address[] validSent = sfe.getValidSentAddresses();
addressWarning("[VALID_SENT_ADDRESSES]", validSent);
if (invalid != null && invalid.length > 0)
retryFlag = false; // there is no point to retry
// Retry with a new transport object. Don't log any new errors.
if (retryFlag) {
Transport newTransport = null;
try {
// Try to resend the message using a new connection
newTransport = session.getTransport(protocol);
newTransport.connect();
newTransport.sendMessage(msg, msg.getAllRecipients());
// Try to close the old transport
try {
transport.close();
} catch (Exception t) {
// The new transport object worked
transport = newTransport;
return true;
} catch (Exception t) {
// The new transport failed too. Try to close it
if (newTransport != null)
try {
newTransport.close();
} catch (Exception t2) {
return false;
return true;
can someone help me to solve. i already use my whole day time try to solve the problem, but i still cannot get it. who expert on this field please open your kindly heart, give a way out to me. thank you.
regards,
albertFirst: please stay with the coding convention and Use capital letters for class names (I suggest "Mailor" instead of "sendMail").
Second: use the code tags in this forum so that source code is formatted in a readable way.
Third: you can't return something in a method without a return type (void).
Fourth: please work through http://java.sun.com/docs/books/tutorial/java/index.html
Maybe you are looking for
-
How can I install ntfs on an external hard drive so that my Samsung Smart TV can see my media files? Or is there a better option?
-
Every time i try to do anything with itunes it freezes after a few seconds and i have to force it to close. Does anyone know how to fix this problem? Im aweful with computers and have tried everything i know of.
-
Why can't I save a picture after I change the resolution in CS5, I could before.
Why am I unable to save a picture one I change the resolution? I know that I am doing it correctly I have done this thousands of times and all of a sudden it doesn't work. Pictures will save if I make other adjustments i.e. crop, erase...etc. The cha
-
Regarding the "Get a Free iPhone" advertisement...
I can understand how the iPhone 5s 16gb can be valued at $300, and the iPhone 4 16gb can be valued at $200, but how can the iPhone in between, the iPhone 5 16gb be valued the SAME as an iPhone 4? If Verizon is valuing the iPhone 4 at $200, shouldn't
-
Hi all, Am Looking for a UDF to replace "-" sign at last. Source. -000000000400.00 Target 000000000400.00-