Giter VIP home page Giter VIP logo

playbook's Introduction

Dwarves Playbook

Dwarves Foundation is an innovation service firm. We have been building an organization with high standard software practices and business growth capabilities, helping tech startups, entrepreneurs and makers deliver their innovative software product since 2013.

We stand for the craftsmanship in software development. More than telling people how to do things, as a team, we take responsibility for collaboratively creating the product of innovation with the client. We value the long-term partnership, and we brought the economic impact through massive product distribution and brought to the market by the clients.

This repo is our playbook which contains our practices in software development and also how we collaborate to make them succeed.

Product Design

Developing

Setup

Practices

Platforms

Production

Business

Contributing

We love pull requests. If you have something you want to add or remove, please open a new pull request. Please leave all PRs open for at least a week to get feedback from everyone.

License

Creative Commons Attribution 4.0 International (CC BY 4.0) @ Dwarves Foundation

playbook's People

Contributors

anduong avatar binhle59 avatar duynglam avatar dyukahi avatar franciosi avatar hieuphq avatar huygn avatar huynguyenh avatar huytieu avatar innnotruong avatar kant avatar khanhtruong avatar lmquang avatar minhcloud avatar monotykamary avatar namnhce avatar nhuocnam avatar phucledien avatar thanhpn avatar thminhvn avatar tienan92it avatar tieubao avatar tuanddd avatar vdhieu avatar zlatanpham avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

playbook's Issues

Go doesn't need generics

Go does not need generics

A little of context

Urs Holzle, the Head of Infrastructure in Google says:

Keeping things simple and yet scalable is actually the biggest challenge"

Google had struggled with that problem ìn 2007 with an enormous codebase, hundreds of developer and the most important thing is 45-minute build. Why is it important, we'll get to that.

During one of those 45-minute builds, they talked about a bunch of features will be included in C++ 11, at that point. Rob Pike who later become one of Golang's creators ask himself:

Did the C++ committee really believe what was wrong with C++ was that it didn't have enough features?

It got them thinking about creating a new language where they should simplify the features instead of adding them.

Eventually, the idea of Go born on September 2007. Two years later, Go marked November 10th, 2009 as its official birthday.

So keep in our mind that Go was designed for speed of compilation and simplicity of the language.

Go philosophy

Most of other languages evolve themselves by adding new features, but in Rob's point of view, adding features would not make them better but bigger. It also makes them much more complicated and become similar to other languages.

Go, however, is a different language. Go doesn't try to be like other languages. Since 2012, when Go 1.0 is released, the language is fixed, nothing has been changed since then. No features which can change the language has been added. The code you wrote back then still work with current Go version.

People might say that without adding features, Go will become a boring language. But what is more important? More fun to write or fewer things to maintain? Adding feature will not only add complexity to the language but also drop the readability of the syntax.

A list of NO's in Go design is a long list which contains not only generics but also ternary operation, pointer arithmetic,... .These features missing because they don't fit, because they affect compilation speed, or because they would make the language too complicated.

Therefore, if your favorite features are missing, and you really need to use them. Go try them on another language. Because after all, Go is just a language. We will need different languages for different problems.

Do we stand on the right side of history ?

By the time Erlang's first appearance years ago, concurrency was kind of a myth back then. Some languages thinked it is essential to have them as a first class feature and some didn't. Python stood on the don't buy it side. But slowly, the usage of concurrency increases.

Then NodeJS and Go were created, highlighted the need for concurrency as a first-class concept, They have shown that concurrency is a must. Python has missed that boat, they stood on the wrong side of history.

Since Go 1.0 is launch in 2009, people don't know whether they need generics or not. By that time, newborn languages like Rust, Swift have proved that have some kinds of generics is useful.

We all know that adding it to Go will make it much more complicated language and increase compilation time which are two things Go was designed to address. But we also know that not adding generics would be a mistake make Go stand on the wrong side of history as Python did. There are reasons for people sticking with Go: simplicity, scalability, compilation time, ... .The question is do we really able to pay the cost for adding generics. If we want to use generics, use Rust or some other language which are support it.

