4.8. Exercises

  1. Given a class Book defined as having the following fields:

    Author author;
    
    string title;
    
    int noOfPages;
    
    bool fiction;

    Write a set of properties for these fields with simple, one-line get and set accessors.

    What would the recommended headers be if we were to write "get" and "set" methods for all of these fields?

  2. It's often possible to discern something about a class's design based on the method calls on objects in client code. Consider the following client code "snippet:"

    Student s;
    Professor p;
    bool b;
    string x = "Math";
    
    s.Major = x;
    if (!s.HasAdvisor())
    
        b = s.DesignateAdvisor(p);

    What members—fields, methods, properties—are implied for the Student and Professor classes by virtue of how this client code is structured? Be as specific as possible with respect to the following:

    • The accessibility of each member

    • How each member would be declared; for example, the details (to the extent that you can "discover" them) of a method or property's header

  3. What's wrong with the following code? Point out things that go against OO convention based on what you've learned in this chapter, regardless of whether or not the C# compiler would "complain" about them.

    First, an example using "get"/"set" methods:

    public class Building
    {
      private string address;
      public int numberOfFloors;
    
      void GetnumberOfFloors() {
        return numberOfFloors;
      }
    
      private void SetNoOfFloors(float n) {
        NumberOfFloors = n;
      }
    }

    Next, an example using properties:

    public class Building
    {
      private string address;
      public int numberOfFloors
    
      public long NumberOfFloors {
        int get {

    return numberOfFloors;
        }
        private set {
          numberOfFloors = value;
        }
      }
    }

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset