Reconstruction Techniques-cocoa China

Source: Internet
Author: User
I want a military rule for the Boy Scouts: "Always keep the camp clean even when you find it ". If you find something dirty on the ground, whoever gets it will clear it. To improve the environment for the next camper. (In fact, the early version of the rule came from Robert Stephen son Smyth bden-Powell, the father of the scouts activity, and said, "trying to make the world better than finding it ".) This is why I constantly refactor my code to make it clean and tidy. when talking about the quality of programming, code readability is my most important part. I would like to share some of my code refactoring skills that most people don't know about. Dictionary ingAssume that you have a switch statement to allocate some values:
  1. Switch (condition ){
  2. Case value1:
  3. Result = @ "valuefor1 ";
  4. Break;
  5. Case value2:
  6. Result = @ "valuefor2 ";
  7. Break;
  8. Case value3:
  9. Result = @ "valuefor3 ";
  10. Break;
  11. Case value4:
  12. Result = @ "valuefor4 ";
  13. Break;
  14. Case value5:
  15. Result = @ "valuefor5 ";
  16. Break;
  17. Default:
  18. Result = @ "valuefordefault ";
  19. Break;
  20. }
  21. Return result;
Remember to switch only five values here. Imagine one to many. Let's use dictionary ing to simplify this Code:
  1. Static nsdictionary * mapping = nil;
  2. If (! Mapping ){
  3. Mapping = @{
  4. @ (Value1): @ "valuefor1 ",
  5. @ (Value2): @ "valuefor2 ",
  6. @ (Value3): @ "valuefor3 ",
  7. @ (Value4): @ "valuefor4"
  8. @ (Value5): @ "valuefor5"
  9. };
  10. }
  11. Return Mapping [@ value]? : @ "Valuefordefault ";
  Pro's (reason for approval)1. it is easier to read, even if there are more values in the original switch, it can become easier to read. 2. faster, The ing is constructed only once, and then we only need to quickly find the value. 3. it is not easy to make mistakes, because break or return is not required here. 4. based on the nature of code ing, you can easily convert this ing into some static data, such as JSON, plist files ,. Dynamic Block ingHow can we do something dynamic about a more complex switch? We can use block to simplify this code. Recently, I have reconstructed some code and formatted the string for different types:
  1. If ([Title isw.tostring: @ "scratches"])
  2. {
  3. Title = [nsstring stringwithformat :( self. vehicle. numberofscratches = 1? @ "% D scratch": @ "% d scratches"), self. vehicle. numberofscratches];
  4. }
  5. Else if ([Title isequaltostring: @ "dents"])
  6. {
  7. Title = [nsstring stringwithformat :( self. vehicle. numberofdents = 1? @ "% D dent": @ "% d dents"), self. vehicle. numberofdents];
  8. }
  9. Else if ([Title isequaltostring: @ "painted panels"])
  10. {
  11. Title = [nsstring stringwithformat :( self. vehicle. numberofpaintedpanels = 1? @ "% D painted panel": @ "% d painted panels"), self. vehicle. numberofpaintedpanels];
  12. }
  13. Else if ([Title isequaltostring: @ "Chips"])
  14. {
  15. Title = [nsstring stringwithformat :( self. vehicle. numberofchips = 1? @ "% D chip": @ "% D Chips"), self. vehicle. numberofchips];
  16. }
  17. Else if ([Title isw.tostring: @ "tires"])
  18. {
  19. Title = [nsstring stringwithformat :( self. vehicle. numberoftires = 1? @ "% D tire": @ "% d tires"), self. vehicle. numberoftires];
  20. }
  21. Else Title = nil;
By using block ing, we can reconstruct this Code as follows:
  1. Static nsdictionary * titlemapping = nil;
  2. If (! Titlemapping ){
  3. Nsstring * (^ const Format) (nsuinteger, nsstring *, nsstring *) = ^ (nsuinteger value, nsstring * singular, nsstring * plural ){
  4. Return [nsstring stringwithformat: @ "% d % @", value, (value = 1? Singular: plural)];
  5. };
  6. Titlemapping = @{
  7. @ "Scratches": ^ (myclass * Target ){
  8. Return format ([target numberofscratches], @ "Scratch", @ "scratches ");
  9. },
  10. @ "Dents": ^ (myclass * Target ){
  11. Return format ([target numberofdents], @ "dent", @ "dents ");
  12. },
  13. @ "Painted panels": ^ (myclass * Target ){
  14. Return format ([target numberofpaintedpanels], @ "painted panel", @ "painted panels ");
  15. },
  16. @ "Chips": ^ (myclass * Target ){
  17. Return format ([target numberofchips], @ "chip", @ "Chips ");
  18. },
  19. @ "Tires": ^ (myclass * Target ){
  20. Return format ([target numberoftires], @ "tire", @ "tires ");
  21. }
  22. };
  23. }
  24. Nsstring * (^ gettitle) (myclass * Target) = titlemapping [title];
  25. Return gettitle? Gettitle (Self): NIL;
Pro 's1. very secure, because there is no way to mistake the IF-else chain. 2. the ing is cached because static variables are used. 3. we can easily add some macros to make the code more concise, and thus it is easier to expand. PS. I can use string matching to implement it, or even use less code. but I don't think it makes it readable. The process is simplified by using return and inverse if judgment conditions earlier.Now you may find that I do not like too many if conditional clauses and I hate if-esle chains that are too long. on the contrary, I prefer to make the if Condition Statement as simple as possible and use return to return it earlier. original code:
  1. If (! Error ){
  2. //! Success code
  3. } Else {
  4. //! Failure Code
  5. }
My favorite writing method:
  1. If (error ){
  2. //! Failure Code
  3. Return;
  4. }
  5. //! Success code
Pro's 1. I don't need to read more code. assume that I am only interested in the error situation. 2. in the case of a large code segment, I don't need to remember all the processes, because I can clearly see the previous return/break.   Dynamic SolutionSometimes, we may see a situation similar to the following:
  1. If ([type ispolictostring: @ "videowidget"]) {
  2. [Self parsevideowidget: dictionary];
  3. } Else
  4. If ([type isequaltostring: @ "imagewidget"]) {
  5. [Self parseimagewidget: dictionary];
  6. } Else
  7. If ([type isequaltostring: @ "textwidget"]) {
  8. [Self parsetextwidget: dictionary];
  9. } Else
  10. If ([type isequaltostring: @ "twitterwidget"]) {
  11. [Self parsetwitterwidget: dictionary];
  12. }
First, I can apply all the refactoring techniques mentioned above here, but this code seems to be mainly waiting to solve the problem of future scalability, let's take a look at how we can make it better.
  1. Sel dynamicselector = nsselectorfromstring ([nsstring stringwithformat: @ "parse % @:", type]);
  2. If (! [Self respondstoselector: dynamicselector]) {
  3. Ddlogwarning (@ "unsupported widget type % @", type );
  4. Return;
  5. }
  6. [Self defined mselector: dynamicselector withobject: dictionary];
Pro's 1. very easy to read and understand 2. it is safer than the if Condition Statement. 3. it is easier to expand. For example, I can add a new tool type to the category. when developing a derivative app, I don't even need to access its basic classes. ConclusionI often refactor my code. Here are some tips that don't know much about people, but it helps simplify your code. I usually write my code on "appcode. appcode is a great ide with a lot of refactoring functions. I use these functions every day and click the link to download them.

Reconstruction Techniques-cocoa China

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.