What would be the correct design here (encapsulation, polymorphism, inheritance)? - oop

Assuming I have an interface and 3 or 4 classes that implement the interface. Now let's say I have another method but it is relevant only for one or two implementing classes.
So as I see it there are two approaches
Declare the method in the interface, implement in all the classes. In classes that the method is not relevant - throw "not supported" exception.
Declare the method only in the implementing classes where relevant but then you have to downcast the instance from interface type to the specific type in order to call the method.
So would be your design here and why?

You should apply the interface segregation principle here, part of the SOLID principles. Instead of having one large interface, split the interfaces up into a few smaller interfaces. Implement the interfaces only in the classes that need it.

I would choose a parent interface. Make the classes that satisfy the interface implement that interface. Create a second interface that extends the first one and adds the extra methods and then make the remaining classes implement that interface. You would still be coding to an interface rather than an implementation and all your design principles are satisfied.

Ask yourself this, will the object that consume the interface necessarily expect this function to be there? Is it important that no matter which instance of the interface you pass, you'll still have that method available?
If the answer to that question is yes, 1. If no, 2.

Related

Kotlin: Interface whereby the implementor must be a data class?

Is there an Interface that I can extend or some other way to create an Interface whereby the implementing class must be a data class? It would be useful to have access to the data class API methods such as copy().
No, copy method have unique number of parameters for every data class, so it's useless to have such interface. If all your data classes have same field - just create and implement common interface.
So I'm going to preface my answer by saying I don't have experience with Kotlin, but I have plenty of Java experience which as I understand it is similar, so unless Kotlin has a feature that helps do what you want that Java doesn't, my answer might still apply.
If I understand correctly, basically what you're trying to do is enforce that whatever class implements your interface X, must also be a subtype of Y.
My first question would be Why would you want to do this? Enforcing that X only be implemented by subtypes of Y is mixing interface and implementation, which the exact opposite of what interfaces are for.
To even enforce this, you would have to have X extend the interface of Y, either implicitly or explicitly. Since in Java (and presumably Kotlin), interfaces cannot extend objects, you have two options:
1) extend the INTERFACE of data, if it exists (which I don't think it does given what I've been reading about data classes. It sounds more like a baked in language feature than just a helpful code object)
2) Add to your interface the exact method signatures of the methods you want out of data classes. BY doing this, you've gained two things: First, you get your convenience methods whenever a data class implements your interface, and second, you still have the flexibility that interfaces are meant to provide, because now even non-data classes can implement your interface if you need them to, they just have to be sure to define the data classes interface methods manually.

Can i use inheritance instead of implement an interface in strategy pattern?

From a picture, Can i use inheritance instead of implement an interface?
I mean change from "ConcreteStrategyA and ConcreteStrategyB implements Strategy Interface" to "ConcreteStrategyA and ConcreteStrategyB extends Strategy Class"
Is it still work well or have some problem?
If it still work well my next question is "Why most people prefer to use interface?"
Well technically from a Design pattern perspective with the Strategy pattern, the concrete Strategies need to implement (I mean write code for, not the interface implements thing) a common contract which the Strategy Context is aware of. This is the primary backbone of Strategy pattern philosophy. The adherence to the common contract is what allows the Strategy context to replace the concrete strategies based on some runtime feature. This pattern ideology is what we loosely call Polymorphism in OOP parlance.
Now in Java you can implement his polymorphic strategy either as an interface or as inheritance. For interface you have given the example in the question itself. For inheritance as long as the contract holds between subclasses (something like a base abstract class with an abstract contract which subclasses implement to provide concrete strategy implementations) you can implement Strategy pattern in inheritance as well.
Now thinking about it from OOP perspective. For OOP inheritance is something which a subclass inherits from a super class. The subclass automatically owns and thus demonstrates that inherited generic behavior but it has a choice to make that behavior more specific to its own type. Thus multiple subclasses can override the same behavior and make bits of it more specific to their use. But this chain becomes cumbersome to manage when it gets too long or when subclasses try to inherit the behaviors which don't apply to them logically.
Thus it makes more sense to implement Strategy pattern using interfaces as against inheritance.
Absolutely. Inheritance is most often used with an abstract base class, when you want your derived strategies to share some common code.
People prefer to use interfaces or abstract classes over concrete base classes because :
With a Dependency Inversion approach, a class needs loose coupling to its Strategy. It only needs to know that the Strategy fulfills a contract, but doesn't want to know about its implementation details. Interfaces and abstract classes are an elegant and minimal way to define a contract without specifying the implementation.
It doesn't make sense to instantiate the base Strategy class most of the time, because it's a general, abstract concept -- in fact, it's better if you forbid instantiating it.
There are no technical problems.
However, a class can only extend one base class but it can implement multiple interfaces. So if you want to, let's say, change your inheritance structure in the future it is easier if you choose to implement an interface instead.
As you know a design pattern is "a general solution to a commonly occurring problem". It just describe a general solution without indications concerning implementation details.
If your problem requires a class in place of the interface, there is nothing wrong replacing it with a concrete (or abstract) class.
Using an interface in the pattern UML is a way to say: "you have to expose this set of public methods".
So, no problem using your approach. As an alternative you could leave the Strategy interface and implement it in a StrategyImpl class, then you can inherit this class in your ConcreteStrategyA and ConcreteStrategyB classes.

