What NOT to do when Java Coding

  • (5 Pages)
  • +
  • 1
  • 2
  • 3
  • 4
  • 5

70 Replies - 39873 Views - Last Post: 30 May 2013 - 04:57 PM

#31 toshiro  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 21
  • View blog
  • Posts: 137
  • Joined: 27-June 09

Re: What NOT to do when Java Coding

Posted 06 February 2011 - 04:19 PM

Single Monster class files The OO paradigm lends itself to modular, scalable, and reusable code. A constant tactic I see in intro CS classes are single massive Driver.java files that contain multiple object classes in addition to a bloated and comprehensive main method. Splitting each object into separate class files makes for easier to debug code (ie clean traceback routes) as well as just plain easier to look at as a dev.

Interpreters abstract away many of the tricks and isms used in C to gain efficiency - thus, if you use an OO lang like Java, then actually abide by its data model.

This segways into a previous poster's comments on the modulating of GUI vs operational/logic code. Separation of form (GUI) and function (well, functions) becomes an imperative as the program is scaled or, heaven forbid, morphs into a mobile implementation.

You will always be learning something new. Everyone is.
Was This Post Helpful? 1
  • +
  • -

#32 n8schatten  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 145
  • View blog
  • Posts: 263
  • Joined: 07-December 10

Re: What NOT to do when Java Coding

Posted 07 February 2011 - 08:00 AM

Got another one that frequently scares me:

The monster-if with no else.

For example:
public void someMethod() {
	if (SOME_CONDITION) {
		// ...
		// ...
		// many lines of something
		// ...
		// ...
	}
	// nothing to be done is the condition doesn't apply
}


I just hate it, when I have to scroll all the way down to the end of a method just to see that nothing happens if the condition doesn't apply. Recently I saw a piece of code in the forums which carried this to an extreme (have a look at the comment where you'd expect the else ;)):

public void actionPerformed(ActionEvent e) {
	if (foo == STATE) {
		// ... many many lines that do something
	}//else if foo != STATE then do nothing
}


Since I dislike this kind of ifs, I came to use Guard Clauses instead:
public void someMethod() {
	if (!SOME_CONDITION) {
		return;  // just do nothing if the condition doesn't apply
	}
	// ...
	// ...
	// many lines of something
	// ...
	// ...
}


This way you can see what happens if the condition doesn't apply at first sight and you don't have to scroll to the end of the method just to see that nothing happens.
Was This Post Helpful? 2
  • +
  • -

#33 cfoley  Icon User is offline

  • Cabbage
  • member icon

Reputation: 1940
  • View blog
  • Posts: 4,027
  • Joined: 11-December 07

Re: What NOT to do when Java Coding

Posted 07 February 2011 - 11:24 AM

I definitely agree with that one. However, a lot of people are still taught to have one point of exit from a function. Also, part of the problem may be having all those lines in the same method to begin with.
Was This Post Helpful? 0
  • +
  • -

#34 Guest_Bhushan*


Reputation:

Re: What NOT to do when Java Coding

Posted 15 February 2011 - 12:14 PM

@xclite:
What if your Date class is used to fill a form. You have to check wether the birth date entered by user is of living person or not(greater than 200 means he must be dead.)?
So now you will add those getters and setters. And then the code who used your class should also be modified.

This is very small problem to deal with. Its better that no complexities arise due to bad coding habit.

And cfoley is trying to explain the same, I guess.

PS: No offense meant. Peace. :)
Was This Post Helpful? 0

#35 xclite  Icon User is offline

  • LIKE A BOSS
  • member icon


Reputation: 894
  • View blog
  • Posts: 3,153
  • Joined: 12-May 09

Re: What NOT to do when Java Coding

Posted 15 February 2011 - 01:52 PM

I'm not dragging this back up, but I pointed out that my Date class would, in fact, have getters and setters.
Was This Post Helpful? 0
  • +
  • -

#36 Mohawk  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 15
  • Joined: 24-August 10

Re: What NOT to do when Java Coding

Posted 15 February 2011 - 07:23 PM

The worst thing I see in code developed by others: not using the power of Javadoc to document the class/module. What a fantastic tool we have in Javadoc, why someone would be so lazy as to leave their documentation blank or even delete the comments.

If you want to impress, learn the rules/tags of Javadoc and don't stop there. After the first line, you are basically working in HTML. Use tables, lists, whatever it takes to let people know how to use your code. Generate your Javadoc documentation and make sure you can understand it. When in doubt add more detail.
Was This Post Helpful? 2
  • +
  • -

#37 SpeedisaVirus  Icon User is offline

  • Baller
  • member icon

Reputation: 114
  • View blog
  • Posts: 855
  • Joined: 06-October 08

Re: What NOT to do when Java Coding

Posted 15 February 2011 - 07:31 PM

