How to achieve abstraction without using interfaces and abstract classes in java - abstraction

I was asked this question in one of my interviews and still dont have answer to it. If by abstraction we only mean , you not able to instantiate object(as applicable for interfaces and abstract classes), so having a private constructor is the answer?
Abstraction is explained in varied ways all over internet . Even using System.out.println is abstraction as we dont know detail behind it .
Using factory classes is also abstraction as we dont know which subclass will be instantiated.
Calling any method within an API is also abstraction.
I am actually confused now, as to what the interviewer wanted as answer.

Abstraction is all about hiding implementation, like how the gas pedal to a car abstracts you from the various complexities in making a car go.
A simple way of doing it is to just use private members. GetActiveServers() could call no private methods, or 5 private methods. That doesn't really matter when we're using it, so long as it works efficiently as needed.
I think he was trying to trick you because of the abstract keyword sort've means something different from abstraction, but it's not entirely unrelated.

Related

How can we mock private methods without using power mockito

Can we mock private methods without using powermockito. I know it is possible though powermockito but just wanted to check with all, is it possible by some other means.
Thanks
-Sam
By design, this isn't possible without PowerMockito or a similar tool.
See Mockito's Wiki where they give the following reasons:
It requires hacking of classloaders that is never bullet proof and it
changes the API (you must use custom test runner, annotate the class,
etc.).
It is very easy to work around - just change the visibility of
method from private to package-protected (or protected).
It requires
the team to spend time implementing & maintaining it. And it does not
make sense given point (2) and a fact that it is already implemented
in different tool (powermock).
Finally... Mocking private methods is a
hint that there is something wrong with Object Oriented understanding.
In OO you want objects (or roles) to collaborate, not methods. Forget
about pascal & procedural code. Think in objects.
There are of course cases where it is not possible to work around, but just take a step back and
Make sure that you are testing the correct things (should you be testing private methods instead of the public ones)
Consider just changing these methods to be package private instead of relying on PowerMock.
Yes we can use the Reflection API for this which provided by Java vendor.

