Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
C#
public class MyCalender
{

private String[] weekdays =
{ "Sun", "Mon", "Tue", "Thu", "Fri", "Sat", "Sun" };

public String[] getWeekdays()
{
return weekdays;
}
}
Posted
Comments
Philippe Mori 22-Jan-13 18:46pm    
You should tag with the proper language. And it look like an homework too...

By returning the private String[] object through the public method you are also giving the outside world read/write access to the contents of the object.
To satisfy the concept you would need to do it this way:
C++
public class MyCalendar
{
   private String[] weekdays = 
      { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };

   public const String[] getWeekdays()
   {
      return weekdays;
   }
}

Now you are allowing the outside world to read the Days of the Week, but now the outside world cannot change the contents of the object.
 
Share this answer
 
Comments
Anderso0on 22-Jan-13 14:32pm    
const what do here ??
Jibesh 22-Jan-13 15:49pm    
check the last line of the solution. it explains what const will do.
'the outside world cannot change the contents of the object'
fjdiewornncalwe 22-Jan-13 17:00pm    
Thanks, jibesh.
Sergey Alexandrovich Kryukov 22-Jan-13 14:37pm    
Right, a 5. A very good approach would be an index operator used to return an array element.
—SA
fjdiewornncalwe 22-Jan-13 17:00pm    
very true.
I am not sure... I see C++ on the top... the sample looks like java... and using const String[]? Isn't final the keyword in java?

In any case, there are really some problems.
1 - Returning the array simple let users to change the items in the array.
2 - Even if you can return a constant array, that will be showing the real type of the array and in many situations it is exactly that what you should avoid. In fact, we know week days don't change, but imagine that you want to change from an array to a list, what will you do with the method? Will you change the return type?

Conclusion: You should not return an array, you should return something that does not compromises the internal representation. You could do it by:
1 - Creating a getCount method and a getWeekDayName, which receives the day by index and returns the String representing it;
2 - By returning some kind of unchangeable collection that can point to an array, list or other.

In any case, you must also take care not to allow users to change the values.
 
Share this answer
 
Comments
Philippe Mori 22-Jan-13 18:45pm    
The code is in C# (even though the OP has tagged it as C++) but your points are good.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900