Object-oriented Thinking

Source: Internet
Author: User
Tags qmail

For example, to send an ad mail, the ad mail list is stored in the database. If you use C for writing, you will generally think like this. Read the mail content first, connect to the database, fetch the mail address cyclically, and call the sendmail command of Qmail on the local machine to send the mail.

Then we consider using Java for implementation. Since it is Oop, no code can be inserted into the main process, so we designed three classes:

One class is responsible for reading the database, obtaining the mail address, and calling the sendmail command of Qmail to send;

One class is to read the mail content, MIME encoded into HTML format, plus the mail header;

A main class reads parameters from the command, processes the command line parameters, and calls the e-mail class.

Divide a task into three modules for processing, and each class completes a module task.

After careful analysis, we will find that such a design is completely designed from the programmer's perspective of implementing program functions, or that the design class is self-improving, from the machine perspective to the real world perspective. Therefore, at the design stage, we have taken into account all the details of program programming implementation, and attempted to meet the real-world software requirements from the starting point of the underlying implementation program.

This analysis method is actually not applicable to object-oriented programming languages such as Java, because if you use C language instead and encapsulate two C functions, it will be much easier to implement than Java, logic is also clear.

I think the essence of Object-oriented thinking lies in the thinking of the problem starting from the human thinking habits in the real world. Once we understand this, we understand the object-oriented thinking methods.

For example, if you need to write a Web page counter and the customer visits the page once, the web page counter is incremented by 1, and the counter is accessed through http: // hostname/count. CGI? Id = xxx

There is a database table in the background that stores the current counter value for each ID (an ID corresponds to a page for statistics on the number of visits) and requests the page once, add 1 to the counter field corresponding to the ID (Here we ignore the problem of table locking when updating database tables concurrently ).

If we analyze it from the perspective of program implementation, we will consider this: first, we GET the id from the http get request, and then query the database table by id, obtain the access Count value corresponding to an id, add 1, update the database, and display the access count to the page.

Now let's assume that a person without programming experience will think about this problem? What kind of requirements does he propose? He may think like this:

I need a counter. This counter should have such a function. If you refresh the page once, the traffic will increase by 1. In addition, it is better to have a counter to be cleared by 0, of course, if a counter can be set to any value, I will be able to cheat.

As a person without experience in programming, he would not think of how to operate the database or how to transmit HTTP variables. What is the requirement of the database, what is my business logic and what functions should the software have.

According to this idea (please note that his idea is actually the way of thinking we are used to in our daily life), we know that we need a Counter, there is a required and two optional methods:

Getcount ()
// Method for getting counter value
Resetcounter ()
// Counter clearing 0 Method
Setcount ()
// Set the counter as the corresponding value method

The complete counter class is defined as follows:

Public class Counter
{
Public int getCount (int id)
{
}
Public void resetCounter (int id)
{
}
Public void setCount
(Int id, int currentCount)
{
}
}

The problem-solving framework already exists. Let's take a look at how to use Counter. In count. cgi, Counter is called to count. The program segment is as follows:

// Obtain the id value from the HTTP Environment
...
Counter myCounter = new Counter ();
// Obtain the counter
Int currentCount = myCounter. getCount (id );
// Retrieve the count from the counter
// Output to the client browser
...

The framework of the program is all written, and the rest is to implement the specific code in the Counter class method. At this time, we should consider the details of the specific program language implementation, for example, in getCount () method to access the database and update the Count value.

From the examples above, we can see that the object-oriented thinking method is actually the way of thinking we are used to in real life. It is from the perspective of human consideration, the process of translating human thinking for solving problems into a way of thinking that can be understood by the program. In this process, the software is gradually designed.

In the process of using object-oriented thinking methods for software design, the most common mistake is to start the analysis and think about the details of program code implementation, therefore, the encapsulated class is based entirely on the program implementation logic, rather than the problem-solving business logic.

The classic error method for learning JDBC programming is: "How do I encapsulate select operations on the database ?"

The object-oriented design is based on the design to solve business problems, rather than the design based on specific programming technologies. I will not encapsulate the select statement. I only encapsulate the business logic that solves the problem, and read the database is considered in the coding implementation phase of the business logic.

Looking back at the example of the advertisement email above, how should we apply the object-oriented thinking method?

For an email, there are three attributes: the mail header, the mail body, and the mail address. to send an email, you need to send the email using a method, you also need a method to list all email addresses. Therefore, the following design should be performed:

JunkMail

Attribute:

head
body
address

Method:

SendMail ()
// Send an email
ListAllMail ()
// Column email address

In Java:

