gpt4 book ai didi

java - 这段代码如何违反 Demeter 法则?

转载 作者:搜寻专家 更新时间:2023-11-01 01:58:26 26 4
gpt4 key购买 nike

以下代码打破了 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?

最佳答案

我认为这里有两个问题:

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

结论:Student对Teacher和Grades的内部结构和逻辑了解太多,破坏了LoD

关于java - 这段代码如何违反 Demeter 法则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2609236/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com