are interfaces essentially additional abstraction layers? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Interfaces (interface/abstract class) are not abstractions?
My knowledge of interfaces is quite limited.
I'm trying to understand them better. What purpose exactly do they serve and when would it be advisable to use them?
Thanks
You are asking a question that fills multiple chapters of most OO text books. I think the best way to answer questions like these is to provide resources, so:
http://en.wikipedia.org/wiki/Interface_(Java)
http://livedocs.adobe.com/flex/3/html/help.html?content=04_OO_Programming_10.html#135768
Or your favorite OO programming book.
In a nutshell, implementing an interface is a little bit like extending a class, except that the interface does not implement the methods you inherent, your class must do that itself. Also, you can implement multiple interfaces. For example, I can create an abstract class Animal and then Flyable and Quackable interfaces. Now class Bat extends Animal and implements Flyable. Class Duck extends Animal and implements both Flyable and Quackable. Class DuckCall can also extend Quackable, etc. You can pass objects to methods based on their interfaces also.
In PHP at least, they're basically just a way to set some restrictions on your objects to make Polymorphism more manageable - that is to say ensure different type of objects can all walk like a duck.
In other words - just a way to programatically ensure your objects have certain members and methods, and throw an error if they don't.
The way I see it, interfaces are used in a similar way to electrical connectors: they define the signals that go in and out of a device so that you don't have to care what exactly is plugged in as long as it respects those rules.
For example, take an mp3 player and it's headphone jack. The engineers that build your mp3 player don't have to care what kind of headphones you will be using on it, and that is possible because of the jack interface.
They program your player against that interface, and then any type of headphones will work as long as they have the jack with the right size. They can even be speakers, they still work (isn't that cool?).
Furthermore, nobody forbids you to plug in something else in the jack socket, as long as it has a jack plug (it implements the interface). You are free to interpret the signals in whatever way you want, and you can for example build a device that changes color instead of playing music.
OOP interfaces work in a similar way: if you require an interface for the objects that are passed as parameter for a method, the caller can send you any implementation for that interface, and the objects that are sent can interpret the calls in their own way.

Any way to automatically generate QSharedData-based structures?

Qt has a build-in supprt for creating objects with integrated reference counting via QSharedData and QSharedDataPointer. All works great, but for each such object I need to write a lot of code: QSharedData-based implementation class with constructor and copy constructor, object class itsef with accessor methods for each filed.
For a simple structures with 5-10 fields this requires really lot of near same code. Is it some ways to automate such classes generation? Maybe it's some generators exists that take a short description and automatically generates implementation class and object class with all accessors?
You usually don't have to implement copy ctor or operator= when using QSharedData/Pointer. The default impls copy/assign the QSharedData-derived member, which usually does the Right Thing (TM).
For the public class, you need to implement the ctor creating the private object, and if the private class is not declared in the header but in the implementation (which is better), a dtor (doing nothing, the only point is that is not inlined and defined in the .cpp, after the private declaration).
For the private class, no method/ctor/dtor implementations are necessary.
For simple value-based classes, writing setters is of course tedious, but the same is true if you use plain private member variables. The overhead in LOC doesn't grow with the number of members.
And no, there is no standard generator solution for that I know of, although writing a script or emacs macro etc. doing it is not that hard. Probably would make sense to add such things to a publicly available toolbox, or QtCreator...
I don't think generators would exist for these things, but I suggest two things:
(ab)use existing shared containers (QVector, QList...)
read the documentation (with examples) on QSharedData, QSharedDataPointer, and QExplicitelySharedDataPointer
The two subclasses have simple examples that show how to implement the shared-ness it seems. I can't help you further though, because I've never had the need to create my own.
On second thought, why not make all data fields public, and use the QSharedData derivative as a struct-like class with reference counting? Maybe not nice on encapsulation, but if you're careful, nothing wrong should happen.

Single overloaded method at BLL layer vs BLL methods having one-to-one correspondence with DAL methods

Assume we create 3-tier module, which enables us to display/create/edit articles. Articles are:
• organized into categories
• before article can be published, admin has to approve it by setting Approve field of Articles DB table to true
• by setting MembersOnly field ( Articles table ) admin can also specify whether particular article can be viewed by anybody or only by registered users
• Articles table also has ExpiredDate field, which tells when will the article expire and thus no longer be published
a) At DAL layer we provide methods GetAllArticles, GetArticlesByCategory, GetPublishedArticles and GetPublishedArticlesByCategory for retrieving articles from the DB
At BLL layer we use GetArticles() overloads to call all of the above DAL methods.
What are the some of the benefits of using single overloaded method at BLL layer instead of BLL methods having one-to-one correspondence with DAL methods? Only advantage I can think of is that this way same ObjectDataSource control can call two or more of GetArticles() overloads, depending on the value of parameters, for example:
public static List<Article> GetArticles(bool publishedOnly)
{
if (!publishedOnly)
return GetArticles();
...
}
If you don’t also design UI layer and thus can’t be sure which methods UI programmer will prefer the most, would it be best practice for DLL layer to provide four overloads of GetArticles + GetAllArticles, GetArticlesByCategory, GetPublishedArticles and GetPublishedArticlesByCategory?
2) When designing DAL methods to retrieve data from DB, how can you in advance know/predict ( without first designing the UI ), exactly which methods (for accessing DB) we should create at the DAL layer?
Namely, in the previous example I’ve had several methods for retrieving articles based on number of parameters ( based on category they belong to, whether we only want published articles etc). Assuming I’m selling this module to third party UI developers, then there is no way to know which data access methods they would prefer the most:
a) so should I create as many data access methods as I can think of ( one for getting all articles that are already expired, one for getting all articles that are already expired, but were never published, one for getting all articles that are not published, one for getting all articles that can be view by registered users only… ) ?
b) Even if all three layer are written by myself – should I still create as many data access methods as I can think of?
thanx
EDIT:
A common way to achieve this is to use interfaces to define the behavior of the API.
a) I’m not sure I understand this. Which class should implement this interface? Perhaps DLL class? In other words, if the name of my DLL class is Article, then third party would derive class named ChildArticle from Article, where ChildArticle would also implement this interface? Or did you mean something else?
b) Anyways, as far as I understand it, providing interface ( which declares defines additional DLL methods to retrieve articles from DB ) would also require DAL class to already have appropriate methods defined, which would be called by methods declared in the interface?
To your point, I believe it is a good idea to prefer fewer coarse-grained methods in the BLL to cover all the functionality required by an entire business operation
I’m not familiar with this term, but you’re prob suggesting that we should prefer overloaded GetArticles() over GetAllArticles, GetArticlesByCategory, GetPublishedArticles and GetPublishedArticlesByCategory?
A) The design of an API is strictly related to what it is meant to achieve and by whom it will be used.
In practice, this means that you should know the target audience of your API, and give them only what they need to get the job done.
Unless I personally interview the people that would buy my product, I can generally guess which methods they would find useful, but within that space, there are still any number of possible methods I could define. Thus, how should I know whether they would also find use for, say, GetArticles() overload which retrieves articles that already expired?!
On the other side it is perfectly fine to have many smaller data-centric methods in the DAL to work with specific pieces of data.
If not DLL, should DAL have as many data access methods as I can come up with ( for particular target audience of course )?
SECOND EDIT:
A few extensibility points can be built into the API to obtain a certain degree of flexibility. A common way to achieve this is to use interfaces to define the behavior of the API. This will allow consumers to replace or extend the pieces of the built-in functionality by providing custom implementations.
Assume I create a BLL layer and then provide some additional interfaces, which consumers could implement to extend BLL’s build-in functionality. But for consumers to be able to implement these interfaces, they will need to have access to BLL’s source code, right? But what if I don’t want consumers to view BLL’s source code?
Interfaces should exist between layers. More specifically, classes should interact with classes from other layers exclusively through interfaces
a) So even DAL’s built-in functionality should be exposed through interfaces? But why? Namely, if we’d use abstract class instead of interfaces, then this class could already implement some utility functions common to all provider classes that inherit from this abstract class?! On the other hand, if DAL uses interfaces instead, then utility functions common to all providers will have to be implemented once for each provider, which could mean a lot of redundant coding?!
b) Anyways, I don’t quite see the benefits ( except when we provide interfaces with which consumers could extend the basic functionality ) in having classes from different layers interacting through interfaces?
For added clarity, instead of overloading methods to work with different parameters, I believe it is better to have one method that accepts a single parameter. This parameter would be an object containing all the data for the method to work with. Some of that data could be required, some could be optional and would influence the effect of the operation.
If I know UI will extensively make use Object Data Source controls, should I still prefer BLL to define a single method (this method having as parameter an object with all the data for the method to work with) instead of method overloads?
cheers mate
I took the liberty to summarize your post in two main questions. I hope I managed to capture the essence of what you are asking.
Q) What is the relationship between the intefaces exposed by the DAL and the ones exposed by the BLL?
A) The BLL is an outward-facing API, and as such it should implement functionality that is useful to the external consumers of the application and expose it in a way that makes sense to them.
The DAL, on the contrary, is a inward-facing API that exposes functionality to retrieve and persist data in way that hides the details of the storage mechanism being used.
In short, the DAL focuses on how data is being represented and managed internally in the application, while the BLL focuses on exposing data in way that is meaningful to consumers.
Q) How many methods should a public API have, and which ones?
A) The design of an API is strictly related to what it is meant to achieve and by whom it will be used.In practice, this means that you should know the target audience of your API, and give them only what they need to get the job done.
Since it is impossible to predict all the possible ways an API will be used, it is important to decide which main use cases to support, and work to make them really straightforward in the API. A good principle to keep in mind is what Alan Kay once said:
Simple things should be simple,
complex things should be possible.
A few extensibility points can be built into the API to obtain a certain degree of flexibility. A common way to achieve this is to use interfaces to define the behavior of the API. This will allow consumers to replace or extend the pieces of the built-in functionality by providing custom implementations.
To your point, I believe it is a good idea to prefer fewer coarse-grained methods in the BLL to cover all the functionality required by an entire business operation.On the other side it is perfectly fine to have many smaller data-centric methods in the DAL to work with specific pieces of data.
UPDATE:
About interfaces
Interfaces should exist between layers. More specifically, classes should interact with classes from other layers exclusively through interfaces. For example, the DAL should expose interfaces for the classes used to access data, like IOrderHeaderTable or IOrderRepository depending on the design pattern being used.
The BLL should expose classes used to execute business operations, like IOrderManagementWorkflow, or ICustomerService.
Note: common functionality inside a layer can still be placed in base classes, since in modern Object-Oriented languages like C#, VB.NET and Java a class can both inherit from a base class and implement one or more interfaces.
Also, external parties who wish to customize the built-in functionality by implementing any of the provided public interfaces can do so without needing access to the source code. Interfaces should however be self-describing and well-documented, in order to make it easy for extenders to understand its semantics.
About the BLL
The BLL should be explicit about the business logic it supports. Therefore it is generally a good idea to have methods that are directly related to business operations.For added clarity, instead of overloading methods to work with different parameters, I believe it is better to have one method that accepts a single parameter. This parameter would be an object containing all the data for the method to work with. Some of that data could be required, some could be optional and would influence the effect of the operation.
Implementation detail: this kind of BLL API is fully supported by ObjectDataSource control built into ASP.NET Web Forms.
About the API
An API should contain all methods the designer can come up with, within the scope defined by the use cases the API is intended to support.

What should i use : functors, interfaces or abstract methods when writing an abstraction(compatibility) layer? (D language)

For example: a compatibility layer between scripting objects (like strings, arrays) or scripting engines( eval() ,readFile() etc.).
Without more context, I'd have to say interfaces as well. Consider that you can represent a function or delegate as an interface with a single method and that abstract classes are just interfaces with some methods potentially already implemented.
That said, it really depends on what you're trying to accomplish. Interfaces lend themselves to cases where you have lots of objects with a common interface but potentially varying implementations. If you are, for example, designing a very simple callback system for plugins (i.e.: let the plugin hook certain events in the host application) then delegates are probably simpler and sufficient for your needs.
Also keep in mind that if you do go with interfaces, you'll probably need some way for the host to instantiate instances. The easiest way to do this is by registering a delegate with the host under some unique name.
Abstract classes are only useful if you want to use interfaces and provide a default implementation of some things. A better solution in that case is to have an actual interface instead, and provide the default implementation as a mixin.
Interfaces have my vote. That way, as long as you define the interface any developer will be able to write something compatible fairly easily without you having to distribute too much code to them.

Resources