Object-oriented design--raising the level of abstraction

Source: Internet
Author: User

Subroutines used from the earliest assembly language to structured programming, then to object-oriented, component-oriented, and service-oriented. I think it's all about constantly raising the level of abstraction. So the programming method is not good or bad, only suitable. Problems in the compilation age are small, so the abstraction we need doesn't need to be too strong. and modern software projects, the scale of the problem is very large, there are a lot of things to consider (although the sheer technical content does not necessarily have a high compilation ERA), we must use a higher level of abstraction to match our problem size.

The advent of object-oriented programming methods is also the case, so we use object-oriented approach to develop a goal is to promote the level of abstraction.

And I think a good way to raise the level of abstraction is to use code to talk to people, to express your thoughts in code, to form a "concept"in code, or to say that code is used to convey knowledge. I put the concept in quotation marks and bold is a special emphasis on the meaning of this in the later I talk about what is said here is the concept. I don't want to talk too much on the surface of the text, let's practice it.

Note that this code is just to illustrate some problems or phenomena, not to consider business rationality, the reader can identify themselves, and then take their own business code to think.

parameters of the method

I don't know if you've written or seen the following code:

BOOL IsValid (string userName, string password, string email, int status);

If you've seen it and then left it alone, you've lost an opportunity to raise the level of abstraction. Robert.martin in clean Code that the parameters of the method should not be too much, if there are too many parameters we have to look at a special. When we look at the method parameters above, we find that these parameters should all belong to the same thing, and now we do not. Similar to string, integer types, the level of abstraction is too low to have any domain meaning. And we found that the parameters and methods of the above method name IsValid is not at the same abstract level, we read to IsValid this method, we can not even suddenly understand its purpose: Oh, this method is to check the validity of the user name, password, mail and state. Oh, how wordy, not necessarily right. If we look at these parameters for two more, we might write this code:

BOOL IsValid (user user);

Publicclass User {

public string Username{get;set;}

public string Password{get;set;}

Publicstring Email{get;set;}

Just to make it easier to use integers instead of enumerations, you can actually create a new enumeration to raise the level of abstraction here-_-

public int status{get;set;}

}

Well, after seeing this method, I knew that this method was used to check the legality of the user, and besides, we created a concept "user", we aggregated a bunch of scattered data into a new object and passed on a knowledge to you.

What I'm saying here may be misleading: I'm not saying that if there are more arguments we're going to abruptly these parameters into a class, the first thing we want to look at is the relationship between these parameters, and if there's no relationship, it's not reasonable.

But I want to say that if you have a method with a lot of parameters, such as three or four, and these parameters actually don't matter, you think about what happened.

don't be obsessed with brother .

Then we go into the IsValid method inside to see:

BOOL IsValid (user user)

{

if (user. Username.length > 0 && user. Email.contains ("@")) {

//....

}

//...

}

We have found that the internal work of this method is to constantly ask the user object, explore the internal state of the user object and make some judgments. It is not good to seek the privacy of others, so strong reliance on others ' internal state violates the principle of object-oriented encapsulation. If our code is constantly searching for the internal state of another object, and then making some judgments, we should think: the object being asked is not a concept. Or the code should belong to the object being questioned instead of the current object:

Publicclass User

{

public bool IsValid ()

{

if (username.length > 0 && email. Contains ("@"))

{

//....

}

//...

}

}

here stick together

Sometimes we find that a part of the method inside the code surrounds a central point in the tangle. Some gaps with other code within the method, most importantly, this code seriously affects the readability of the whole method, because with this code, the method body becomes longer, the method is more difficult to read. At this point we should sort out the code inside the method, check the code, if there is some code to do one thing (the method may be the same point when writing, for the same purpose of the code is put together, but as time goes by, the new code constantly added may violate this principle). For example, the IsValid method above may be implemented as follows:

Publicclass User

{

public bool IsValid ()

{

if (Username.length > 0 && (email). Contains ("@")

&& (email. EndsWith (". com") | | Email. EndsWith (". Biz"))))

{

//....

}

//...

}

}

That long list of && | | is not to verify the legality of email. Because its existence makes a mess here, if we can further raise the level of abstraction: Extract a group of code into a method, using the method name to describe the method itself:

Publicclass User

{

public bool IsValid ()

{

if (username.length > 0 && isemailvalid ())

{

//....

}

//...

}

BOOL Isemailvalid ()

{

return email. Contains ("@") && (email. EndsWith (". com") | | Email. EndsWith (". Biz"));

}

}

Not only the abstract level of this group of code to improve, IsValid suddenly also noble up, understood more (but that group of code is still there, but hidden behind the abstract, forget is there is a famous saying: Every beautiful interface behind there is a dirty implementation < jokes >).

Split Personality

Encountered such code did not, a class in five methods, three methods to access the A,b,c property, the other two methods to access the D,e,f property. There seems to be a looming dividing line that divides this class into two. Sometimes the dividing line is not very obvious and there may be some overlap. This is actually similar to extracting a method described above. We are just a higher level than the method: missing a type to separate this part of the code. Or look at the user class above, we found that there are a few ways to always surround the email in circles, the user class other things are not very concerned about:

Publicclass User

{

public bool IsValid ()

{

if (username.length > 0 && isemailvalid ())

{

//....

}

//...

}

BOOL Isemailvalid ()

{

return email. Contains ("@") && (email. EndsWith (". com") | | Email. EndsWith (". Biz"));

}

public string EmailAddress ()

{

return string. Format ("\" {0}\ "<1>", Username,email);

}

private String Convert ()

{

if (email. IndexOf (' # ')! =-1)

{

return email. Replace (' # ', ' @ ');

}

}

}

I think maybe we're missing an email concept, so we can encapsulate these methods and the attributes they want to use:

Publicclass User

{

private email email;

public bool IsValid ()

{

if (username.length > 0 && email. Isemailvalid ())

{

//....

}

//...

}

}

Publicclass Email

{

private string address;

BOOL Isemailvalid ()

{

return address. Contains ("@") && (address. EndsWith (". com") | | Address. EndsWith (". Biz"));

}

public string EmailAddress (string userName)

{

return string. Format ("\" {0}\ "<1>", Username,email);

}

private String Convert ()

{

if (email. IndexOf (' # ')! =-1)

{

return address. Replace (' # ', ' @ ');

}

}

}

All right, let's talk about it so much. There are many more examples of similar levels of elevation of abstraction, simply by re-organizing the code, forming concepts, and passing the knowledge of the field to the person reading the code. Then I want to say that object-oriented design may be really difficult, need rich experience, but object-oriented programming is not difficult, just need us to have a better heart on it. The code is not written out and then put there, and then not to the tube, we need to take care of our code every now and then, then observe, and then continue to carve.

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.