Search code examples
javaabstraction

Why Use Abstraction?


I was recently told that I should use abstraction more in my code. I am fairly unfamiliar with the matter, and in research I have found a lot about abstract classes but I am referring more to the "information hiding" portion, not the function in the code itself.

For example, if I have one class which performs a unique purpose, why would I want to create an abstract version for that class to implement? I am having trouble figuring out when to use abstraction and for what purpose, how does having essentially the same class without method bodies change how it is used? Is it mostly for when other people work with the code, and if that is true, should it still be done in more private projects just as good practice?


Solution

  • Abstraction is a more general notion in programming than declaring classes as abstract.

    Abstraction is related to separation of concerns, and basically involves encapsulating details of implementation away from higher level, or more abstract code.

    For example, I may have a user object, persisted to a database, and want to check to see if the user has some flag set to true in order see a button on a view.

    I could, in my view code, get a db connection, run a sql query, deserialize the results into a user object, and check the flag, but I haven't separated my concerns. My view code knows lots about how I persist data, how to take a resultset and turn it into a user, how to get a db connection, the db structure, etc...

    Instead I should abstract away those details, so the view layer can just get the user from something and check the flag. The something can know the details of the database, and may even delegate some of those details to lower level components.