Mohawk couldn't be more right. Javadoc is a uniquely powerful tool and people seem to not too often use it. Infact (I develop C# for a living) it's the one redeeming quality that makes me still appreciate java despite all of the features that should be in Java7 that aren't going to be seen. MS has completely dropped the ball by not picking up the awesomeness JavaDoc functionality provides.
Was This Post Helpful? 0
  • +
  • -

#38 n8schatten  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 145
  • View blog
  • Posts: 263
  • Joined: 07-December 10

Re: What NOT to do when Java Coding

Posted 16 February 2011 - 06:09 AM

I partially agree with Mohawk. Javadoc is indeed a great tool, but it is also very easy to overdo it. Which directly leads to another thing NOT to do (imho):

Do not overcomment!
When looking at the code of some of my fellow students I saw things like:
/**
* Getter method for someAttribute to avoid direct access to someAttribute.. bla bla bla bla
* @return someAttribute - variable containing the value of bla bla bla
*/
public SomeClass getSomeAttribute() {
  return someAttribute;
}


This is not only superfluous, but also kind of disturbing!
Another aspect of overcommenting is trying to enhance bad code by adding a vast amount of comments. One example of this is the much too long method which is divided into smaller parts by adding comments. Why not pulling out another method and give it a speaking name? The method's name is very likely to convey all the information the comment would have (e.g. //calculate number of items -> private int calculateNumberOfItems() {...}). If you have to add this kind of comments, you probably should re-think your design.

PS: I do not advocate undercommenting, which you should also NOT do!
Was This Post Helpful? 3
  • +
  • -

#39 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7564
  • View blog
  • Posts: 12,693
  • Joined: 19-March 11

Re: What NOT to do when Java Coding

Posted 21 March 2011 - 07:59 PM

View Postxclite, on 04 February 2011 - 08:10 AM, said:

I disagree with never declaring a public member. If you have a data item in a class, and it has a getter and a setter, you're just adding redirection. Don't declare public members when some sort of control or manipulation happens, sure. But what's the point of adding methods if all the method does is set or return the value?



I agree with you - sort of. I'd ask, why does it have a getter and a setter? Why is some other class allowed to reach in and tweak this class' innards? Sometimes this makes sense, but usually it's just a bad idea. If the field is to be modified, the logic should live in that class. So I'd say
a) public fields are okay, as long as they're static and final
B) mutable fields should only be changed directly by the class they're in
c) other classes should interact with the object, not the data. If I'm writing a game, and an object needs to move, I should be telling it "move yourself ten units forward" or "turn left 45 degrees and set your velocity to 4", and the object should know what that means. I should not be telling it "set your position to X,Y".

So yeah - "what's the point of adding methods if all the method does is set or return the value?" is a good question. I just disagree with you on the implications. :)
Was This Post Helpful? 1
  • +
  • -

#40 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7564
  • View blog
  • Posts: 12,693
  • Joined: 19-March 11

Re: What NOT to do when Java Coding

Posted 21 March 2011 - 08:33 PM

View Postcfoley, on 07 February 2011 - 11:24 AM, said:

a lot of people are still taught to have one point of exit from a function. Also, part of the problem may be having all those lines in the same method to begin with.


Single point of exit is a harmful dogma. You should always get out as soon as you can. That's why return statements show up in bright flashing neon green alternating with hot pink (at least, they do if you code in vi without syntax highlighting - you learn to see this stuff, if you don't code with crutches)

Too many lines in a method is the correct root cause. That method should be broken down into helper methods - probably three or four levels of them, if it's fifty lines of code.


View Postn8schatten, on 16 February 2011 - 06:09 AM, said:

I partially agree with Mohawk. Javadoc is indeed a great tool, but it is also very easy to overdo it. Which directly leads to another thing NOT to do (imho):

Do not overcomment!



Quoted, as the kids say, for truth. I'm a technical writer, documentation is what I do for a living, and one of the big things you need to address in that field is: too much information is negative information. Documenting a getter/setter method is a perfect example. (Never mind that the getter/setter probably shouldn't exist!) If you're reading through the documentation and you see too many "getFoo(): gets foo" "getBar(): returns this object's bar field" "setQ(int q): sets q to the given value", you're going to miss something like "setZ(int z): set the value of Z. Allowable values are in the range [1..5], inclusive, any other value will cause the machine to execute an HCF shutdown" because you've stopped reading at that point. Your method name should tell me what the method does, your parameter names should tell me what the method expects, and your throws clause should tell me how it breaks. The javadoc should tell me what I won't guess from a well-written mthod signature.
Was This Post Helpful? 3
  • +
  • -

#41 Bellum  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 53
  • Joined: 04-February 09

Re: What NOT to do when Java Coding

Posted 03 June 2011 - 12:17 PM

View Postn8schatten, on 16 February 2011 - 07:09 AM, said:

One example of this is the much too long method which is divided into smaller parts by adding comments. Why not pulling out another method and give it a speaking name? The method's name is very likely to convey all the information the comment would have (e.g. //calculate number of items -> private int calculateNumberOfItems() {...}). If you have to add this kind of comments, you probably should re-think your design.