If it has to come to a Yes/No question whether we should add Generics into the language or not. For me, it is a big fat NO, we don't need generics in Go.

How we use Protocol in Swift efficiently

Brief

A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol.

In addition to specifying requirements that conforming types must implement, you can extend a protocol to implement some of these requirements or to implement additional functionality that conforming types can take advantage of.

For more detail, please have a look at: https://docs.swift.org/swift-book/LanguageGuide/Protocols.html
In this article, we aren't going to detail of What and How to implement protocol, instead of that, we are give you some examples to make your code more swiftly.

Clean up protocol mess:
Give an example: We have ProductViewController class show the table of products. Let adoptive tableview delegate and datasource.

class ProductViewController: UITableViewControllerDelegate, UITableViewDataSource {
}

We also need show tutorial for this screen. We has protocol Tutorial

protocol Tutorial {
 func isShowed() -> bool
 func showTutorial()
}

Now our class become:

class ProductViewController: UITableViewControllerDelegate, UITableViewDataSource, Tutorial{
 func numberOfRowInSection() -> Int{}
 func CellForRowAtIndex() -> UITableVireCell{}
 func isShowed() -> bool{}
 func showTutorial(){}
}

Because we are implement tableview protocol, tutorial protocol in one scope of class ProductViewController, the code base mess cause hard to read.
To fix this mess we can using class extension to make class/struct/enum conform to protocol in stead of adopt in base scope of object.

class ProductViewController {
}

//MARK: - UITableViewDatasource - Delegate
extension ProductViewController: UITableViewDelegate, UITableViewDataSource {
 func numberOfRowInSection() -> Int{}
 func CellForRowAtIndex() -> UITableVireCell{}
}

//MARK: - Tutorial
extension ProductViewController: Tutorial {
 func isShowed() -> bool{}
 func showTutorial(){}
}

Now each protocol live in they own scope, we can easy to track, modify or delete if needed.

Use protocol as interface.
As we already know, not like Objective-C and other languages, Swift doesn't have interface. Swift control methods and variables scope by using "Public, Private, Open, FilePrivate" keyword. However we can use Protocol to expose methods and variable without using control keyword.
Example:

protocol  HomeViewModelType{
 var input: HomeViewModelTypeInput {get}
}
protocol HomeViewModelTypeInput {
 func set(product: Product)
}
class  HomeViewModel: HomeViewModelType, HomeViewModelTypeInput{
 var product:Product!
 var input: HomeViewModelTypeInput {return self}
 func set(product: Product) {
 self.product = product
 }
}

Use:
class HomeViewController {
 // We are declare viewModel is **HomeViewModelType**, not **HomeViewModel** , because HomeViewModel conform to HomeViewModelType so we can init viewModel using HomeViewModel.

 let viewModel: HomeViewModelType = HomeViewMode()
 viewModel.input.set(Product)

 viewModel.product //Error because viewModel is type HomeViewModelType doesn't have product.
}

Use Protocol to simplify objects behavior.
User case: You have group of multiple object with different type Label, TextBox and Image. You are building SignUp View to let user create account, before submit info to server we should validate data and indicate in red each UI above. For easy to use, easy to read code above we can adopt protocol following way:

protocol Highlightable {
 func highlightInRed()
}

extension UILabel: Highlightable {
  func highlightInRed() {
   self.textColor = .red
 }
}
extension UITextField: Highlightable {
  func highlightInRed() {
    self.layer.borderColor = UIColor.red.CGColor
   self.layer.borderWidth = 1.0
 }
}
extension UIImage: Highlightable {
  func highlightInRed() {
    self.image = UIImage(name:"hightlightRed.png")
 }
}
 

Shadow protocol
We can use protocol to filter objects.

Example: We have following object:
Horse, Cow, Goat, Salmon, Shark, Pigeon, Eagle, Pine

We want to know which one is Animal or Plant, which one Flyable and so on.
Using empty protocol, knowing as Shadow protocol to mark object as many type we want.

protocol Animal{}
extension Horse: Animal{}
extension Cow: Animal{}
extension Goat: Animal{}
extension Salmon: Animal{}
extension Shark: Animal{}
extension Pigeon: Animal{}
extension Eagle: Animal{}

