[Translation] WWDC 2019: good development habits

This translation from WWDC 2019 Session 239
Speakers: Josh Tidsbury

Successful APPdevelopment need to master all aspects of things. Understand the practice can be incorporated into the development process to improve your productivity, improve your APPperformance and stability. By learning how to improve the Xcodequality of the code written. Gain some valuable practical understanding of technology development.

Good morning, I'm Josh, from Apple technical evangelism team. Our team is an incredible honor to work with developers like you from around the world. Our goal is to help you develop a truly outstanding APP. In exchange you we learned a lot, you have to understand the process used, challenges, goals and vision. We can help you out to learn skills and tools, although each story we hear is slightly different, but no matter from where in the world, they have a lot of common themes.

When you imagine 手艺when the word, the first thing you might think of the design. Developers and engineers also engaged in craft, craft, after all, defined as follows:

  1. Skills planning, production and execution of
  2. Heart, skilled or creative and production and

Code is out of hand, it involves a lot of skills in the construction of APPneeded technical and creative choices. Today I want to talk to you about this door "craft activities" care about things such care into your code, storyboardsand products. It may seem easy to start, but the combination of all the requirements of today we proposed the developer point of view, sometimes quite difficult. Craft skills evolve over time, which requires dedication, patience and concentration. It's about learning to enjoy the process of bringing almost the same as when the destination and more. Part of this process is to convert those who need strong at the beginning and conscious attention to things as customary, the number of things in practice to drive a car, conscious attention when we drive over time is reduced similar, because we have these things converted to natural habit in Appdevelopment, we can do the same thing.

To do this, it means to embrace a good habit to abandon bad habits. When developing a APPtime, developers need to focus a lot of details, but these details are rarely used our APPusers observed directly, but they can feel the performance, reliability and stability due to the impact of these details.

We do not have enough time to focus on all the details here. Today I want to take some time to review some promising practices to improve our development work, they will be incorporated into routine work processes after the formation of habits, it will save us from the plight of frustration, hassle and waste of time in the future . I'm sure most of you have been in practice many related things, but perhaps some of you did not become a habit, maybe some inspiration here will be away for more practice.

First we look at 组织 :

1. Organization

In addition to APPoutside developers of identity I was a carpenter, for me, is a good a way to escape from modern life. One thing for sure is that much easier to create a good and beautiful furniture in a clean workshop in. If your table is disorganized, incoherent, and it is difficult to find the tools and materials needed, we had to make room for your current job and upset something more, spend more time than usual At the same time the process is also accompanied by more accidents and errors.

Our team contacted every year many Xcodeprojects, there are some practices that can help you ensure clean workspace, so you can best work.

XcodeProject to benefit from Groupthe code structure and organization brings. Let each part of your program code files at a glance, when you try to repair Bug, quickly ready for you.

Using the Groupangle function blocks to organize your projects, which users operate Appthe same way on the logic. We often see some of the projects using the file type to group, or simply do not grouping, so there is no benefit to want to quickly learn how to source files associated with people.

Furthermore grouping helps your Xcodeproject structure and the actual file system structure to match. From the Xcode 9beginning, when you're new in the project Groupwill also create a file folder on the disk to store files in the group. This means that no matter when you look at all similar from the project, source code management or disk structure, helps reduce confusion and chaos.

StoryboardIt is a very powerful tool for building user interfaces through a visual manner. We did have a number of projects all UIall will fall in one Storyboard, there is no reason to do so.

Thanks Storyboardbe referenced between. It should be created separately for each major part of the application Storyboard, and then connect them by reference. You will find that this can be well isolated from separate changes, and make you easier in a large team, avoiding the risk of those nasty merge conflicts. Just like you would not put all the code in a file in the same, so do not put all UIin one Storyboardfile.

The project files up to date is to make sure Xcodeto help you solve the key methodological issues and avoid accumulation. If you regularly deal with it really can not be a problem, if placed ignore, really cause problems in the future. First of all, when you update to a new version of Xcodethe time, sometimes you need to make the decision Xcodeto update the project settings and project files to the latest format. So, unless you have an important principle do not, otherwise we recommend that you appear in a pop-up prompts or issue navigatordo this when warnings.

Second, make sure your project using the new build system New Build System, this feature was first introduced in 2017. It is in terms of performance, rely on management to make significant improvements to adopt Swiftthe package play a crucial role. From its Xcode 10start as the default build system, you can pass from Filethe lower menu Projects Settingsto see validation in progress.

