classobjectoopmethodslow-level-api

I have Customer class and Order class. Where should I write a method to find the number of orders placed by a customer


This question was asked in an interview round to my friend. As I am going to give the same interview, so was preparing it.

I have a Customer class and Order class. Q1)Where should I write a method to find the number of orders placed by a customer. Q2)Where should I write a method to find the number of customers who have given more than 5 orders.


Solution

  • Q1) Customer class. It involves a single customer, so a single instance is involved. Often such a class would maintain a list of orders anyway.

    Q2) Think outside the box. I'd put the method outside of customers and outside of orders, but it would of course have to query whatever classes are managing all the customers. In the simplest case it would build up a list as it queries each customer instance as to how many orders it contains.

    There are many variations of this (such as caching and maintaining running totals), depending on goals and constraints such as efficiency or timeliness of response, and if you give a simple answer you should qualify it with that point.

    For example, if 5 orders is a level where extra benefits kick in, then it should be tracked by the customer object as each order is placed, and some other class notified when the threshold is crossed.

    On the other hand, if this is a data analysis query, then it would proceed more as I give in the first simple answer to Q2, because the actual number would vary with different queries. Someone might be analyzing to see what level should they set for the extra benefits.

    Much depends on goals and constraints, and by making that point you show the interviewer that you have an analytical mind that is not confined to a single perspective.

    Often interview questions are not about "can the person find the answer" but are about "how does this person approach finding the answers to tricky problems". Do they gather more information? Are they conscious of what issues are involved? A question such as Q2 is a trick in a way because both questions gently guide the interviewee to think "which of the two" rather than a wider scope including some as yet unmentioned third class.

    Good luck and welcome to the Stacks.