Asynchronous programming best practices

后端 未结 4 1275
遇见更好的自我
遇见更好的自我 2020-12-12 11:15

I have recently written my first Android app which was roughly 8,000-10,000 lines of code. One thing that continuously hindered my use of normal design patterns was android

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-12 11:32

    From an amateur perspective, I don't expect my first attempt to be a clean, production-ready app. I end up with spaghetti, fettucini and even ravioli code sometimes. At that point, I try to rethink what is what I dislike the most from the code, and search for a better alternative:

    • Rethink your classes to better describe your objects,
    • keep the code in each method to a minimum,
    • avoid dependencies to static variables anywhere you can,
    • use threads for expensive tasks, don't use them for quick procedures,
    • separate the UI from the app logic (keep it in your classes instead),
    • keep private fields anywhere you can: it will be helpful when you want to change your class,
    • iterate through these until you like the code

    One of the most common errors I've seen in asynchronous methods is to use a static variable inside a loop that creates one or more threads, without considering that the value may change in another thread. Avoid statics!

    As OceanBlue points out, it may not be clear from this that final static variables do not create any danger, but public static variables that can change. It is not a problem with the statics themselves, but with the notion that they will have a value and then find out that the value changed. It may be difficult to spot where the problem was. Typical examples would be a clicks counter or a timer value, when there could be more than one view clicked or more than one timer.

    Hopefully you will receive suggestions from people with much more experience than me. Good luck!

提交回复
热议问题