Ah, yeah. I've totally been doing that. :sweatdrop:

EDIT:
Now that I think about it, putting everything in a JFrame constructor is probably a bad idea. :stupid:

This post has been edited by Bellum: 03 June 2011 - 12:19 PM

Was This Post Helpful? 0
  • +
  • -

#42 SixOfEleven  Icon User is offline

  • using Caffeine;
  • member icon

Reputation: 945
  • View blog
  • Posts: 6,342
  • Joined: 18-October 08

Re: What NOT to do when Java Coding

Posted 03 June 2011 - 01:39 PM

View Postxclite, on 04 February 2011 - 11:10 AM, said:

I disagree with never declaring a public member. If you have a data item in a class, and it has a getter and a setter, you're just adding redirection. Don't declare public members when some sort of control or manipulation happens, sure. But what's the point of adding methods if all the method does is set or return the value?


Data validation is the point, and it is so very often over looked. Even a variable whose value you don't care about may need to be validated down the road. It is good practice to use get and set methods instead of having to go back in the future and do it. So you write a little more code and it takes a few nanoseconds more to execute. You'll thank yourself if you ever have to go back and do it in a large enterprise application.

Though I never use it, that is why I like this property structure in C#.

public string SomeProperty
{
    get;
    set;
}



It is so easy to go back six months or a year down the road and add validation.

string someField;

public string SomeProperty
{
    get { return someField; }
    set
    {
        // Perform validation
    }
}



I know we are talking Java here and not C# but the principle remains.

private string someField;

public string getSomeField()
{
    return someField;
}

public void setSomeField(string value)
{
    // Perform validation
}



If the value of a variable is critical I will go so far as to use these sorts of accessors rather use the variable to be sure that its value is never compromised.
Was This Post Helpful? 1
  • +
  • -

#43 smohd  Icon User is offline

  • Critical Section
  • member icon


Reputation: 1817
  • View blog
  • Posts: 4,625
  • Joined: 14-March 10

Re: What NOT to do when Java Coding

Posted 03 June 2011 - 02:17 PM

To add two things that were said not by me in other help threads:
Don`t create multiple objects of Scanner
Some people give every input its own object of Scanner like

  public static void mani(String[] args){
      String name;
      int age;
      Scanner keyboard = new Scanner(system.in);
      name = keyboard.nextLine();
      Scanner keyboard1 = new Scanner(system.in); 
      age = keyboard1.nextInt();
}


Don`t mix threading with GUI
Was This Post Helpful? 0
  • +
  • -

#44 jgonzalez498  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 43
  • Joined: 29-May 11

Re: What NOT to do when Java Coding

Posted 07 June 2011 - 09:48 AM

View Postm-e-g-a-z, on 04 February 2011 - 03:12 AM, said:

A really bad thing I don't like people doing is putting all of their code in a try block such as when they are reading a file for example. You should only have something that might generate an exception in the try block NOT inserting everything you read from the file into an array list within the try block.

This below just doesn't look nice..ITS NOT RIGHT. I would NOT recommend anyone to write code like this below.

	
			try {
                                ArrayList<String> a = new ArrayList<String>();
				Scanner s = new Scanner(new FileReader("abc.txt"));
				while(s.hasNext())
					a.add(s.next());
				 System.out.println(a);
				 
			} catch (FileNotFoundException e) {

				e.printStackTrace();
			}



All you would need in your try-catch blocks is this..

                       //Initialise Scanner to null etc.
			try {
				 s= new Scanner(new FileReader("abc.txt"));
	 
			} catch (FileNotFoundException e) {

				e.printStackTrace();
			}
                       
                        //Then add to arraylist


Another thing is when people use pointless print statements. I can understand print statements are a good way of debugging but really are going to have this?!

 public int getValue() {
  System.out.println("Calling the getValue Method.");
     return value;
 }     



But is it really that bad of a practice to do this. Because I do it alot o.o but then again I wouldn't know better lol :sweatdrop:
Was This Post Helpful? 0
  • +
  • -

#45 xclite  Icon User is offline

  • LIKE A BOSS
  • member icon


Reputation: 894
  • View blog
  • Posts: 3,153
  • Joined: 12-May 09

Re: What NOT to do when Java Coding

Posted 07 June 2011 - 10:21 AM

View PostSixOfEleven, on 03 June 2011 - 04:39 PM, said:

If the value of a variable is critical I will go so far as to use these sorts of accessors rather use the variable to be sure that its value is never compromised.

I am getting tired of reiterating this, but I agree that accessors are important. I disagreed that they were always necessary. There ARE cases where you know you will never need more than a "return this.value."
Was This Post Helpful? 0
  • +
  • -

  • (5 Pages)
  • +
  • 1
  • 2
  • 3
  • 4
  • 5