This year, I was a senior in computer science. I learned a lot about software development and compiled some small programs. After posting numerous resumes, I finally received an interview notification from an organization. When she arrived at the office, the front-end lady gave him a question, which says, "Please use C ++, Java, C #, or VB. net any object-oriented language to implement a calculator console program, requires two numbers and operator numbers to be entered to obtain the results." It's not easy to look at it. It's less than 10 minutes. It's okay if you finish writing the dishes. After the paper is handed in, the Organization will notify you within one week. Therefore, you have to wait patiently. But half a month has passed, and there is no message. I am wondering why I didn't give me a chance to implement my code. After finding the big bird who has been working for three years and asking why, the big bird asked the question and understood the details of the small food code, and then laughed and said, "You are a little foodie, you have no idea what the unit means. Of course you will not be contacted again ". "Is my code wrong? Isn't the unit question asking me to implement the code of a calculator? What is the problem with this ." Class program {static void main (string [] ARGs) {console. write ("Enter the number A:"); string a = console. readline (); console. write ("select the operator number (+,-, *,/):"); string B = console. readline (); console. write ("Enter the number B:"); string c = console. readline (); string d = ""; If (B = "+") d = convert. tostring (convert. todouble (A) + convert. todouble (c); If (B = "-") d = convert. tostring (convert. todouble (a)-convert. todouble (c); If (B = "*") d = convert. tostring (convert. todouble (a) * convert. todouble (c); If (O = "/") d = convert. tostring (convert. todouble (a)/convert. todouble (c )); Console. writeline ("Result:" + d) ;}} what is the problem with the cakeo code?Code specification and ReconstructionThe Big Bird said: "Without saying what the speaker means, there are many deficiencies in your current code that need to be improved. For example, for variable naming, your name is ABCD, and the variable does not have any specific meaning. This is very nonstandard. The method of determining the branch means that every condition has to be judged, it means that the computer did nothing three times; Data Input validity judgment, etc. What if the user inputs a character symbol rather than a number? What if the customer enters 0 in the divisor? ." "Oh, that's right. I 've heard the teacher say this before, but I never cared about it. I'll change it right away. I'll show it to you later ." Class program {static void main (string [] ARGs) {try {console. write ("Enter the number A:"); string strnumbera = console. readline (); console. write ("select the operator number (+,-, *,/):"); string stroperate = console. readline (); console. write ("Enter the number B:"); string strnumberb = console. readline (); string strresult = ""; Switch (stroperate) {Case "+": strresult = convert. tostring (convert. todouble (strnumbera) + convert. todouble (strnu Mberb); break; Case "-": strresult = convert. tostring (convert. todouble (strnumbera)-convert. todouble (strnumberb); break; Case "*": strresult = convert. tostring (convert. todouble (strnumbera) * convert. todouble (strnumberb); break; Case "/": If (strnumberb! = "0") strresult = convert. tostring (convert. todouble (strnumbera)/convert. todouble (strnumberb); else strresult = "the divisor cannot be 0"; break;} console. writeline ("Result:" + strresult); console. readline ();} catch (exception ex) {console. writeline ("your input is incorrect:" + ex. message) ;}} laruence: "roar, good, good, fast? For the current Code, there is no problem with implementing the calculator, but is the code written in this way consistent with the subject's meaning ?" Side dish: "What do you mean is object-oriented ?" Big Bird: "Ha, it's not a small dish !"Triplicate vs multiplexing"I understand. He said to implement it in any object-oriented language, that means to implement it in an object-oriented programming method, right? OK, I learned this, but I didn't expect it at the time ." Laruence: "All Programming beginners will have this problem, that is, they will intuitively use the logic that computers can understand to describe and express the problem to be solved and the specific process of solving it. This is actually a computer-based approach. For example, the calculator program requires two numbers and operator numbers first, and then determines how to calculate the number based on the operator number, this is not wrong, but this thinking makes our program only to meet the current needs, the program is not easy to maintain, not easy to expand, not easy to reuse. This does not meet the requirements of high-quality code ." Side dish: "I am confused, laruence. How can I make it easy to maintain, expand, and reuse? Can I be specific ?" Laruence: "For example, if I want you to write another Windows Calculator, can your current code be reused ?" "That's not easy. Just copy the code? ." Laruence: "It seems that it is still a small dish. Some people say that the job of junior programmers is Ctrl + C and CTRL + V. This is actually a very bad coding habit, it may be a disaster to maintain your repeated code to a certain extent. The larger the system, the more serious the problem is. The principle of programming is to avoid repetition in the best way possible. Think about it. Which of the code you wrote has nothing to do with the console, but is only related to the calculator ?"4. Business EncapsulationDish: "What do you mean is a classification? Oh, right. Separate computing and display ." Laruence: "To be accurate, it is to separate the business logic from the interface logic and reduce the coupling between them. It is easy to maintain or expand only when points are left ." Dish: "Let me try it ." Class program {static void main (string [] ARGs) {try {console. write ("Enter the number A:"); string strnumbera = console. readline (); console. write ("select the operator number (+,-, *,/):"); string stroperate = console. readline (); console. write ("Enter the number B:"); string strnumberb = console. readline (); string strresult = ""; Strresult = convert. tostring (operation. getresult (convert. todouble (strnumbera), convert. todouble (strnumberb), stroperate )); Console. writeline ("Result:" + strresult ); Console. Readline (); } Catch (exception ex) {console. writeline ("your input is incorrect:" + ex. Message );}}} Public class operation {public static double getresult (double numbera, double numberb, string operate) {double result = 0d; Switch (operate) {Case "+": Result = numbera + numberb; break; Case "-": Result = numbera-numberb; break; Case "*": Result = numbera * numberb; break; Case "/": Result = numbera/numberb; break;} return result ;}} Side dish: "I have written it. You can check it out !" Laruence: "ha, laruence, you can teach me, :). well written. This completely separates the business from the interface ." "You are a bird ." "If you want me to write a calculator for a Windows application, I can reuse the operation class ." Laruence: "It is not just a Windows program. For a web program, you can use it for computation, PDA, mobile phone, or other software that requires a mobile system ." Side dish: "Ha, this is not the case for Object-Oriented. I am not afraid to write similar code ." Laruence: "Don't worry, that's all. It's really not totally object-oriented. You only use one of the three features of object-oriented. Are there two useless features ?" Dish: "isn't the three main characteristics of object-oriented encapsulation, inheritance, and polymorphism? Here I should use encapsulation. Isn't that enough ?............ I can't see how such a small program uses inheritance. As for polymorphism, I have never been quite familiar with its advantages and how to use it ." Laruence: "It's time to learn something. You have to think about it. I'm going to" Warcraft "and talk about it later ."5. Experience the beauty of the simple factory ModelThe next day, I came back to laruence and asked, "Did you say yesterday that small programs like calculators can still use three object-oriented features? I cannot understand how inheritance and polymorphism can be used ." Laruence: "Are dishes very interesting? Well, today I will help you deepen your skills. You should first consider whether the code you wrote yesterday can be modified and expanded flexibly ?" "I have separated my business from the interface. Isn't that flexible ?" Laruence: "How do you change it if I want to add a root (SQRT) operation ?" "You only need to change the operation class. Just add a branch in the switch ." Laruence: "The problem is that you need to add a square root operation, but you need to involve the addition, subtraction, multiplication, division operations in the compilation. If you are not careful, change the addition operation to the subtraction operation, this is not terrible. For example, if the company asks you to maintain the company's salary management system, only technicians (monthly salary) and market sales personnel (base salary + Commission) are allowed ), manager (annual salary + shares) three calculation algorithms, now want to add part-time staff (hourly salary) algorithm, but according to your program yesterday, the company must give you the computing classes of the original three algorithms, so that you can modify them, I am really depressed. This will lead to a chance. So apart from adding a part-time algorithm, you wrote an if statement in the technician's (monthly salary) algorithm) {salary = salary * 1.1 ;} That means that your monthly salary will increase by 10% every month (Be careful when you get caught in jail). It was originally intended to allow you to add a function, but it changed the original code that runs well, this risk is too high. Do you understand ?" "Oh, you mean, I should separate the addition, subtraction, multiplication, division, and other operations. Modifying one of them will not affect the other, and adding an algorithm will not affect other code. Is that true?" Laruence: "Let's go. You should feel how to use inheritance and polymorphism ." Side dish: "OK, I will write it now ." /// <Summary> /// operation class /// </Summary> class operation {private double _ numbera = 0; private double _ numberb = 0; /// <Summary> // number A /// </Summary> Public double numbera {get {return _ numbera;} set {_ numbera = value ;}} /// <Summary> // number B // </Summary> Public double numberb {get {return _ numberb;} set {_ numberb = value ;}} /// <Summary> /// obtain the calculation result /// </Summary> /// <returns> </returns> Public Virtual double getresult () {double result = 0; return result ;}} /// <Summary> /// addition class /// </Summary> class operationadd: Operation {public override double getresult () {double result = 0; result = numbera + numberb; return result ;}/// <summary> // subtraction class /// </Summary> class operationsub: Operation {public override double getresult () {double result = 0; Result = numbera-numberb; return result ;}/// <summary> // multiplication class /// </Summary> class operationmul: Operation {public override double getresult () {double result = 0; Result = numbera * numberb; return result ;}} /// <summary> /// division class /// </Summary> class operationdiv: Operation {public override double getresult () {double result = 0; if (numberb = 0) throw new exception ("the divisor cannot be 0. "); Result = numbera/numberb; return result ;}}" laruence, I wrote a part of it according to your method. The first is an operation class, it has two number attributes, which are mainly used for the front and back numbers of the calculator. Then there is a virtual method getresult () to get the result. Then I wrote the addition, subtraction, multiplication, division, and subclass of the operation class, after it is inherited, The getresult () method is rewritten, so that if you want to modify any algorithm, you do not need to provide code for other algorithms. But the question is, how can I let the calculator know which algorithm I want to use ?" Laruence: "Is it well written? It's much more than I imagined. Your problem is actually how to instantiate an object. Ha, I'm in a good mood today, let's take a look at the 'simple factory mode'. That is to say, it is easy to change whether or not the instantiated objects (such as the root operation) will be added in the future, we should consider using a separate class to create an instance. This is the factory. Let's look at how to write this class." /// <Summary> /// operation class factory /// </Summary> class operationfactory {public static operation createoperate (string operate) {operation condition = NULL; Switch (operate) {Case "+": {condition = new operationadd (); break;} case "-": {condition = new operationsub (); break;} case "*": {scheme = new operationmul (); break;} case "/": {scheme = new operationdiv (); break ;}} return comment ;}} Big Bird: "ha, see this. You only need to enter the operator number, and the factory will The instance generates the appropriate object and returns the result of the calculator through polymorphism in the form of the parent class ." Operation condition; condition = operationfactory. createoperate ("+"); condition. numbera = 1; condition. numberb = 2; double result = condition. getresult (); Big Bird: "Ha, the implementation of the interface is such code, whether you are a console program, Windows program, web program, PDA or mobile phone program, you can use this code to implement the calculator function. When one day we need to change the addition operation, where do we only need to change it?" Dish: "Change operationadd ." Laruence: "So we need to add a variety of complex operations, such as square root, cube root, natural logarithm, and sine cosine. How can we do this ?" Dish: "You only need to add the corresponding operation subclass ." Laruence: "Well? Is that enough ?" "By the way, you still need to modify the computing factory and add branches in the switch ." Laruence: "ha, that's right. What if I want to modify the interface ?" Food: "Let's change the interface. It's about computing ." "Back to the code I wrote in my interview questions that day, I finally understood why I failed to write the code. It turned out that a small calculator could write such a wonderful code. Thank you, laruence ." Laruence: "Hey, remember, programming is a technology and an art. You can't just finish the work after writing the code and running the results correctly. You often think about how to make the code more concise, it is easier to maintain, expand, and reuse. Only in this way can it be truly improved. Writing elegant code is really a great thing. But there is no end to learning. In fact, this is the beginning of understanding object-oriented. I will give you a assignment and create a cash register software for the mall. The salesperson will charge the customer based on the unit price and quantity of the purchased goods ." "That's it? No problem ." |