As a carpenter, we often retain some little scrap in case you might use, they should be filled until we have to accept the reality: These small scrap never really been used to project. Developers also have this preference, but fortunately there is a (compared to woodworking) more easy decision, because you have joined the project code into source control, you have it? Remove those codes do not need and do not use, do not just comment them out. In case one day you want to get it back, if you really need it, you can also from the historical version of that file will find it back, throw away these "little scrap" it.

The other thing we do not want to lose control of things is a warning Warning. To do this, you and your team should begin to practice zero warning, the code contains a warning should not be checked in, you should treat treat errors as warnings, fix them as soon as possible. If our project has thousands of warning, most of the reason is because the developer did not give up and arrange a time to fix them and built up. Also, if you maintain such a project, when a new alert is generated you simply can not find.

By the following way to make your project work space and Article no tangled and neat and clean, which you APPplay a crucial role in the long-term health and success:

  • Use Groupto organize your project, and file system structure corresponding
  • Use Referencesplit oversizedStoryboard
  • Ensure that project documents are up to date
  • Clear abandoned, old code;
  • To find and address the root causes of its warning appears.

Do these things make your projects to be flexible, your development process work better in the project life cycle.

2. Track

Speaking of source control, you should enable it when building the project. We did come across many projects without source code control, especially those independent development team project. You set up Xcodewhen the project, you just need to make sure this checkbox is checked on it, so that your project will use the Gitsource code management.

Now you can always go back and look at your past changes, and when changes occur when you commit the current set of changes and easier to detect any type of error. After you enable source control, it should also pay attention to these things makes it more useful and efficient:

First, the smaller size of each submission. Regularly checking to make your current code and branches to keep a small incremental update, make these changes possible localized and self-contained. When you need to solve clues or later return to the bug, which will give you a review of the path. And because these are small changes you do to reduce the chance of introducing infringement.

Secondly, write useful commit messages. Because one day we will ask out of this hope I can answer the question: exactly what was wanted. When you are trying to remember the circumstances and reasons when the code was changed, you commit messagesis to give you the future of notes.

Even if you are an independent developer source code control also like to participate in large team that. This means adding new features and bug fixes can be done through a branch, once you're done you can squash merged back into the main branch or devbranches, use meaningful commit message. Now you have a variety of options and model to follow, I suggest you try to use them to find the most suitable for your kind and integrated into your development process.

This is the track. Managing source code for successful modern Appdevelopment workflow is essential, apply it as part of your project, regarded as part of everyday practice. Maintain a smaller submit, fill in useful commit message, as well as the use of branches to help manage and isolation due to bug fixes or code changes to add new functionality caused.

3. Document

In my opinion, the code clarity and maintainability greatest contribution notes and documents that you and your colleagues for the kind of action like breadcrumbs. Some people say I do not need code comments, my code is self-documenting (self-documenting), I'm not buying it. From the perspective of the algorithm code written in really good clear description of what it does, indeed from the record. But it does not explain why, the reason why there are these codes, how to adapt the code in a larger context, nor does it describe the reasons behind such an approach when writing at that time. Best developers I worked, was not only incredibly clear and concise writing code, but also take the time to leave a review of records or useful comments in the code to guide future readers to understand the intent of the original author. Junior developers can benefit more in the process, because you will begin to experience great changes at the end of inconsistencies, the decision taken at the start may actually make the final decision on the project. (Translator's Note: junior developers in because the experience of the factors leading to the code changes more, and therefore require more documentation and a clear description of the comment)

How to be counted as good comments it? Good comments assume readers understand the programming language used, and the steps adopted a code sequence can walk through, it really concerned about is the reason for the code originally written here causes and support to do so. For example, we often see that it is actually of little value Notes:

//A constant string id value
let id = "2ADA155F-1529-4D2D-98C4-0E4BD06940E8"
复制代码

I'm assuming most of you use Swiftwritten some code to know here is create a string constant to carry this value, but we do not know idwhat it is, its uses and is hard-coded into APPthe cause of. Add comments to it a little later, we understand the reason for the existence of this value, and where it comes from.

// The permanent identifier for this application when interacting
// with the CMS, provided by the vendor of the CMS.
let id = "2ADA155F-1529-4D2D-98C4-0E4BD06940E8"
复制代码