Public class JunkMail
{
Private String head;
Private String body;
Private String address;
Public JunkMain ()
{
// Default class Constructor
// Read the email header and body from the external configuration file
This. head = ...;
This. body = ...;
}

Public static boolean
SendMail (String address)
{
// Call qmail and send an email
}

Public static Collection listAllMail ()
{
// Access the database and return an email address set
}
}

After JunkMail is designed, it is very easy to call the JunkMail class to send emails.

If the traditional process-oriented programming is a process that conforms to the instructions for running machines, the object-oriented thinking method is a thought process that conforms to human problems in real life.

When analyzing and designing object-oriented software, remind yourself not to think about the implementation of program code as soon as possible, and leave the constraints of specific programming languages aside, focus on analyzing the business logic of the software we want to implement, analyzing the business processes of the software, and thinking about how to describe and implement the business of the software. After all, software is just a carrier, and business is what we really want to achieve.

But in the design process, I am always worried. If I do not consider the implementation of the program code at all, how can I know that my design must be reasonable? How do I know that the classes and interfaces I designed can be implemented? Therefore, we often see the following phenomena:

In the design process, although you know that you cannot consider code implementation too early, you must estimate the implementation of a class or an interface with your own familiar programming language, check whether it can be compiled. Therefore, if you are not careful, you will go back to the old design path based on the implementation of program functions.

For example, when designing a Web program, data is often displayed on pages. For example, you need to list all users in the system. Assume that the User class is used to represent the User, add the User addUser (), delete the User deleteUser (), and query all the User listUsers () methods. There is a user table in the database, and one record is the information of a user. The following describes how to implement the User class:

The addUser () and deleteUser () methods are well implemented, that is, adding and deleting records to the database. The listUsers () method is actually a select statement for the user table to retrieve a record set. But how can I obtain the list of all users from the listUsers () method?

The return value of a method call is only one and not multiple. Therefore, in many cases, the return value is defined as a set type, such as Vector. In this way, you can extract records from the database one by one and insert them into the Vector when implementing the code of the listUsers () method. In the main program, you can call the listUsers () method to return a Vector, and then traverse the Vector to obtain the user list.

Public class User
{

Public static void addUser (...)
{
// Insert a record to the database
}

Public static void deleteUser (...)
{
// Delete a record in the database
}

Public Vector listUsers (...)
{
// Put the select result of the database into a set
}
}

This design is basically reasonable, but it is still a small problem. During the design, we considered using Java's collection class Vector to store an indefinite and long data set, thus violating the object-oriented design principle: the implementation of specific programming languages should not be considered too early during design. Therefore, you must use Abstract methods and methods unrelated to specific implementations to express business logic.

We know that we usually use the next and hasNext methods to traverse data structures with set features. next is used to get the next user and hasNext is used to determine whether there are other elements. Therefore, we define an interface Iterator, which defines two methods: next and hasNext:

Public interface Iterator
{
Public boolean hasNext ()
{
}
Public object next ()
{
}
}

The Return Value of the listuses method of the user class
Changed to the implementation class of the iterator interface:

Public class user
{
...
Public iterator listusers ()
{
}
...
}

In this way, the design of the User class and the specific implementation method are separated, because any class that implements the next () and hasNext () methods can be used as the return values of listUsers, can be used to express the "user list", not just the Vector.

For example, I can use arraylist to express the user list, because arraylist also implements iterator. Of course, I can also write a class to store the user list, as long as next () is implemented () and the hasnext () method.

In this way, when writing code, the programmer has the maximum flexibility and can use different programming methods to store the user list according to the specific situation. In particular, it reduces the Coupling Degree of the program and increases the portability of the program. The listallmail () method of junkmail should also be changed to the interface type.

Then, use the listusers method of the user class in the main program as follows:

User myUser = new User();
Iterator iterator = myUser.listUsers();
while (iterator.hasNext())
{
iterator.next();
}

In this way, you do not need to consider program code implementation. at a high level, you can abstract the functions and define them as interfaces. At the same time, you can design the system reasonably, it is designed based on business needs.

Conclusion

Through the design instructions of the above examples, the use of Object-oriented thinking is actually a process of abstracting business logic from specific programming technologies, this abstract process is a top-down process that is very consistent with the habits of human thinking, that is, the most important aspect of the problem is abstracted into a simple framework without considering the details of the problem solution, focus on how to solve the main contradictions, divide the details of the problems into small ones, and then focus on solving the detailed problems.

Therefore, once you grasp this point, you will find that in the software design and development process, you will always unconsciously use the object-oriented thinking method to design and write the program, in addition, the design and development of programs are no longer so boring. A software that uses object-oriented technology for design and architecture is even more artistic in mind. Finally, we hope that the object-oriented thinking method can bring creative pleasure to your programming path.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.