Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Doing practise questions for a Java exam which have no answers (useful) I have been asked to do the following:

Write a class called Person with the following features:

  • a private int called age;
  • a private String called name;
  • a constructor with a String argument, which initialises name to the received value and age to 0;
  • a public method toString(boolean full). If full is true, then the method returns a string consisting of the person’s name followed by their age in brackets; if full is false, the method returns a string consisting of just the name. For example, a returned string could be Sue (21) or Sue;
  • a public method incrementAge(), which increments age and returns the new age;
  • a public method canVote() which returns true if age is 18 or more and false otherwise.

My code is as follows can someone point out any errors?

public class Person
{
    private int age;
    private String name;

    public Person(String st)
    {
      name = st;
      age = 0;
    }

   public String toString(boolean full)
   {
     if(full == true)
     {
        return name + "(" + age + ")";
     }
     else
     {
        return name;
     }
   }

   public int incrementAge()
   {
      age++;
      return age;
   }

   public boolean canVote()
   {
     if(age >= 18)
     {
        return true;
     }
     else
     {
        return false;
     }
   }
}
share|improve this question

migrated from stackoverflow.com Sep 23 '11 at 23:06

This question came from our site for professional and enthusiast programmers.

    
I don't see any errors :) –  Cata May 30 '11 at 14:27

14 Answers 14

up vote 12 down vote accepted

instead of

if(full == true)

use

if (full)

and instead of

if(age >= 18)
{
   return true;
}
else
{
   return false;
}

use:

return age >= 18
share|improve this answer
    
Thank you both for your answers, just wee small minor things i need to keep an eye on then. –  user445714 May 30 '11 at 14:31

That's fine, but I would have written the last method as return (age >= 18);

share|improve this answer
 return name + "(" + age + ")";

to

return name + " (" + age + ")";
share|improve this answer
    
+1: Improve spacing is good. –  Peter Lawrey May 30 '11 at 14:31

I don't think it's a good idea to write toString method with arguments - doing so you will not override the default Object.toString and will have no benefits from using it outside your code. For example, when outputting elements of a collection which contain Person won't display neither age nor name, but something like Person@a3f33f (default implementation). At least provide toString with no arguments as well

share|improve this answer
    
Denisk that actually moves onto my next question, Does the Person class overload or override any methods? Briefly explain your answer. –  user445714 May 30 '11 at 14:34
    
I was going with override until i seen your comment and would go with overload the Object.toString? –  user445714 May 30 '11 at 14:35
    
Currently you have toString method overloaded - thus, you actually have 2 toString methods - one inherited from Object (default no-arg method), and one with boolean argument. If you declared your toString with no arguments it would override Object.toString, and you would end up with 1 toString method (which, as I have mentioned, can be widely used by many things outside your own code) –  denisk May 30 '11 at 14:38
    
I agree with denisk, and want to point out that flags like full in method arguments are a code smell: A method should do one and only one thing (Single Responsibility Principle), and a method with a flag does at least two things. Uncle Bob agrees as well (Clean Code: amazon.de/Clean-Code-Handbook-Software-Craftsmanship/dp/… ) –  Landei Mar 3 '12 at 13:44
    
The toString(boolean) method is part of the assignment requirements. But normally, this is good advice. –  Eva Jan 16 '13 at 12:04

In addition to the other comments, on your constructor, having an argument called "st" isn't particularly useful to the reader as it doesn't tell them what it's for. From a code style perspective might be better to have an argument called name, and explicitly set this.name = name in the body.

share|improve this answer
1  
To add on, at this moment of learning it may seem not to matter, but when you're developing, these little things that make the usage more intuitive (especially when you're using auto-completion) will reduce your (and others') pain. –  blizpasta May 30 '11 at 14:44

Your code is almost fine. I would change two things:

The following is a little shorter :)

public boolean canVote()
{
    return age >= 18;
}

Your toString(true) would return "Sue(21)" rather than the "Sue (21)" (with space) which is asked for. My toString would look like this:

public String toString(boolean full)
{
    String str = name;
    if(full) {
       str += " (" + age + ")";
    }

    return str;     
 }
share|improve this answer

If the age is implemented as a primitive integer there is no need to initialize it to 0 because all primitive number instance variables are initialized to 0 by default. Anyway if you had used a wrapper instead (Integer) the initialization to 0 is required.

Take a look at the "Default Values" section:

http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

share|improve this answer

This is also less verbose

public int incrementAge() {
  return ++age;
}
share|improve this answer
    
I worry that a student might be docked points for readability if they put that answer. Otherwise, I would write it like that too. –  Eva Jan 16 '13 at 12:07

How about adding a constant for 18, say MIN_AGE_TO_VOTE?

And:

return name + (full ? " (" + age + ")" : "");

Less readable, I agree :-)

share|improve this answer
1  
+1 for only the constant. (I agree, the ternary operator is not too readable and harder to maintain.) –  palacsint Jul 7 '12 at 15:56

Use String.format instead of string concatenation:
return name + "(" + age + ")"; becomes

return String.format("%s (%s)", name, age);
share|improve this answer
    
It's a Java question ;) –  palacsint Jul 7 '12 at 22:09
    
ouch. thanks for pointing that out.. –  codesparkle Jul 7 '12 at 22:11
  1. The name field could be final. Making a variable final relieves the programmer of excess mental juggling - he/she doesn't have to scan through the code to see if the variable has changed. (From @nerdytenor's answers.)

  2. You should check the argument in the constructor. Does it make sense to create a Person object with a name which is null or an empty String? If not, check it and throw a NullPointerException or an IllegalArgumentException. (Effective Java, Second Edition, Item 38: Check parameters for validity)

  3. A note about the specification:

    Flag arguments are ugly. Passing a boolean into a function is a truly terrible practice. It immediately complicates the signature of the method, loudly proclaiming that this function does more than one thing. It does one thing if the flag is true and another if the flag is false!

    Source: Clean Code by Robert C. Martin, Chapter 3: Functions.

    This should be two methods: toString() and toFullString(), for example, without any parameter.

share|improve this answer

Looks fine, only canVote is maybe a bit clumsy:

   public boolean canVote()
   {
        return age >= 18;
   }
share|improve this answer

I would see if you can make the code less verbose.

public boolean canVote() {
    return age >= 18;
}
share|improve this answer

My version of Person class would be,

public class Person
{
private int age;
private String name;

public Person(String st)
{
  this.name = st;
  this.age = 0;
}
public String toString(boolean full)
{
     return full?name + "(" + this.age + ")":name;
}

public int incrementAge()
{
   return ++this.age;
}

public boolean canVote()
{
    return (this.age >= 18); 
}
}
share|improve this answer
1  
No StringBuilder in the toString method? –  Gilbert Le Blanc Jul 6 '12 at 16:21

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.