protocol Plant{} 
extension Pine: Plant {}

protocol Flyable{}
extension Pigeon: Flyable{}
extension  Eagle: Flyable{}

Use: let creatures =  [horse, cow, goat, salmon, shark, pigeon, eagle, pine]

let animals = creatures.filter{creature in return creature is Animal} => [horse, cow, goat, salmon, shark, pigeon, eagle]

let plants = creatures.filter{creature in return creature is Plant} => [pine]

let flyables = creatures.filter{creature in return creature is Flyable} => [pigeon, eagle]

In example above, eagle object is Animal and is Flyable, not only is Eagle.

Native > Cross-platform development

Một trong những vấn đề thường gây tranh cãi hiện nay giữa các mobile developer đó là nên chọn một cross platform framework (React Native, Flutter) để code mobile, hay là native (Java/Kotlin để dev android, Swift/Objective-C để code iOS). Ở Dwarves Foundation chúng tôi vẫn đang stick với lựa chọn Native. Why?

  • Vấn đề về độ đảm bảo:
    Sẽ thế nào nếu FB/Google không tiếp tục phát triển React Native/ Flutter? Một ví dụ điển hình là project Parse của Facebook đã dừng phát triển từ 2017. Đối với Native thì chắc chắn sẽ không bao giờ có chuyện đó.

  • Vấn đề bản quyền:
    Một ví dụ điển hình gần đây là bản quyền của React vào tháng 8 năm 2017 (giờ đã chuyển thành MIT). Facebook khi mới ra mắt React đã gắn bản quyền của React là BSD + patents, có nghĩa là bạn có quyền sử dụng sản phẩm của họ (React) nhưng sẽ không thể kiện họ. Sẽ thế nào nếu một ngày React Native hoặc Flutter thay đổi bản quyền dạng khác, Facebook/Google sẽ bắt bạn làm điều gì đó để tiếp tục sử dụng sản phẩm của họ?

  • Vấn đề làm UI:
    Với các framework cross platform mobile hiện tại thì UI code và Business Logic code sẽ dính với nhau. Còn đối với Native thì UI sẽ tách riêng với logic code (Android là XML, iOS là Storyboard/XIB).
    Đồng thời ở Native sẽ áp dụng Constraint, Auto layout cho UI tốt hơn là framework

  • Vấn đề về adapt feature mới của platform:
    Chắc chắn những feature mới khi các platform update như AR trên iOS sẽ được cập nhật sớm hơn. Cũng như khi các native component UI thay đổi thì các framework sử dụng render engine riêng như Flutter sẽ cập nhật chậm hoặc tệ hơn nữa là sẽ cần dev thay đổi code để adapt các thay đổi này.

  • Code Reuse:
    Đây là lý do mà đa số mọi người chọn sử dụng cross platform framework. "Viết 1 lần và sử dụng ở mọi nơi", nghe có vẻ khá hay, nhưng có thực sự như vậy? Đa số là vậy, nhưng nếu như các feature chưa được support trên cross platform framework thì các developer vẫn phải kết hợp với native, lúc này đòi hỏi developer phải vừa biết code native (android/iOS) lẫn sử dụng framework. Không những thế, đối với các app đòi hỏi phải sử dụng đúng native component với từng platform thì đối với các cross platform framework, chúng ta còn phải định nghĩa UI cho từng platform và chỉ reuse được logic code. Do đó effort bỏ ra cũng không phải ít

Frontend - Typescript recommendations

https://github.com/dwarvesf/playbook/blob/master/engineering/frontend.md (currently outdated for the most parts).

Typescript is dominating and being used opinionatedly in most of our projects, thus some help are needed to add Typescript to polish up our Frontend practices.
@tuanddd @zlatanpham are you guys willing to help? Even just bullet points & some helpful links are good enough (more are welcome ofc), I'll look into restructuring the whole Frontend section later.

Golang or go home

About Golang

