有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java这段代码是如何违反德米特定律的?

下面的代码将Law of Demeter分隔开:

public class Student extends Person {
  private Grades grades;

  public Student() {
  }

  /** Must never return null; throw an appropriately named exception, instead. */
  private synchronized Grades getGrades() throws GradesException {
    if( this.grades == null ) {
      this.grades = createGrades();
    }

    return this.grades;
  }

  /** Create a new instance of grades for this student. */
  protected Grades createGrades() throws GradesException {
    // Reads the grades from the database, if needed.
    //
    return new Grades();
  }

  /** Answers if this student was graded by a teacher with the given name. */
  public boolean isTeacher( int year, String name ) throws GradesException, TeacherException {
    // The method only knows about Teacher instances.
    //
    return getTeacher( year ).nameEquals( name );
  }

  private Grades getGradesForYear( int year ) throws GradesException {
    // The method only knows about Grades instances.
    //
    return getGrades().getForYear( year );
  }

  private Teacher getTeacher( int year ) throws GradesException, TeacherException {
    // This method knows about Grades and Teacher instances. A mistake?
    //
    return getGradesForYear( year ).getTeacher();
  }
}

public class Teacher extends Person {
  public Teacher() {
  }

  /**
   * This method will take into consideration first name,
   * last name, middle initial, case sensitivity, and
   * eventually it could answer true to wild cards and
   * regular expressions.
   */
  public boolean nameEquals( String name ) {
    return getName().equalsIgnoreCase( name );
  }

  /** Never returns null. */
  private synchronized String getName() {
    if( this.name == null ) {
      this.name == "";
    }

    return this.name;
  }
}

问题

  1. LoD是如何被打破的
  2. 破解LoD的密码在哪里
  3. 如何编写代码来维护LoD

共 (3) 个答案

  1. # 1 楼答案

    我认为有两个问题:

    1. Grades逻辑与Student混合太多。它应该在Grades类中完成
    2. Teacher的逻辑被放入Student

    结论:学生对老师和成绩的内部结构和逻辑了解太多,这打破了LoD

  2. # 2 楼答案

    大多数这样的问题都可以通过重新访问域模型来解决

    看起来这个学生的责任比应该的要大得多。它应该只有一个改变的理由

    我会通过添加一个ReportCard对象来重构它

    public class ReportCard
    {
      public Student Student...
      public int Year...
      public ReportCardItem[] ReportCardItems...
    
      getGrades()...
      createGrades()...
    }
    
    public class ReportCardItem
    {
      public Grade Grade...
      public string Subject...
      public Teacher Teacher...
    }
    
  3. # 3 楼答案

    根据你提到的维基百科文章,“通过”到达

    我惊讶地发现成绩表是这个学生的财产。这不应该是学校了解和管理的事情吗?我会问学校,哪位老师在哪一年给学生打分