Service layer for course student registration I have this piece of code in my service layer and registers and student for a course.
As you can see if have alot of if statements and i was wondering if any could suggest a nicer way of writing this code?
    public async Task&lt;bool&gt; RegisterStudentForCourseAsync(RegisterStudentForCourseRequest registerStudent)
    {
        var student = await _studentRepository.GetStudentInformationAsync(registerStudent.StudentId);

        if (student == null)
        {
            throw new StudentCourseRegistrationException(&quot;Student Not Found&quot;);
        }
       
        var alreadyRegistered = student.Enrollments.Any(x =&gt; x.CourseId == registerStudent.CourseId);

        if (alreadyRegistered)
        {
            throw new StudentCourseRegistrationException(&quot;Student is Already Registered for Course&quot;);
        }
       
        //change this to a config setting
        if (student.SubjectCount &gt;= 5)
        {
            throw new StudentCourseRegistrationException(&quot;Cannot Register Amount of Courses&quot;);
        }

        var course = _courseRepository.GetCourseInformation(registerStudent.CourseId);

        if(course == null)
        {
            throw new StudentCourseRegistrationException(&quot;Course Not Found&quot;);
        }
        
        if(course.Enrolled &gt;= course.Capacity)
        {
            throw new StudentCourseRegistrationException(&quot;Course is fully Booked&quot;);
        }

        return await _courseRepository.SaveRegisterationOfStudentForCourse(course, registerStudent, student);
    }
}
you can write fluent extension methods:
 public static class Extensions {
     public static T EnsureNotNull&lt;T&gt;(this T t, string message = null) {
         if (t == null) throw new StudentCourseValidationException(message ?? &quot;Value not found&quot;);
         return t;
     }
     public static Student EnsureAlreadyRegistered(this Student student, string courseId) {
          if (student.Enrollments.Any(x =&gt; x.CourseId == courseId) throw new StudentCourseRegistrationException(&quot;Student is Already Registered for Course&quot;);
          return student;
      }
      //and so on
 }

then your code would look like:
public async Task&lt;bool&gt; RegisterStudentForCourseAsync(RegisterStudentForCourseRequest registerStudent)
    {
        var student = await _studentRepository.GetStudentInformationAsync(registerStudent.StudentId);

        student
              .EnsureNotNull()
              .EnsureNotAlreadyRegistered(registerStudent.CourdeId)
              .EnsureCanHaveMoreCourses();
        
        var course = _courseRepository.GetCourseInformation(registerStudent.CourseId);

        course
             .EnsureNotNull()
             .EnsureNotFullyBooked();

        return await _courseRepository.SaveRegisterationOfStudentForCourse(course, registerStudent, student);
    }
}