Small dish programming growth record (an interview frustrate code without fault is good?)

  • 2020-05-05 11:44:39
  • OfStack

Small vegetables this year computer major big four, learned a lot of software development aspects of things, also learn to make up a small program, complacent, heart to find a good unit. After sending out countless resumes, he finally received an interview notice from an organization.
When             arrived at the house, the receptionist gave him a title, which said, "please use C++, Java, C# or VB.NET any object-oriented language to implement a calculator console program, requires the input of two Numbers and operation symbols, the result.
                After handing in the paper, the unit said a week to wait for notice. So the dishes had to wait patiently. But half a month passed, no news, small vegetables very wonder, my code implemented ah, why not give me a chance.
                xiaoge found a job for three years, ask the reason, the big bird asked the question and understand the details of the xiaoge code, laughed, said: "xiaocai xiaocai, you were cheated, the meaning of the unit, you do not understand, of course will not contact you."
                says, "is there anything wrong with my code? The unit problem is that they want me to implement the code for a calculator.

class Program 
{ 
    static void Main(string[] args) 
    { 
        Console.Write(" Please enter a number A : "); 
        string A = Console.ReadLine(); 
        Console.Write(" Please select operation symbol (+ , - , * , /) : "); 
        string B = Console.ReadLine(); 
        Console.Write(" Please enter a 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(" The result is: " + D); 
    }      
}

What's wrong with the code for the dish?
ii   code specification, refactoring

Big bird said: "and leave aside the meaning of the author, just your current code, there are a lot of shortcomings need to be improved. For example, variable naming, your name is ABCD, variables do not have any specific meaning, which is very irregular; The judgment branch, the way you write it, means that every condition has to be judged, which is equivalent to the computer doing three useless tasks; Data entry validity, etc. What if the user enters a character symbol instead of a number? What if the customer enters a 0 when divisor occurs? These are all areas for improvement."

"Oh, that's right, I've heard the teacher say this before, but I've never paid any attention to it.

class Program 
{ 
static void Main(string[] args) 
{ 
try 
{ 
Console.Write(" Please enter a number A : "); 
string strNumberA = Console.ReadLine(); 
Console.Write(" Please select operation symbol (+ , - , * , /) : "); 
string strOperate = Console.ReadLine(); 
Console.Write(" Please enter a number B : "); 
string strNumberB = Console.ReadLine(); 
string strResult = ""; 

switch (strOperate) 
{ 
case "+": 
strResult = Convert.ToString(Convert.ToDouble(strNumberA) + Convert.ToDouble(strNumberB)); 
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 zero 0"; 
break; 
} 

Console.WriteLine(" The result is: " + strResult); 

Console.ReadLine(); 


} 
catch (Exception ex) 
{ 
Console.WriteLine(" Your input is wrong: " + ex.Message); 
} 
} 
} 


Big bird: "roar roar, good, good, change quickly? So far as the code is concerned, there is no problem to implement the calculator, but does the code written like this match the author's meaning?"

Side dish: "you mean object-oriented?"

Big bird: "ha, small vegetables not small vegetables also!"

three copy VS multiplexes

Small dish: "I see, he said to implement in any object-oriented language, that means to use object-oriented programming method to implement, right? OK, I learned that, but I didn't think of it at the time."

Big bird: "any beginner programmer has the problem of intuitively describing and expressing the problem and the solution in terms of logic that a computer can understand. The way it is to use the computer to think, calculator - this program, for example, to ask for two Numbers and arithmetic symbols first, and then choose how to operation, according to operational sign judgment results, this itself is not wrong, but that thinking makes our program just for meet the needs of implementation of the current program is not easy to maintain, not easy to expand, more is not easy to reuse. It doesn't meet the requirements of high quality code."

Small dish: "bird elder brother ah, I am a bit confused, how ability easy maintenance, easy extension, easy reuse again, can you be specific?"

Big bird: "for example, I now ask you to write another windows calculator, can your current code reuse?"

Small dish: "that return not simple, copy code past not line? It's not too much trouble."

Big bird: "small vegetables or small vegetables. Some people say that the job of a beginner programmer is Ctrl+C and Ctrl+V. The bigger the system, the more problematic this approach is, and one of the rules of programming is to avoid duplication as much as possible. Think about it. What part of the code you wrote is not related to the console, but to the calculator?"

four-service package

Small dish: "you mean cent a kind come out? Oh yes, separate the calculation from the display."

Big bird: "to be precise, it's to separate the business logic from the interface logic, to de-couple them. It is easy to achieve and easy to maintain or expand only when separated."

Side dish: "let me try."

class Program 
{ 
static void Main(string[] args) 
{ 
try 
{ 
Console.Write(" Please enter a number A : "); 
string strNumberA = Console.ReadLine(); 
Console.Write(" Please select operation symbol (+ , - , * , /) : "); 
string strOperate = Console.ReadLine(); 
Console.Write(" Please enter a number B : "); 
string strNumberB = Console.ReadLine(); 
string strResult = ""; 

strResult = Convert.ToString(Operation.GetResult(Convert.ToDouble(strNumberA),Convert.ToDouble(strNumberB),strOperate)); 

Console.WriteLine(" The result is: " + strResult); 

Console.ReadLine(); 

} 
catch (Exception ex) 
{ 
Console.WriteLine(" Your input is wrong: " + 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; 
} 
} 


Small dish: "bird elder brother, I wrote good, you see!"

Big bird: "ha, small bird can teach also, :), write good, so completely separated business and interface."

Small dish heart dark scold: "you are a bird." "If you asked me to write a calculator for the Windows application now, I could reuse this class," says  .

Big bird: "not only is Windows program, Web version of the program needs to calculate can use it, PDA, mobile phone and other need to mobile system software needs to calculate can also use it."

Side dish: "ha, object-oriented just so. I'm not afraid to write similar code next time."

Big bird: "don't worry, that's all, really not completely object-oriented, you only used object-oriented one of the three features, still two useless?"

"The three main features of object orientation are encapsulation, inheritance and polymorphism. Isn't that enough? ..................... I really don't see how such a small program can use inheritance. As for polymorphism, I never really knew what it was good for or how to use it."

Big bird: "slowly, some things are easy to learn, you think it over, I want to go to" warcraft ", change the time to chat.

Experience the beauty of a simple factory model
The next day, kochi came back to big bird and asked, "did you say yesterday that a small program like a calculator could still use three object-oriented features? How inheritance and polymorphism might come into play is beyond me."

Big bird: "side dish very have study spirit? Well, today I'll give you a boost. The first thing you need to consider is whether the code you wrote yesterday is flexible enough to be modified and extended."

Small dish: "I already separated business and interface, this isn't very agile?"

Big bird: "so let me ask you, now if I want to add an sqrt operation, how do you change it?"

Side dish: "that just needs to change Operation class line, add a branch in switch line."

Big bird: "the problem is you have to add a square root, but you have to add, subtract, multiply and divide to compile. If you're not careful and you change the addition to subtract, it's not too bad. Now, for example, if the company asks you to do for the company's salary management system maintenance, originally only technicians (monthly), market sales staff (basic salary + commission), manager (salary +) three operation algorithm, now to increase the part-time staff (hourly) algorithm, but writing in accordance with the procedure you yesterday, the company will have to be to contain some of the original three algorithms computing class for you, let you change, if you plan a dozen in the heart, 'TMD, company gave me such a low salary, I'm really depressed, it will have the opportunity to', so you in addition to increased part-time algorithm, Write  
in the technician (monthly salary) algorithm

if ( Employees are a side dish ) 
{ 
salary = salary * 1.1; 
} 

That means you'll get a 10% increase in your monthly salary (beware of getting caught in jail), and it's too risky to add a feature that makes a difference to the code that already works. Do you understand?"

"Oh, you mean that I should separate the addition, subtraction, multiplication and division operations, and modify one of them without affecting the others, and add algorithms without affecting the other code, is that right?

Big bird: "oneself want to go, how to use inheritance and polymorphic, you should have feeling."

Side dish: "OK, I write right away."

/// <summary> 
///  Operation class  
/// </summary> 
class Operation 
{ 
private double _numberA = 0; 
private double _numberB = 0; 

/// <summary> 
///  digital A 
/// </summary> 
public double NumberA 
{ 
get{ return _numberA; } 
set{ _numberA = value;} 
} 

/// <summary> 
///  digital B 
/// </summary> 
public double NumberB 
{ 
get{ return _numberB; } 
set{ _numberB = value; } 
} 

/// <summary> 
///  Get the result  
/// </summary> 
/// <returns></returns> 
public virtual double GetResult() 
{ 
double result = 0;  
return result; 
} 
} 


/// <summary> 
///  Add 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> 
///  Divide the class  
/// </summary> 
class OperationDiv : Operation 
{ 
public override double GetResult() 
{ 
double result = 0; 
if (NumberB==0) 
throw new Exception(" The divisor cannot be zero 0 . "); 
result = NumberA / NumberB; 
return result; 
} 
} 

Dishes: "the elder brother of the big birds, according to the way you said I write out a part of the first is an operations class, it has two Number properties, mainly used for calculators and number, and then there is a virtual method GetResult (), is used to get the results, then I have written the addition, subtraction, multiplication, and division operations class subclass, inheriting it, rewrite the GetResult () method, so if you want to modify any of the algorithm, do not need to provide other code of the algorithm. But the question is, how do I let the calculator know which algorithm I want to use?"

Big bird, "writes very good, well beyond my imagination, your problem now is the problem of how to instantiate the object, ha, today the mood is good, teach you a recruit again 'simple factory pattern", that is to say, who the hell to instantiate, will increase the instantiated object (such as increasing the operation of open), and this is the place where it is easy to change, should consider using a single class to do this the process of creating an instance, this is the factory, come, let's take a look at this class how to write."

/// <summary> 
///  Arithmetic factory  
/// </summary> 
class OperationFactory 
{ 
public static Operation createOperate(string operate) 
{ 
Operation oper = null; 
switch (operate) 
{ 
case "+": 
{ 
oper = new OperationAdd(); 
break; 
} 
case "-": 
{ 
oper = new OperationSub(); 
break; 
} 
case "*": 
{ 
oper = new OperationMul(); 
break; 
} 
case "/": 
{ 
oper = new OperationDiv(); 
break; 
} 
} 

return oper; 
} 
} 

Big bird: "ha, see, this way, you just need to enter the operation symbol, the factory will instantiate the appropriate object, through polymorphism, return the parent class way to achieve the result of the calculator."

Operation oper; 
oper = OperationFactory.createOperate("+"); 
oper.NumberA = 1; 
oper.NumberB = 2; 
double result = oper.GetResult(); 

"Ha, interface implementation is such a code, whether you are a console program, Windows program, Web program, PDA program, PDA or mobile phone program, you can use this code to achieve the function of the calculator, when one day we need to change the addition operation, we just need to change where?

Side dish: "change OperationAdd   ok."

Big bird:   "so we need to add all kinds of complicated operations, such as square roots, cube roots, natural logarithms, sines and cosines, etc. How to do?"

Small dish: "as long as add corresponding computation subclass ok."

Big bird:   "huh? Is that enough?"

Side dish: "by the way, we still need to modify the arithmetic factory and add branches in switch."

Big bird:   "ah, that's right, but what if I have to change the interface?"

Small dish: "that go to change interface ah, concern computation what matter ah."

Side dish: "  think back to the code that I wrote in the interview that day, I finally understand why I did not write successfully, originally a small calculator also can write so wonderful code, thank big bird."

Remember that programming is more of an art than a skill. You can't just write code and get it right. Always consider how to make your code simpler, easier to maintain, easier to extend, and easier to reuse. Writing elegant code is a pleasure. But there's no end to learning, and that's really the beginning of understanding object orientation. Give you a homework, do a shopping mall cashier software, sales staff according to the customer to buy goods unit price and quantity, to the customer charge.

Side dish: "this? No problem."

Related articles: