简体   繁体   中英

OOP in Android/Java

I am currently developing an flashcard-app for on reason because i don't like the existing ones and the second reason is that i want to improve my java/android skills.

In my app i tried to use OOP. My Cards are stored in a sqlite database.

Now my question: Currently my Object "Card" which represents a single Flashcard has its own DatabaseAdapter which it can use to update its own state ie its points.

 Card card = new Card();
 card.setPoints(10); //<-- Also update its row in the database

Or is it better to do something like that:

 DBAdapter dbAdapter = new DBAdapter();
 Card card = new Card();
 dbAdapter.setPoints(Card);//<-- Updates Card and Database!

What do you thing is better?

Thx in advance!

What you have done in the second example is not advisable as you are creating a side effect. Updating the database is also updating the card, which is wrong. Updating the database should do one thing,and that is to update the database.

I would prefer the first method as the Card knows how to update itself but you are also doing the same mistake of updating the database. Let the database know how to update itself, and the card know how to update itself. I think it achieves a clean separation of concerns.

For example:

card.setPoints(points)//update card and only card
dbAdapter.setPoints(card) //update the database and nothing else.

Definitely the first one. The class which is setting the points should have no knowledge of how the points are set (or stored). It's a "separation of responsibility".

Imagine in the future if you decide to change from a database to an ACME Dilithium Crystal Accumulator(TM). How much code would need to change in option 1 vs option 2?

I guess not both.

 dbAdapter.update(card.getId(),card.getPoint());

Syntax should be

  public boolean update(int id, int value)

Your DbAdapter should have only methods which store or retrieve, delete data they should not be specific to card functionality.

In above example card.getId() returns URI associated with Card and then it just updates integer value so your code has separation of responsibilities and isolation.

If both of the above mentioned code snippets work, I would prefer the first over the second, because the code seems more readable, intuitive and is shorter!

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM