Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 5 of 5

Thread: Encapsulation (getters and setters) Tips?

  1. #1
    Junior Member Robertgif's Avatar
    Join Date
    Feb 2013
    Posts
    19
    My Mood
    Amazed
    Thanks
    6
    Thanked 1 Time in 1 Post

    Default Encapsulation (getters and setters) Tips?

    Hello all, as I continue coding, I have gone back over some code that I wanted to encapsulate. I made all my instance variables private and made a lot of new public methods that would be used to set and get my instance variables. While I don't have any particular question about encapsulation, I was hoping anyone could read over my most recent code and offer any tips/suggestions so that I am not practicing bad habits.

    Its rather hard to kill a bad habit if you do it a lot.

    Thanks!

    public class player{
    	private int health = 100;
    	private char sex;
    	private String name;
    	private static short damage = 10;
    	private static int hitchance;
     
     public void attack(){
    	//First decides if they hit or not...
    	setHitchance();
    	if (getHitchance() >= 6){
    	System.out.println(name + " prepares for an attack...");
    	System.out.println(name + " unleashes the attack for " + getDamage() + " damage!");
    	health = health - damage;
        }
    	else{
    	System.out.println(name + " missed!");
    	}
     } 
     public void die(){
    	System.out.println(name + " has died");
    	System.out.println(name + " loses");
     }
     public void setHitchance(){
    	hitchance = (int) (Math.random() * 10);
     }
     public int getHitchance(){
     return hitchance;
     }
     public void setSex(char maleOrFemale){
    	sex = maleOrFemale;
     }
     public char getSex(){
    	return sex;
     }
     public int getHealth(){
    	return health;
     }
     public void setName(String NameA){
    	name = NameA;
     }
     public String getName(){
    	return name;
     }
     public int getDamage(){
    	return damage;
     }
    }

    Another Class...
    public class fightGame {
    	player fighter1 = new player();
    	player fighter2 = new player();
     
     public void introFight() {	
    	fighter1.setSex('m');
    	fighter2.setSex('m');
     
    	fighter1.setName("Lig");
    	fighter2.setName("Bone");
     
    	System.out.println("\nWelcome one and all to the grand fighting arena!");
    	System.out.println("Today we will see the fight off between the one and only: " + fighter1.getName() + " and " + fighter2.getName());
    	System.out.println("\n");
     }
     public void startFight() {
    	System.out.println(fighter1.getHealth() + " " + fighter2.getHealth());
    	while (fighter1.getHealth() > 0 & fighter2.getHealth() > 0) { 	
    	fighter1.attack();
    	fighter2.attack();
    	System.out.println(fighter1.getName() + "'s health is now: " + fighter1.getHealth());
    	System.out.println(fighter2.getName() + "'s health is now: " + fighter2.getHealth());
      }	
    	if (fighter1.getHealth() <= 0){
    	fighter1.die();
    	}
    	else{
    	fighter2.die();
    	}
     }
    }
    "You should not let technology (or method) drive your design, but make your design drive the technology".

    Always learning!


  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Encapsulation (getters and setters) Tips?

    The one glaring remark I have is the lack of comments, in particular Javadoc.

    Some other minor remarks:

    1. In Java the convention is to use camel-case naming convention. Classes begin with upper-case letters, variables and methods begin with lower-case letters.

    2. Some of your tabbing looks off and it makes it harder to read the code. I don't know if that's a copy/paste error or if your code tabbing needs to be fixed.

  3. The Following User Says Thank You to helloworld922 For This Useful Post:

    Robertgif (February 28th, 2013)

  4. #3
    Junior Member Robertgif's Avatar
    Join Date
    Feb 2013
    Posts
    19
    My Mood
    Amazed
    Thanks
    6
    Thanked 1 Time in 1 Post

    Default Re: Encapsulation (getters and setters) Tips?

    I can just go look this up if I have to but I might as well ask, what is Javadoc?

    Is there a general rule of thumb for tabbing?

    Thanks for the advice on the camel-case naming, i'll keep that in mind!

    Thanks so much!
    "You should not let technology (or method) drive your design, but make your design drive the technology".

    Always learning!

  5. #4
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Encapsulation (getters and setters) Tips?

    Javadoc is a way for you to document how a class behaves and how it's suppose to function. There are also some standard tools which can take javadoc and will translate it into a separate API documentation for developers to use. If you've used the Java SE API documentation, this was generated using Javadoc and the standard tools.

    You don't need to use the Javadoc notation, there are other tools available like Doxygen or you can use plain comments, but the idea is you want documentation for how to use a class/method. Here's an article for Oracle which has recommendations and syntaxes for how to write good Javadoc.

    The basic idea is to let developers using the class understand what they can and can't do with a particular class/method. As long as you can get that point across without having to resort to examining the implementation details you've succeeded.

    In general, things I use Javadoc for:
    1. Classes
    2. methods
    3. Public/protected fields
    4. Interfaces
    5. Enums

    Here's an example class with Javadoc and code comments:

    /**
     * A player has a name and some health. When a player's health reaches 0, it is dead.
     * 
     * A player may not have less than 0 health.
     */
    public class Player
    {
    	private String name;
    	private int health;
     
    	/**
    	 * Creates a new player with 100 health and the given name.
    	 * 
    	 * @param name
    	 *            name to give this player
    	 */
    	public Player(String name)
    	{
    		this.name = name;
    		health = 100;
    	}
     
    	/**
    	 * @return the name of this player
    	 */
    	public String getName()
    	{
    		return name;
    	}
     
    	/**
    	 * Changes the name of this player.
    	 * 
    	 * @param name
    	 *            new name for this player
    	 */
    	public void setName(String name)
    	{
    		this.name = name;
    	}
     
    	/**
    	 * @return player's current health
    	 */
    	public int getHealth()
    	{
    		return health;
    	}
     
    	/**
    	 * @param health
    	 *            The value to change the player's health to. If a given value is less than 0, it is
    	 *            clamped to 0.
    	 */
    	public void setHealth(int health)
    	{
    		if (health < 0)
    		{
    			health = 0;
    		}
    		this.health = health;
    	}
     
    	/**
    	 * Have this player fight with another player. Keeps subtracting 1 health from both players until
    	 * at least one player reaches 0 health.
    	 * 
    	 * @param other
    	 *            the player this player is fighting
    	 * @return true if this player lives after the fight
    	 */
    	public boolean fight(Player other)
    	{
    		if (other.health > health)
    		{
    			// we died
    			other.health -= health;
    			health = 0;
    		}
    		else
    		{
    			// we may have not died
    			health -= other.health;
    			other.health = 0;
    		}
    		return health > 0;
    	}
    }

    As far as tabbing goes:

    anytime you have a block statement, the items inside the block should be tabbed in. For example:

    public class Test
    {
    	// class block, tab in
    	private String name;
    	private int id;
     
    	public static void main(String[] args)
    	{
    		// method block, tab in
    		int local = 1;
    		if(local == 1)
    		{
    			// if-statement block, tab in
    			System.out.println("blah");
    		}
    		// not in block anymore, tab back out
    		else
    			// single-line block, wouldn't recommend ever using these, always use curly quotes. But tab these in, too
    			System.out.println("bleh");
    		// end of block, tab back out
    		local = 2;
    		switch(local)
    		{
    		// exception: cases and default statements should not be tabbed in
    		case 1:
    			// but stuff inside them should be
    			System.out.println("hello");
    			break;
    		default:
    			System.out.println("world");
    		}
    	}
    }

  6. The Following User Says Thank You to helloworld922 For This Useful Post:

    Robertgif (February 28th, 2013)

  7. #5
    Junior Member
    Join Date
    Feb 2013
    Location
    Germany
    Posts
    27
    Thanks
    0
    Thanked 5 Times in 5 Posts

    Default Re: Encapsulation (getters and setters) Tips?

    And be careful with encapsualting complex objects. Strings Integer and so are allways new initialized during assignments but check this for instance:

        public static class ExampleEncapsulating{
            private Date date;
     
            public Date getDate() {
                return date;
            }
     
            public void setDate(Date date) {
                this.date = date;
            }
     
        }
     
        public static void main(String[]args){
           Date now = new Date();
           ExampleEncapsulating e = new ExampleEncapsulating();
           e.setDate(now);
           now.setTime(new Date().getTime() - (1000 * 60 * 60 * 24));
           System.out.println(e.getDate());
        }

    There I change the intern behaviour of the object from outside. You can avoid this by making a copy of the parameter in the setter.
    And check allways, which intern vars are considered for being
    final and so setted by constrcutor and without setter, for example the sex

    Also think about writing ReadWrite-interfaces and readonly-interfaces or write a static factory-method where you setting all intern fields

    Good advices are in "Effective Java" from Joshua Bloch

  8. The Following User Says Thank You to janpiel For This Useful Post:

    Robertgif (March 4th, 2013)

Similar Threads

  1. Help with Encapsulation and Value Methods! Please and Thanks!
    By nickjesus3 in forum What's Wrong With My Code?
    Replies: 0
    Last Post: November 10th, 2012, 01:31 AM
  2. Replies: 6
    Last Post: October 31st, 2012, 06:16 AM
  3. Problems with input/output and getters/setters
    By robbiep551 in forum File I/O & Other I/O Streams
    Replies: 6
    Last Post: January 5th, 2012, 11:44 PM
  4. Doubt in Encapsulation concept
    By nareshn in forum Object Oriented Programming
    Replies: 1
    Last Post: January 19th, 2011, 02:20 AM
  5. Encapsulation question regarding ArrayLists
    By LDM91 in forum Collections and Generics
    Replies: 3
    Last Post: October 27th, 2010, 11:51 AM