We could go further, to a variable after the name change became clearer.

// The permanent identifier for this application when interacting
// with the CMS, provided by the vendor of the CMS.
let cmsApplicationIdentifier = "2ADA155F-1529-4D2D-98C4-0E4BD06940E8"
复制代码

If you find your own variables using a single letter or similar id, etc. name, and perhaps this is you give them choose a more descriptive name of a good opportunity. Auto-complete feature allows Xcodefull of charm, you even do not have to enter any more things. In this case the identifier when used at any time throughout the code base is clear.

Bring documents and notes similar benefits, but these benefits are throughout the entire application even beyond. When you write your own APP, you create layers of abstraction and algorithms, large segments of code into neat winding can be tested, reusable functions. If you do not choose these functions to add documents, then you have to be over in the minds of the document function again at forcing yourself every time you use this function, it is often necessary to achieve this from the beginning to understand the internal functions, including each parameter how to use and the results generated.

If you do not know how to Xcodeadd documents, it is very simple, as long as the first line you position the cursor to the function signature, then press option + command + /the key combination, you need all the placeholder text will be generated automatically fill the empty enough.

Hold down optionand click on any use of this function will display the place already know and love with your native SDK / Swift standard library style similar shortcuts help pop-up box.

High-return investment notes and documentation is really low investment of your time, it will be a steady stream of income throughout the project cycle. So please for your code to add useful comments, so that readers can better understand the original author's ideas. More choice for your variables descriptive names for your functions, properties, structures, and enumerations are added on documentation.

4. Test

Next, I want to talk about testing, especially unit testing. To this end I would like to tell us Marshall, he is our Swiftpreacher and development tools, a very smart and friendly partner, also happens to be a Swiftfield Lint 对讲机.

Whenever I submit code review, I was ready to welcome a tsunami-like insights and feedback of preparation, which helped me to improve the content written from form and function. A few days ago, Marshall on another topic unit tests also led me to the right direction. Now, I must admit, I did not write unit testing impeccable record, I do not do not appreciate the potential value they bring, or are not familiar with them, but I always tend to come out after they had actual code write unit tests, I always wanted to do it on the last.

However, one day I was in for a APPmoment to realize the data model layer of new features, Marshallsaid to me: "What are you doing these things, between the dictionary and the structure of these two represent the best add a unit test to ensure the switching back and forth to work properly. "

I really can not figure out how this could go wrong in the future, but I still listen to Marshallthe views of this simple process to add a unit test. I ran down unit testing, see the green check mark indicates that the test passed, I feel very satisfied, so I submitted the code review. Once again, I think this test is in a few weeks we need to add additional data to this structure, there is no problem running after modification time, my work is done, right? Ready to check the code, and then I remembered that run the unit tests, because I really forgot to modify the dictionary deserialization manner caught the existing unit tests. This Bugmight we achieve UIwill be exposed time, there is no doubt that we would waste a considerable amount of time to find out why. So thanks Marshallfor reminding me the unit tests as part of routine practice Marshall: "You're welcome, Josh!"

Write unit tests is important, even those seemingly looks relatively simple code As this example I encountered the same. Vulnerability of the code and a potential return of bug, in view of this we do not have so much time to thoroughly test, we will Xcode, as an extra set of "eyes."

Therefore, the implementation unit testing as part of routine practice to develop and run them before each submission. Unit testing is a key component of continuous integration, so you can be ready for it. Testing is one of the users never actually see the hidden details, but may lead to different consequences, giving users the ultimate experience or APPsignificant damage caused by data being very frustrated.

5. Analysis

Today there are many forms of analysis can be used as part of your daily work processes, some of which need to invest extra time, some may work for you in the background, you do not even need to go to hell.

Called Network link Conditionertool is very useful APPto develop a good network performance often in the home or office, is not your APPtypical setting is usually used.

Therefore, by enabling Network link Conditioner it can artificially limit the performance of network performance is similar to a typical cellular network, and even poor network environment, you will be amazed at the number of issues arising in this race and load conditions, so your customers avoided.

In your Schemehave some settings Sanitizerselected, you can find a variety of errors in the development cycle through them. Address SanitizerSimilar problems will monitor memory errors and buffer overflow, memory problems are often the cause of security vulnerabilities, so use Address Sanitizerthat can help you make sure that these issues will not be exposed to online.

