这段代码违反了OOP封装概念,为什么? [英] this code is violate OOP encapsulation concept, WHY ?

查看:95
本文介绍了这段代码违反了OOP封装概念,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public   class  MyCalender 
{

private 字符串 [] weekdays =
{ Sun 星期一 星期二 Thu Fri Sat Sun};

public String [] getWeekdays()
{
返回工作日;
}
}

解决方案

通过公共方法返回私有String []对象,你也给出了外部世界对对象内容的读/写访问权。

为了满足这个概念,你需要这样做:

  public   class  MyCalendar 
{
private 字符串 [] weekdays =
{ Sun Mon Tue Wed Thu Fri Sat 太阳};

public const String [] getWeekdays()
{
return 工作日;
}
}



现在你允许外面的世界阅读星期几,但现在外界无法改变内容对象。


我不确定...我在顶部看到C ++ ......示例看起来像java ...并使用const String []?在java中不是最终的关键字吗?



无论如何,确实存在一些问题。

1 - 返回数组简单让用户更改数组中的项目。

2 - 即使你可以返回一个常量数组,这将显示数组的真实类型,在许多情况下,它正是你应该的避免。事实上,我们知道工作日不会改变,但想象你想要从数组更改为列表,你将如何处理这个方法?你会改变返回类型吗?



结论:你不应该返回一个数组,你应该返回一些不会影响内部表示的东西。您可以通过以下方式完成:

1 - 创建一个getCount方法和一个getWeekDayName,它按索引接收日期并返回表示它的String;

2 - 返回一些一种不可更改的集合,可以指向数组,列表或其他。



在任何情况下,您还必须注意不要让用户更改值。

public class MyCalender
{

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

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

解决方案

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:

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.


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.


这篇关于这段代码违反了OOP封装概念,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