Overview

  • An open-source language:

    • Created by Google engineers Robert Griesemer, Rob Pike and Ken Thompson, made its first stable release in 2011.
    • You can contribute to the Go project by creating new proposals, fixing bugs or making it faster. Doing this is considered to have Elite engineer level (SS rank - highest rank in DF's ranking criteria)
  • Why Go?

    • C and C++ are difficult to work with and not safe. Compiling speed, dependencies and runtime errors are vast.
    • Ruby, an interpreted language, is safe but it’s slower and has many dependencies, including the interpreter itself.
    • Java is too complex and verbose to write, it also needs a virtual machine run the code.
    • Javascript lets you free, go wild and slowly kills you (maintenance nightmare, callback hell - before async, await) and no built-in solution for safety.
    • While Go is:
      • Fast compilation makes it work like an interpreted language.
      • Safe because of being: strongly and statically typed and garbage collected.
      • Easy to work with: concise, explicit and easy to read.
      • Modern: has built-in support for multi-core networked distributed applications.
  • Go has proverbs:

    Don't communicate by sharing memory, share memory by communicating.

    => Traditional threading models (in Java, C++ and Python..) require us to communicate threads using shared memory, while Go provides goroutines and channels, encourages the use of channels to pass references to the data between goroutines to ensure that only one goroutine has access to the data at a given time.

  • Advantages of using Go:
    Go has the cutest mascot ever!
    Go's mascot

    • Compilation:
      • It compiles directly to machine code with no virtual machine needed!
      • The language design is built for fast compilation in mind from the beginning.
      • It compiles cross-platform to OS X, Linux, Windows and so on...
      • It creates only one executable file output without any dependencies, easy to upload and run.
    • Safety:
      • Garbage collected: Golang integrates the whole garbage collection system into your executable binary.
      • Reliable: With Go, creating a very reliable software is regular. For example, using pointers in Go is not as dangerous as in C because the memory is being managed by Go
    • Paradigms:
      • Go is an imperative language which is an advantage and a disadvantage to some people.
      • Supports (OOP): Go gets the best practices from OOP and lets you program differently, in a Go way.

        Go wants you to compose things not inherit like in other OOP langs.

      • Supports interfaces (as in OOP). “Polymorphism” in Go is way easier than in other languages: Go lets you attach functions to any type, when a type implements the functions of an interface, that type can be used in places that desire the interface. (The type is now called receiver)
      • Supports functional programming (FP). For example, Go supports anonymous functions, closures, and first-class functions. Here is an example of a simple closure in Go:
        Functional programming
    • Concurrency
      • Built-in concurrency: goroutines - lightweight threads that help build more flexible program in more maintainable way. And Go provides Channels for two goroutines communicate efficiently.
    • Standard Library
      • Almost everything you need is included in Go's standard library (HTTP fetching, JSON parsing, and encryption).
    • Tooling
      • Built-in command-line tools: auto-formatting your code, checking race-condition issues, auto-documentation, test coverage reporting etc.
      • Example Tools:
        • go fmt will automatically rearranges your code for you after each save:
          Before go fmt
          After go fmt
        • go test -cover will display the percent of the statements in source code you tested:
          Test coverage
        • go run -race ... will spot data race for you if there is one :
          Race condition detector
  • Disadvantages of using Go:

    • No generic support: only If you come from OOP languages that support "Templates" and you can't cope with this. Because too much abstraction would cause difficulty in understanding the logic and less explicit code (which is going against the language design from the creators).
    • Err everywhere: only if you hate the replication of this. But as mentioned above, the language design is meant for explicitness, you should cover all cases in your logic!
       // there are no try-catch exceptions in Go, check errors explicitly
       if err != nil {
          return err
       }
       // ...
    
    • No function overloading support. However, Go infers this to some extent by type assertions.
    • Strict rules: Sometimes an advantage, sometimes a disadvantage. For example: You can feel little heavy when you have ever-changing structs. However, most of these rules can be overridden by using Go’s reflection capabilities.
    • Not so strong runtime safety. However, Go doesn’t bring the level of safety, for example, Rust provides. Go’s safety is for compile-time only and only to some extent for runtime (for example forbidden pointer arithmetic). Go cares more about the productivity of programmers (and that is what we care as well).
    • Smaller number of packages as compared to other ecosystems like Node.js and Ruby. This is because Go’s standard library is full of features which mostly doesn’t need third-party support. However, the number of packages are increasing.

We should refactor as soon as we have chance

Brief

  • Software development now seems to be a process of iterations. after every iterations, we introduce more smell codes. However, it's difficult to determine when it's approriate to refactor our code.
  • This always be a indecisive battle and not be the right answer for all types of projects.
  • Refactor too early and you could over-abstract your design and slow down your team. You’ll also make sub-optimal design decisions because of the limited information you have.
  • On the other hand, if you wait too long to refactor, you can end up with a big ball of mud. The refactoring may have grown to be a Herculean effort, and all the while your team has been suffering from decreased productivity as they tiptoe around challenging code.

Questions:

When we want to refactor some code, we should ask ourselves some questions before going up to any refactoring. These all affect to your refactoring decision:

  • How large is scope your project has? (project timeline? team size? how long is an iteration?)
  • How rush are your current in-dev features? Are we in new and complex peices of functionality?
  • Is your release now stable? Small changes may lead to subsequent issues and other bugs not related to current features. And customer will complain about quality or development process.
  • Should we refactor when everything is working ok?
  • Is your customer aware of it and willing to pay for that?
  • How much time and effort will refactoring costs?
  • How much valuable will refactoring get?
  • Is there any slow down impact to current feature development or team?

When we need to refactor:

  • After some release works quite stable.
  • After getting new improvement ideas (more readable, new code style, new architect, ...)
  • An aware issue that occurs multiple times.
  • We are have out-of-date or deprecated libraries/functions.
  • There are security patches or hot fixes from in-used frameworks or libraries.
  • We prepare codebase to apply any new libraries or features.
  • Motivation to learn something new and better.

Who will take responsibility for refactoring:

  • Refactoring tasks should be aware and approved from all team members.
  • Pair programming and do peer review for all refactored code

How we do refactoring (in our case):

  • Before doing this, read some books on refactoring progress or code quality (Clean Code, Working Effectively with Legacy Code, ...) to get ideas, use cases, pros and cons.
  • List out all things we want to refactor
  • Document all issues you have met as lesson learnt so everyone don't run into it later.
  • if it quick, small and safe, count it into current working feature
  • if it's moderately complex and I don’t want to be distracted from the current features, throw it into task list as part of new features/user stories.
  • Whereas, refactoring to bring structural uniformity across the system, must be done with agreement between engineers and product managers.
  • Apply code tools to help us more consistent and reduce effort for refactoring: code formatter, code linter, ...
  • refactor something that no one "needs". Avoid refactor code when many components depend on it, no matter how bad it is. It's risky.
  • remove unused modules, dependencies, redundancy code. we have source control and can easily get back to it anytime if need.
  • Get deep dive into data structures, algorithms and rules:
    • SOLID, DRY, KISS, LESS
    • Design patterns
    • Software architectures
  • improving readability (variable/function naming, organize code into more sensitive components)
  • have test as much as posible on old program to keep the old behaviors are correct and later changes don't accidently change the program behaviors.

Conclusion:

  • Refactor early, refactor often.
    • Refactoring should be started early in a project's development, and should be repeated often.

Hey audiences or other teams, please give us feedbacks and suggestions!!! We appreciate that. <3

Android KTX is the official Anko

Nếu bạn đã lập trình ứng dụng di động android được một thời gian dài, chắc hẳn đôi khi bạn muốn code của bạn gọn gàng và dễ đọc hơn, lập trình được nhanh và dễ dàng hơn. Sự ra đời của kotlin trong việc phát triển ứng dụng di động android một phần nào đã đáp ứng được điều đó. Một trong số những library đi kèm kotlin là Android ktx và Anko là những library chứa những extension functions chứa những giải pháp cho việc này. Android ktx là cái tên xuất hiện sau, là bản chính thức và nằm trong bộ android jetpack. Sử dụng android ktx là 1 điều rõ ràng, vậy thì những lập trình viên đang xài anko thì sao?

Trước tiên ta xem 1 vd về thấy được lợi ích của việc dùng ktx hoặc anko , bạn có thể xem ví dụ sau đây:

// Kotlin
val bundle = Bundle()
bundle.putLong("id", 1)
bundle.putString("style", "fancy")

// KTX
val bundle = bundleOf("id" to 1, "style" to "fancy)

Rất ngắn gọn và dễ hiểu phải ko nào?

Android Ktx: kể từ khi google support cho kotlin trở thành ngôn ngữ chính thức trong việc lập trình ứng dụng android, ý tưởng sử dụng extension functions được google triển khai 1 cách mạnh mẽ và ngày càng hoàn thiện. Và Android ktx sẽ còn được phát triển nhiều hơn vì nó nằm trong bộ Android Jetpack, điểm cải tiến chính từ Android Pie trở đi.

Anko: là một thư viện Kotlin từ JetBrains. Nó chia sẻ các mục tiêu với Android KTX. Android KTX và Anko tương tự nhau nhưng không hoàn toàn giống nhau .

Sự khác biệt giữa Anko và Android KTX
2 bộ thư viện này có những mục tiêu chung nhưng về định hướng thì KTX không có ý định thêm chức năng mới vào các API Android hiện có.

Anko có phạm vi rộng hơn và điều này cho phép nó linh hoạt để đổi mới và tạo các tính năng mới ( Anko Layouts và Anko Coroutines là ví dụ).

Vậy thì giữa những cái chung và cái riêng của 2 bộ thư viện này có điểm gì đáng để chúng ta cân nhắc . Xin mời các bạn cùng xem qua các tính năng nổi bật rồi chúng ta có thể đưa ra kết luận vậy thì chúng ta sẽ nên dùng cái nào nhé.

Common:
là set những library support cho android sdk

Android Ktx:

  • androidx.core:core-ktx
  • androidx.fragment:fragment-ktx
  • androidx.fragment.app
  • androidx.palette:palette-ktx
  • androidx.palette.graphics
  • androidx.sqlite:sqlite-ktx
  • androidx.sqlite.db
  • androidx.collection:collection-ktx
  • androidx.collection
  • androidx.lifecycle:lifecycle-viewmodel-ktx
  • androidx.lifecycle
  • androidx.lifecycle:lifecycle-reactivestreams-ktx
  • androidx.lifecycle
  • android.arch.navigation:navigation-common-ktx
  • androidx.navigation
  • android.arch.navigation:navigation-fragment-ktx
  • androidx.navigation.fragment
  • android.arch.navigation:navigation-runtime-ktx
  • androidx.navigation
  • android.arch.navigation:navigation-testing-ktx
  • androidx.navigation.testing
  • android.arch.navigation:navigation-ui-ktx
  • androidx.navigation.ui
  • android.arch.work:work-runtime-ktx

Anko: sẽ support những mục sau:

  • Intents
  • Dialogs and toasts
  • Logging
  • Resources and dimensions

Nhìn vào danh sách trên, ta thấy android ktx dĩ nhiên sẽ là lựa chọn trong mục này, để sử dụng cho các nhu cầu liên quan đến những module trên chúng ta nên sử dụng bộ android ktx vì nó mạnh mẽ hơn, đầy đủ hơn.

Sử dụng Android Ktx cho các tính năng liên quan đến Android sdk.

VD:

//kotlin
supportFragmentManager
    .beginTransaction()
    .replace(R.id.my_fragment_container, myFragment, FRAGMENT_TAG)
    .commitAllowingStateLoss()

//ktx
supportFragmentManager.transaction(allowStateLoss = true) {
            replace(R.id.my_fragment_container, myFragment, FRAGMENT_TAG)
        }
// Standard Kotlin way
Snackbar.make(layout, "Go Kotlin!", Snackbar.LENGTH_SHORT)
 .setAction("Undo") {
 // Undo logic
 }
 .show()
// Anko
snackbar(layout, "Go Kotlin!", "Undo") {
 // Undo logic
}

SQLite

Mặc dù android đã có sẵn Room để sử dụng database, nhưng nếu muốn dùng sqlite thuần, vẫn có thể dùng bộ extension function này, Cả 2 bộ thư viện đều support

Sử dụng KTX hoặc Anko đều được.

VD

//kotlin
db.beginTransaction()
try {
    // insert data
    db.setTransactionSuccessful()
} finally {
    db.endTransaction()
}

//ktx
db.transaction {
    // insert data
}
//anko
database.use {
    insert("User", 
        "id" to 42,
        "name" to "John",
        "email" to "[email protected]"
   )
}

Coroutines

Về Coroutine, đây là điểm mở rộng đầu tiên so với ktx, nhưng có 1 vấn đề là anko cần thời gian để support kotlin coroutines khi Kotlin cho ra version mới, chưa kể đến việc kotlin coroutines vốn sẵn dễ sử dụng. Tuy nhiên không thể phủ nhận sự đơn giản, rõ ràng của Anko Coroutines

Vì chúng ta nên cập nhật liên tục các version mới nhất của các library của android, kotlin nên ta nên dùng kotlin coroutines

VD:

fun getData(): Data { ... }
fun showData(data: Data) { ... }

doAsync(UI) {
    val data: Deferred<Data> = bg {
		// Runs in background
		getData()
    }

    // This code is executed on the UI thread
    showData(data.await())
}

Layouts

Nếu các bạn đã chán với việc tạo layout xml theo kiểu truyền thống thì anko sẽ giúp các bạn vẽ layout trong code được dễ dàng hơn. Đây là điểm mở rộng thứ 2 của Anko so với Ktx. Android ktx không support chuyện này. Về mục này facebook cũng có 1 library support cho việc này nhưng không tốt như anko, chưa kể ta có thể cài thêm plugin để mà xe preview cho anko layout.

✅ **Trường hợp cần viết layout trong code sẽ sử dụng Anko **

Ví dụ về việc code layout đơn giản

   verticalLayout {
        padding = dip(30)
        editText {
            hint = "Name"
            textSize = 24f
        }
        editText {
            hint = "Password"
            textSize = 24f
        }
        button("Login") {
            textSize = 26f
        }
    }

1 số tính năng thú vị chỉ có riêng ở Android Ktx

Như đã nói ở mục common, Android Ktx support rất nhiều trong bộ androidX, là 1 phần trong bộ AndroidJetpack đó là 1 điều đáng giá để ưu tiên nó vì trong tương lai bất cứ tính năng mới nào, google sẽ cập nhật cho android ktx.

  • Animator functions
animator.addListener(
        onEnd = {}, 
        onStart = {}, 
        onCancel = {}, 
        onRepeat = {}
)
  • Time operations
DayOfWeek.FRIDAY.asInt()
Month.APRIL.asInt()
Year.now().asInt()
  • Text
val builder = SpannableStringBuilder(urlString)        
    .bold { append("hi there") }
// or even some bold / italic / underlined text if you want!
val builder = SpannableStringBuilder(urlString)        
    .bold { italic { underline { append("hi there") } } }
  • Graphics
val adaptiveIcon = bitmap.toAdaptiveIcon()
val drawable = bitmap.toDrawable(resources)
val icon = bitmap.toIcon()
val drawable = someInt.toDrawable()
val icon = someByteArray.toIcon()
val icon = someUri.toIcon()
val colorDrawable = someColor.toDrawable()
val bitmap = drawable.toBitmap(width = someWidth, height = someHeight, config = bitMapConfig)

Đó chỉ là 1 vài ví dụ, bạn có thể tìm hiểu full các function tại đây

✅ **Trường hợp cần viết layout trong code sẽ sử dụng Anko **

Nói chung, Anko và Android KTX bao gồm các phần khác nhau của API Android và không có lý do gì bạn không thể sử dụng cả hai trong dự án của mình. Như những so sánh trên trong bài viết, tùy theo bạn cần những tính năng nào để sử dụng, bạn sẽ có những lựa chọn của riêng minh. Giữa những điểm chung giữa 2 library chúng ta nên dùng Ktx, còn những cái riêng mà anko có mà project cần sử dụng thì nên sử dụng anko.

Sử dụng Anko khi cần viết layout

Sử dụng KTX cho các tính năng thuộc android sdk

Happy Coding.

Nguồn tài liệu tham khảo:

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.