In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Most people do not understand the knowledge points of this article "what are the principles of DRY and TED", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this article "what are the principles of DRY and TED?"
The code we write needs to be read not only by the machine, but also by others. So we're going to write:
Code that can be read by others
Extensible code
Testable code (code should be testable, and writing tests for code that does not have testability is a waste of life)
Among them, 2BI 3 points put more emphasis on the principle of object-oriented design. While this article pays more attention to the local code problems, this paper summarizes the common mistakes and optimization methods by giving examples.
The examples in this article are based on two guiding principles:
I. dry (Don't repeat yourself)
This principle is so important simply because:
The less code, the less Bug
Code without repeating logic is easier to maintain, when you fix a bug, if the same logic appears in another place, and you don't realize, do you feel wronged?
II. TED principle
Simplicity (Terse)
Expressive (Expressive)
Just do one thing (Do one thing)
three。 Give examples to illustrate
1. Reject comments and elaborate comments in code
Counterexample:
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
sixteen
seventeen
/ / /
/ /! @ # $% ^ & ^ & * (
/ / /
/ / /
Public decimal GetCash ()
{
/ /! @ # $% ^ & ^ & * ((! @ # $% ^ & ^ & * (
Var a = new List () {2m, 3m, 10m}
Var b = 2
Var c = 0m
/ /! @ # $% ^ & * (
Foreach (var p in a)
{
C + = pawb
}
Return c
}
After refactoring:
one
two
three
four
five
six
Public decimal CalculateTotalCash ()
{
Var prices=new List () {2m, 3m, 10m}
Var itemCount = 2
Return prices.Sum (p = > p*itemCount)
}
Good code naming can completely replace comments, and if you are trying to write a comment, in a way, you are trying to write a piece of code that no one else can understand.
When you can't give your method an exact name, it's likely that your method does more than one thing and violates (Do one thing). Especially if you want to add words such as "And,Or,If" to the method name
two。 Assign values to Boolean variables
Counterexample:
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
Public bool IsAdult (int age)
{
Bool isAdult
If (age > 18)
{
IsAdult = true
}
Else
{
IsAdult = false
}
Return isAdult
}
After refactoring:
one
two
three
four
five
Public bool IsAdult (int age)
{
Var isAdult = age > 18
Return isAdult
}
3. Conditional judgment of double negation
Counterexample:
one
two
three
four
If (! isNotRemeberMe)
{
}
After refactoring:
one
two
three
four
If (isRemeberMe)
{
}
Whether you have seen such a condition or not, I have. Seeing such a conditional judgment, I immediately fainted.
4. Refuse HardCode, refuse to dig a hole
Counterexample:
one
two
three
four
If (carName = = "Nissan")
{
}
After refactoring:
one
two
three
four
If (car = = Car.Nissan)
{
}
Since we are playing a strongly typed language, we will use the function of the compiler to make the error occur during the compilation phase.
5. Refuse the magic number, refuse to dig a hole
Counterexample:
one
two
three
four
If (age > 18)
{
}
After refactoring:
one
two
three
four
five
Const int adultAge = 18
If (age > adultAge)
{
}
The so-called Magic number is a magic number. Readers have no idea what your number is. There are a lot of such codes.
6. Complex conditional judgment
Counterexample:
one
two
three
four
five
six
seven
If (job.JobState = = JobState.New
| | job.JobState = = JobState.Submitted |
| | job.JobState = = JobState.Expired |
| | job.JobTitle.IsNullOrWhiteSpace () |
{
/ /....
}
After refactoring:
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
If (CanBeDeleted (job))
{
/ /
}
Private bool CanBeDeleted (Job job)
{
Var invalidJobState = job.JobState = = JobState.New
| | job.JobState = = JobState.Submitted |
| | job.JobState = = JobState.Expired |
Var invalidJob = string.IsNullOrEmpty (job.JobTitle)
Return invalidJobState | | invalidJob
}
Is there a sudden enlightening rush?
7. Nested judgment
Counterexample:
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
Var isValid = false
If (! string.IsNullOrEmpty (user.UserName))
{
If (! string.IsNullOrEmpty (user.Password))
{
If (! string.IsNullOrEmpty (user.Email))
{
IsValid = true
}
}
}
Return isValid
After refactoring:
one
two
three
four
If (string.IsNullOrEmpty (user.UserName)) return false
If (string.IsNullOrEmpty (user.Password)) return false
If (string.IsNullOrEmpty (user.Email)) return false
Return true
* this kind of code is subject to some early idea of using a variable to store the returned results. It turns out that once you know the result, you should return as soon as possible.
8. Use preconditions
Counterexample:
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
If (! string.IsNullOrEmpty (userName))
{
If (! string.IsNullOrEmpty (password))
{
/ / register
}
Else
{
Throw new ArgumentException ("user password can not be empty")
}
}
Else
{
Throw new ArgumentException ("user name can not be empty")
}
After refactoring:
one
two
three
If (string.IsNullOrEmpty (userName)) throw new ArgumentException ("user name can not be empty")
If (string.IsNullOrEmpty (password)) throw new ArgumentException ("user password can not be empty")
/ / register
The style after refactoring is closer to contract programming, first of all, the pre-conditions must be met, otherwise there is no need to talk about it.
9. Too many parameters, more than 3
Counterexample:
one
two
three
four
Public void RegisterUser (string userName, string password, string email, string phone)
{
}
After refactoring:
one
two
three
four
Public void RegisterUser (User user)
{
}
Too many parameters make it difficult for the reader to grasp the intention of the code, and too many parameters will affect the stability of the method. It also indicates that the parameters should be aggregated into a Model
10. The method signature contains Boolean parameters
Counterexample:
one
two
three
four
Public void RegisterUser (User user, bool sendEmail)
{
}
After refactoring:
one
two
three
four
five
six
seven
eight
nine
Public void RegisterUser (User user)
{
}
Public void SendEmail (User user)
{
}
The Boolean parameter is telling the method to do more than one thing, violating the Do one thing
10. Write expressive code
Counterexample:
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
sixteen
seventeen
eighteen
Private string CombineTechnicalBookNameOfAuthor (List books, string author)
{
Var filterBooks = new List ()
Foreach (var book in books)
{
If (book.Category = = BookCategory.Technical & & book.Author = = author)
{
FilterBooks.Add (book)
}
}
Var name = ""
Foreach (var book in filterBooks)
{
Name + = book.Name + "|"
}
Return name
}
After refactoring:
one
two
three
four
five
six
seven
eight
nine
Private string CombineTechnicalBookNameOfAuthor (List books, string author)
{
Var combinedName = books.Where (b = > b.Category = = BookCategory.Technical)
.Where (b = > b.Author = = author)
.Select (b = > b.Name)
.aggregate ((a, b) = > a + "|" + b)
Return combinedName
}
Declarative code is more expressive and concise than imperative code. This is one of the reasons why functional programming is becoming more and more popular.
four。 About DRY
Usually people refactoring code, an important idea is DRY. I'd like to share a counterexample of DRY:
Projects have a variety of MODEL layers during the architecture process, such as DomainModel,ViewModel,DTO. In many cases, most of the fields in these Model are the same, so some people will think of the DRY principle and simply use one type instead of pasting and copying and switching back and forth.
The fundamental reason for the failure of this counterexample is that these Model responsibilities are different, although in most cases the content will be duplicated, but they play a variety of different roles.
Consider this scenario: DomainModel has a field DateTime Birthday {get;set;}, and ViewModel also has DateTime Birthday {get;set;}. Demand upgrade: the interface is required to no longer display birthdays, only whether they are adults or not. We just need to add a Bool IsAdult {get {return.}} to the ViewModel, and the DomainModel does not need to be changed at all.
five。 Make use of advanced production tools
Take Reshaper in the vs plug-in as an example, Reshaprer can give varying degrees of hints to most of the counterexamples listed in this article. After a period of practice, when Reshaper can't give any hints to your code, your code will have a significant improvement.
Screenshot shows the prompt function of Reshaper:
The cursor moves over the wavy line, and Alt+Enter,Resharper automatically optimizes the code
The above is the content of this article on "what are the principles of DRY and TED". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.