在MainActivity内部实现一个类的做法存在哪些缺点?

huangapple go评论62阅读模式
英文:

What are the drawbacks of implementing a class inside MainActivity for android?

问题

我在想,何时不适合在MainActivity内部实现一个类。直到现在,我只使用了一个活动(Main),所以我一直在MainActivity内部创建类。

然而,我现在正在与更多的活动一起工作,我计划从MainActivity传递一个类的实例到另一个活动,然后再传回来。对于这个类,我应该新建一个.java文件(在MainActivity之外创建一个新类)吗?

如果决定将类定义保留在MainActivity中,可能会遇到哪些问题?

英文:

I'm wondering when it's not a good idea to implement a class inside MainActivity. Up until this point, I've only been using one actvitiy (Main) and so I've just been creating classes inside MainActivity.

However I'm working with more activities now and I'm planning on passing an instance of a class to another activity and back from MainActivity. Should I create a new .java file (create a new class outside of MainActivity) for this class?

What are some issues I could run into if I decide to keep my class defined in my MainActivity?

答案1

得分: 6

虽然这个问题的答案可能很基于个人观点,但是最佳实践是将 Activity 类保持尽可能简单和空白,这一点在 Google 的工程师和 Android 的倡导者在每年的 I/O 大会上已经多次强调过。创建一个架构,将功能委托给不同的类,将 Activity 仅视为入口点。模块化和抽象化代码将使理解和维护变得更加容易。

如果你具体询问缺点,那就是将不必要的复杂性添加到 Activity 中,使其变得不太易读和难以维护。当然,你可以将一个或多个类嵌套到 Activity 中,但为了更好地决定具体的编码选择,我建议你在架构设计模式方面获得技能,因为理解整体架构的大局也将帮助你做出较小的编码决策,比如何时嵌套一个类。

英文:

Although this question can be very opinion-based, the best practice, which has been preached several times by Google engineers and Android advocates in the annual I/O, is to keep Activity classes as simple and empty as possible. Create an architecture where functionalities are delegated into different classes, treating an Activity only as an entry point. Modularizing and abstracting your code will make it much easier to understand and maintain.

If you ask specifically about the drawbacks, then is adding unnecessary complexity into an Activity. making it is less readable and less maintainable. Of course, you can nest a class or as many as you like into an Activity, but then so that you can better decide on specific coding choices, I would recommend gaining skills in architecture design patterns, as understanding the big picture of an overall architecture will also help you to make smaller coding decisions, such as when to nest a class.

huangapple
  • 本文由 发表于 2020年10月16日 22:00:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/64390697.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定