Is it good practice for every public method to be covered by an interface?

It's good practice for a class' implementation to be defined by interfaces. If a class has any public methods that aren't covered by any interfaces then they have the potential to leak their implementation.
E.g. if class Foo has methods bar() and baz() but only bar() is covered by an interface then any use of baz() doesn't use an interface.
It feels like to get cleaner code it would make sense to either:
create extra interfaces if the class has to have those methods (eg a separate interface to cover the behavior of baz() above)
or ideally refactor (eg using more composition) so the class doesn't need to have so many methods (put baz() in another class)
Having methods not covered by an interface feels like a code smell. Or am I being unrealistic?
I consider it as "overusing" the interface.
Interface can give you access only to limited functionality, therefore it is good for gathering more classes with similar functionality into one List<Interface> and using them, for example.
Or if you want to keep loose coupling principle, you rather give another component some interface than the whole class(es).
Also some classes should have restricted access to another classes, which can be done with interfaces too.
However high cohesion principle (which is usually connected to loose coupling) does not prevent you from using class itself, if two classes are and should be "strong" connected to each other.
I don't think that's the purpose of interfaces. If you actually talk about the 'is-a' and 'has-a' relationship between classes, not necessarily a class needs to cover all public methods in interfaces. That's like taking the concept too far.
A class can have methods which describe it's behavior but then, there are some methods that do not exactly describe the classes' behavior but rather describe what else the class can do.
In case if a question arises about SRP regarding the 'can-do' behaviors, it is possible that the class can use a component to execute those behaviors rather than implementing within itself.
For e.g., I have a class DataGrid, why would I need to have an interface called IDataGrid which exposes all the public methods. But may be there is an additional functionality that the DataGrid can do, which is export the data. In that case I can have it implement IExportData, and implement the ExportData method, which in turn does not export the data but uses a component, say DataExportHelper, that actually does the job.
The DataGrid only passes the data to the component.
I don't think SRP will be violated in the above example.
EDIT:
I am a .Net developer, so would like to give you and example from MS library classes. For e.g., the class System.Windows.Window does not implemnt any interface that has Close() method. And I don't see why it should be a part of any presenter.
Also, it is possible that something might look seem like a code smell but not necessarily it might be wrong. Code smell itself does not mean there is a problem but that there is a possibility of problem.
I have never come across any principle or guideline in software design which mentions that all the public members of a class need to be exposed in some or the other interface. May be doing that just for the sake of it might be a bad design.
No, I would definitely not consider methods not covered by an interface a code smell.
It seems like this might be dependent on the object infrastructure you are building in, but in the infrastructures I'm familiar with, the real point of interfaces is to provide a manageable form of multiple inheritance. I consider the overuse of multiple inheritance a notable smell.
In .NET at least, abstract classes are explicitly the preferred construct for exposing abstraction (not interfaces). The .NET design guidelines say: Do favor defining classes over interfaces., with rationale described here http://msdn.microsoft.com/en-us/library/vstudio/ms229013(v=vs.100).aspx.
Even in COM (where any externally visible functionality had to be defined in an interface) there are perfectly good reasons to have non-exposed functions: limiting the visibility of implementation details. COM was originally defined in C (not C++) which lacked the richer set of access modifiers that newer languages have, but the concepts were there: published interface members were public, everything else was internal.

Are interfaces redundant if using abstracts as an interface?

