Sobes.tech
Middle

Why do many developers refuse MVP architecture?

sobes.tech AI

Answer from AI

  • Boilerplate. A lot of code for connecting View and Presenter: interfaces for View, implementation of Presenter, lifecycle handlers.
  • Difficulty in testing the Presenter. Testing the Presenter often requires mocking the View, which can be complex and have dependencies.
  • Problems with state preservation. When the configuration changes (e.g., screen rotation), it is necessary to manually save and restore the state of the Presenter, which can be cumbersome.
  • Poor scalability. As the screen complexity grows, the Presenter can become bulky and hard to maintain.
  • Lack of direct connection between View and data. The View does not have direct access to data; all requests go through the Presenter, which can complicate simple operations.

Example code demonstrating boilerplate in MVP:

// View interface
interface MyView {
    fun showData(data: List<String>)
    fun showError(message: String)
}

// Presenter interface
interface MyPresenter {
    fun attachView(view: MyView)
    fun detachView()
    fun loadData()
}

// Presenter implementation
class MyPresenterImpl(private val model: MyModel) : MyPresenter {

    private var view: MyView? = null

    override fun attachView(view: MyView) {
        this.view = view
    }

    override fun detachView() {
        view = null
    }

    override fun loadData() {
        // Simulate data loading
        val data = model.getData()
        view?.showData(data)
    }
}

// Usage example in Activity
class MyActivity : AppCompatActivity(), MyView {

    private lateinit var presenter: MyPresenter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_my)

        presenter = MyPresenterImpl(MyModel())
        presenter.attachView(this)
        presenter.loadData()
    }

    override fun onDestroy() {
        super.onDestroy()
        presenter.detachView()
    }

    override fun showData(data: List<String>) {
        // Update UI
    }

    override fun showError(message: String) {
        // Show error
    }
}