By enabling Thread Sanitizercan you use the simulator to test or debug your APPdiscovery data competition problem. Data competition means that two threads are not synchronized, and at least one attempt to write the same piece of data, which may make the mistake of annoying running unforeseeable problems arise even memory exceptions.

Undefined Behavior SanitizerCan capture such as division by zero, floating-point conversions out of range or overflow, and unaligned pointers, etc. bug, when it occurs undefined behavior program may crash, it may not be expected to work, or appear to be no problem, but at different times seemingly no reason different results. SanitizerIt can help you get rid of frustrating bug, before they cause havoc in your project.

The last is to introduce Main Thread Checkerit to make sure you're not in a background thread AppKitand UIKitof APIinvalid calls. For example, if you go outside the main thread in the thread updated interface, it could result in the loss of interface updates, visual confusion, loss of data and crash. Sometimes these bugas occurs intermittently become very difficult to track, and the impact on the performance of this function is to enable very small, so we recommend that you keep as much as possible to enable it.

In debug your AppPlease always pay attention to performance and resource utilization to ensure the appuse of system resources as efficiently as possible. First, you can use the debug dashboards, these dashboards at any time when you build and run the project in Xcodethe Debug Naviagtorfind, you can see through their entire Applife cycle CPU, 内存, 磁盘and 网络utilization of, you quickly understand Appwhether it is connected through an unknown network server or an endpoint is constantly polling, consume large amounts of bandwidth and power.

Finally, you can pass Profilethe Instrumentsfurther in-depth analysis button. Which I often use one Time Profiler, it allows you to identify which paragraphs of the code takes up most of the period, and that period may allow us to reduce the scope of the code should become asynchronous or is not scalable way to achieve.

Analysis is a fairly wide range of topics, but most of the tools described in this I just need you to remember is enabled on the line. Use Newwork link Conditionersimulate typical or poor network conditions; frequent use Sanitizersand Checkers, as long as they are open just fine; regularly check the debugging dashboard, and pay close attention to your APPfootprint and performance; use Instrumentsto analyze your Appin-depth research and more accurately solve those problems. These small efforts into habits will greatly improve your APPperformance and reliability.

6. Assessment

Living in Toronto when I have a garage, then it changed my carpentry workshop, this is a comfortable space, it is entirely belongs to me.

But since moving to the Bay Area, I have not the space of their own. I've been here all kinds of shared community woodworking shop, because now must share space with other tools and so sometimes people get frustrated. But I did not realize I should be grateful instead is the opportunity to exchange ideas to other people in the store and ask them for advice on what to do.

I think that the Appanalogy is code review development. Over the past few years I have been as an independent developer to complete many Appof the development, which seems to me to have their own workplaces, like, incredible too fast and flexible, only their opinion is important. The disadvantage is that you do not learn from colleagues or counterparts better use of language, framework and SDK opportunity.

While solutions to problems usually have many, but there is always a better kind. Such that more concise or performance, maintainability and reliability more prominent way. Not because it worked just means that it must be correct, can not in some way it can go significantly improved. (Translator: combined 个人工作间 vs 共享工作间, 个人开发 vs 团队开发advantages and disadvantages to understand these words)

All of Apple's team has a policy of non-accredited code can not be incorporated into the project. Through this process our team learned a lot from each other, more consistent code style, not to mention the convenience of improved reliability. It also ensures that our entire team is more familiar to the wider code base, so that we can address the bugscope and functions are also wider. I was fortunate in such an experienced team, which makes things simple. But if you ran your own company or an independent developer, try to find your area or from partners around the world, and with their code review each other. Perhaps also from gathering, conference or share the local office to look to find. So, now that you've included in your plan to review the code of practice developed it.

Good code review is kind of how? First, take time to understand the meaning of each line of code changes, glance makes no sense. Second, build the project and run look, do not assume that the author has done before, the last time the merger is submitted especially to see your records. Run these tests, the first to do so is to remind you to check whether in fact these tests and whether the test passed, remember compiler does not mean destruction on some manner does not exist. Thoroughly read these notes and documents, I mean some of them, right? Then find out whether there are spelling and grammatical errors. Continue to find the variable name misspelled, as a Canadian, I have a long-term use colouras a color variable names habit, it makes my team look coloralmost crazy when variable. To ensure the function code library, consistency variable names can be easier to find, but also save time.