I'm reading through Design Patterns by GoF and I'm starting to wonder. Are interfaces redundant if you're using an abstract as the interface in languages like C#? Let's put multiple inheritance aside for a moment, as I understand you can only achieve that (in C#) through interfaces.
I'm trying to apply this logic to DDD in C#. Almost every example and implementation I've ever seen uses interfaces. I'm starting to wonder why. Could the abstract class be used instead? It seems to me that this would be a more robust solution, but then again I could be missing something, which is why I'm asking here.
Summary:
Question 1: In the context of OOP with a language that only supports single inheritance, if designed properly what are some uses
of interfaces over the abstract class?
Question 2: In the context of DDD, if designed properly what are the uses of interfaces over the abstract class?
Note:
I've read through all the similar questions listed, but none seem to give me an answer. If I missed one, please let me know.
For question 1: regardless of support for multiple inheritance interfaces are contract specifications, abstract classes are base classes.
Interfaces provide a way for a class to specify a set of capabilities ( think IDisposable, IEnumerable, etc ) and it's recommended that they obey the Interface Segregation Principle.
Abstract classes should implement a concept that can be extended, or that can have different implementations depending on the context ( think HttpContextBase, AbstractButton etc ).
The biggest difference between interfaces and abstract classes is conceptual. You can argue that, except inheritance, an interface is the same as an abstract class with only abstract methods, but conceptually they represent different things.
As for question 2: in the context of DDD interfaces are implementations details. I dare say you can do DDD and not use interfaces or abstract classes, or even inheritance. As long as you have your bounded contexts, aggregates, entities and VOs well defined.
In conclusion, when you try to express a contract use an interface, when you want to indicate that your class has some capability, implement an interface. When you have a concept for which you can provide more implementations depending on context, use a base class ( abstract or not ).
When you think about it like this, the decision of the language makers ( c# ) to allow only single inheritance, but allow implementation of multiple interfaces makes a lot of sense.
The advantage of Interfaces is precisely that there is no multiple-inheritance. By using an Interface you can allow classes like Forms, UserControls, Components, etc to participate in interactions that would otherwise be diffucult/impossible.
I recommend doing both. I usually create an interface, and (if possible) then create an abstract class that inherits that interface to provde any common or default implementaion of that interface. This gives you the best of both worlds.
interfaces are not redundant. an interface is independent of implementation while abstract classes are implementation. code that uses an interface does not have to be changed or recompiled if some implementation class changes.
the advantage is above. if you are doing ddd, start out with concrete classes and write some tests. refactor common stuff into base classes (some will be abstract). if there is a reason to make an interface go ahead and do so. repeat until done.

Interface uses as like this

If interfaces have empty methods (implicit abstract method) then what is its use? Why do we say it reduces the code and provides re-usability? Give me a real life example of using an interface that shows the difference between an abstract class and an interface.
Interface is more like a contract. It doesn't provide any implementation reuse as such. Which actually makes your code de-coupled from implementation. Having a abstract class with ALL the methods abstract provides the same benefit (if we ignore the issue of multiple inheritance).
For a really good example take a look at Java Collections and how things are loosely coupled using interfaces for Collection, Map and Lists.
Because of the terminology you are using, I am going to assume you are talking about Java.
An interface is useful in lieu of an abstract class because a class can only inherit from a single class, but can implement multiple interfaces.
An interface is a contract between parts of the program. It says that one part of the program has certain expectations about classes that implement this interface. As long as those classes uphold that interface contract, the other parts of the program don't care how that contract is implemented, just that it is implemented.
It allows for polymorphism and for the reuse of code. For instance, (with respect to Java), you can take the List interface. You can write code that interfaces with a List object where you don't care about the implementation of the List. Your code then can be used with a LinkedList or an ArrayList or any other type of list that it may deal with, and it should be able to manage well enough. You can write code now that has certain expectations through this List interface contract, and 15 years down the road someone can use the latest technologies to create their own List implementation and your code will be able to use it.
Abstract class lets you describe fields and non abstract methods. It does not limit you to simply describing interface, it involves some logic. Interface on other hand does what it says and has nothing to do with logic. From client code side, you have no worries about implementation and how stuff works. It lets you exchange one interface realization with other without additional code.
On realization code side, interface lets you perform multiple "inheritance".
I like to call these types of features "implied code documentation". Using an interface can communicate a lot of information to other developers who will be working on your project, and this information can help prevent a lot of headaches.
For instance, if a class implements an interface that has 2 methods, and I'm new to the project, that may tell me that the developer who wrote those methods don't want the method signature to change.
Think about the Dog class and the Cat class that both implement the interface Sociable, where there are methods walk(int speed), sit(), layDown(), bite(int degree).
If we have a Dog class and a Cat class that implement these methods and there are dependencies on them, changing the method signature of one could have some negative effects.
Interfaces are a way to help describe a class. In this example, a Sociable Dog and a Sociable Cat have a lot in common.
As far as reusability goes, your classes become reusable because it's harder for others to come in and change the contract defined in the method signature.
Lastly, while a class can only subclass one class, it can implement multiple interfaces. Thus, the advantage of using an interface is that I can have a Dog that implements Big and Sociable, and a Cat that implements Small and Sociable.