Team LiB
Previous Section Next Section

Exercises

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

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

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

    What would the recommended headers be if we were to write "get" and "set" methods, rather than properties, for all of these attributes?

  2. It's often possible to discern something about a class's design based on the messages that are getting passed to 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 features—attributes, 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 accessibility of each feature

    • How each feature would be declared: e.g., 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;
        }
      }
    }
    

Team LiB
Previous Section Next Section