This process may feel in the short term may slow down your speed, but in the long run, by reducing the potential for errors and problems, will undoubtedly save you time, money and customers. Benefit when you, as a developer of experience dealing with similar modes or challenges in the future.

7. Decoupling

Developers committed to creating a small but reusable, testable code, after all, we do not want to always be repeated again and again to write the code.

Package and framework gives us a more focused way to maintain the opportunity to code, and portable way to provide functionality, not just your current App , the other App can take advantage of these gains. If you App include Extensions and packaged into their shared code Framework , then your application binary package size will be reduced, because your Lord App and Extensions to share this Framework . Of course, creating package also gives you the opportunity to share the results of your efforts in the community, especially now with the Xcode 11 package of tighter integration of. But in addition to you App , the shared framework, package and library code, but also comes with excellent documentation to allow others to better use.

Therefore, the frame and the package as a way to split your code base, which can make your role in the outcome more are being developed or maintained app. FrameworkIt can help you reduce the size of the binary package, then you can share the results with the community, but make sure that came with excellent documentation.

8. Management

Finally, I want to talk about is a dependency management, especially to find out the benefits and risks it brings to your project. Use Swiftpackage, frames and other library has many benefits, but before you get started, understand the contents of the library which contains the well in question is potentially very important.

To make sure you understand the dependencies impact on the data you want to Appresponsibility for the content, including actions for the number of users. Ensure that the Frameworkindex information is not collected or equipment necessary to ensure that it does not have the data sent from your device.

Also we have to understand and study the given dependencies of dependencies. After all, after the introduction of the dependent packages contain dependencies means that your Appsafety and success of this whole chain of hooks.

Finally, there is another possibility will destroy you App, if dependencies are not maintained how to do? Or simply disappear it? It is important that you have a plan you decide how to deal with these situations is encountered at any time, after all, you introduced a new dependency in the project, the future projects really depend on it. So are you ready yourself to fix this open bugit? Or turn it inside the project and maintain it, or if you plan to have to rely on that in the future all cleared out and include the necessary work so bring?

Use external dependencies (such as Swift package) allows you to complete the work more quickly, and to avoid duplication tool to create a community that already exists. In the attitude control their use, to ensure that they do so only in accordance with your expectations, be sure to use them to respect your Appusers' privacy. Action plan prepared to deal with mistakes or they disappear in the future. Ask when you add a new dependency in the project yourself these questions, this thing becomes your habit, you will maximize their strengths and get the long-term returns.

to sum up

For Appdevelopment projects, the final project sometimes feel 10%the time spent working with the former 90%as long time. But I think after trying by these practices into habits, you can avoid this feeling.

By effectively organize your workspace, so you work faster and more efficient to focus on the actual code. The use of source code control track your library, you can reduce the chance of regression bug, the bug can lead to speed up the investigation of the cause. Help write meaningful comments and documentation, you can read the code in the future, and each time I have written a class, structure, reduce the burden of the cost function. Unit testing can save you at the last minute, to introduce some regression bug in time. SanitizersAnd checkersability to provide ongoing analysis of your code, they run in the background, you do not even have to worry about. Dashboard and Instrumentsensure you efficient use of system resources, allowing you to accurately track performance and other issues. Code review is not just evaluate code style and function, it is a great learning opportunity for you to improve your development skills and share it with your development team in the community. Your project will be broken down into smaller, reusable bag and framework to help you get extended to multiple projects, and it allows you to share your work, this is also beneficial to reduce the size of the binary package. Finally, the use of external dependencies (such as Swiftpackages) can be reused community has developed good features to help you get things done faster. But be sure to check that they are doing good, remember? Including its user data you do, you do not have them ready.

These practices as part of your job, will only increase a little bit of time for each stage of the project, but will save incredible time for you in the long run, make sure your project is built to last. I hope that the ideas and suggestions for you today so that you can offer to think about how to further improve as a developer 手艺. You're thinking incorporate these practices can improve your quality of work and stability, these conscious efforts to convert habits that will allow you to make more energy into important areas. You use those APPpeople may not say why, but you can feel the care put into the work brings, you can build for yourself these proud. Thank you!

[Applause]

Reproduced in: https: //juejin.im/post/5cfe40dae51d45590a445b1b

Guess you like

Origin blog.csdn.net/weixin_33840661/article/details/93178559