OOP software design problem [closed] - oop

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
There are two classes:A and B.
And I need to implement a function whoViewed,
I have two options,make it an member function of A and B.Which smells a little duplicate.
Another choice is to make it a separate class:Viewer,but it's more abstract.
If you were me,which way will you choose?
To make it more general:
what will you do when you need to get statistic information across different classes(like get the latest viewed 10 entities{which can be A or B} from database) within the scope of OOP.

I would recommend not using inheritance and instead go with composition. Create a class called ViewMonitor which will handle the shared functionality. The odds are that there is no logical way to design an inheritance structure.

Obviously duplicating the whoViewed() method in 2 places is bad, so that option is off the table. You have a third option: Create a parent class that implements whoViewed() and have A and B inherit from it. The famous Gang of Four Design Patterns book recommends favoring composition over inheritance. So this would suggest making the Viewer class you mentioned in the question. Given the limited context provided in your question, I would suggest taking the GoF's advice and going with the Viewer class.
Incidentally, if you expect the implementation of whoViewed() to be different in A and B, you could make Viewer an interface and implement the interface in A and B.

if WhoViewed in A and B has the exact same functionality, make a class, from which they can inherit.
If the implementation of the method is different for both classes, of if they already inherit from another class, use an interface for A and B.

I would not suggest to introduce inheritance here, because it is serious decision, require that both classes to be truly polymorphic in all aspects.
In this case - make implementation in the third class, make this class a member of A and B, and then delegate call to the whoViewed method to this member.
In a pseudo code:
class C
{
WhoViewed();
}
Class A{
C m_C;
WhoVied{
m_c.WhoViwed();
}
In the B do the same as in A.
If speaking in OOD language - replace inheritance with delegation.

I would use composition and delegate to an external object. Your problem sounds like a cross cutting concern, hence AOP could be an option for you.
Depending on the language you could use Mixins (Ruby) or Traits (Scala).

This seems more like an AOP problem and should be solved using an aspect.
If you can think of the "who Viewed" as an aspect that you can then store the latest viewed 10 entities from database.
You would then intercept the calls to your entities and store the required metadata off in an easy to locate location.

if whoViewed() implementation is same for both then I would like to have a seperate helper class or an abstract class which is inherited by both A and B.
if whoviewed() implementation is ways apart write them in their respective classes.

Related

Having problems understanding OOP. Public members or getters and setters? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
i'm trying to learn OOP and i did read a lot of topics about OOP but I still don't fully grasp the concepts.
I'm asking for some clarification regarding that matter, in particular:
Is it fine to have public members in a class, or should I always use getters and setters?
OOP or Object Oriented Programing is a paradigm (method) of writting programs. Basically, it simplifies creating programs by considering everything as an object represented by classes.
The basic concepts of OOP (applies for all languages) are clear:
Inheritance: Object A (or class) is able to inherit from another object, let's say Object B. That means that Object A, in this case the child, will inherit the attributes and methods of object B which is in this case the parent. This concepts means that you can re-use your code.
Polymorphism: As the name indicates, it means than an object, more specifically, a method can take several forms. How? This concept goes with Inheritance. Say you have a parent class that is Animalthat has a method called talk() that prints some text, and you have two child classes respectively called dog and cat. Both child classes would inherit the method talk() from their parent class being Animal. Both dogs and cats are Animals, but they do not talk the same way. To solve this, we would re-define the method talk()in the child classes using the concept of polymorphism without needing to changing the method's name or signature.
Encapsulation: Last, understanding this concept should answer question 2 and 3. Basically, this means that each object or class will contain inside its own members (which provide data) and methods (which provide data manipulation). With this, what you are doing is binding the data with the methods in one container being the object. For example, let's take an Air Conditioner AC for short. An AC has attributes, let's say: make, model, isOn, temperature. Additionally, it encapsulates methods to manipulate the temperature: tempDown() and tempUp() to lower and raise the temperature by one degree.
What you need to understand here that, the AC's methods to lower or raise the temperature are already built inside it. It is not us people who lower or raise the temperature, sure we do press the button but that only triggers the method that does that. The functionalities themselves are build inside the AC not outside it, that is to say that the methods that manipulate the AC should be encasulated inside the AC. The attributes on the other side are supposed to be private by concept. The AC's attributes, for example the temperature, belongs to the AC itself, it should not be public. It is bad practice to set a class' attributes as public because it defies the encapsulation concept. And so only the methods encapsulated with the attributes should have access to them. If you need to edit the attributes of an object from outside the class, you can create a method that does that for you. Methods are public.
At last, regarding the use of getters and setters, there are a lot of debates about the subject, some even describe them as "Evil". If you create methods just to access the class attributes, you might as well just set them as public and spare yourself the extra lines of code. Some languages even have better ways to manage members like using properties in Python. Like I said before, attributes should remain private and should only be edited/accessed by the object itself, not from the outside. The way to do that is via the methods that will manipulate them. For example, let's say you have a bank account that has an attribute : balance. If you were to set the attributes as public or have getters/setters, it means anyone can access your balance from outside the class and change it to whatever value they like. On the other side, if you had the attributes private, the class decides what sort of data manipulations you can have via the methods. A method that would only print the balance, or that would only add money if it is extracted from another account, you can even add an extra layer of secury via logging each action inside each method.
You can add Abstraction (basically separating the declaration and implementation of code through interfaces) and Overloading to the mix. You can read more information here :
https://www.tutorialspoint.com/cplusplus/cpp_object_oriented.htm

Do I need an interface if there is just one implementation? [duplicate]

This question already has answers here:
Java Interfaces Methodology: Should every class implement an interface?
(13 answers)
Closed 7 years ago.
I have been doing OOP for a quite while and I got confused with usages of interfaces after an argument with a colleague few days before.
Basically, I have been using interfaces when I apply design patterns, especially when there are multiple classes implementing common features.
In my application, there is Hibernate layer and few Sevices classes as example UserService, CompanyService, etc.
The question was whether we keep, separate interfaces also for each Service classes. Such as UserServiceContract, CompanyContract and etc.
My colleague argument was, there is no need to have interfaces.
I came across that in this tutorial also, the author has used interfaces. But there is no common interface that implements several classes only once.
example interface implentation
The benefit of using the interfaces was in this situation, it improves the code structure. Yes, there is IDE features that show what methods available for a class. But, I still want to get your guys idea too about this.
When you are talking design patterns and best coding practices, needing is not what you should be asking yourself. You do not need most of what you do, at least not immediately. Of course you do not know whether you will need different implementations of that contract until you actually do. So this is not a question of what you need right now. This is a question of what you will wish you had later.
What you have seen in the link you posted is the D in SOLID: the Dependency Inversion Principle:
Depend on abstractions, not on implementations.
You are better safe than sorry, you know.
EDIT: Also, I would advise against sufixes for interfaces (or prefixes). If you will be using the interface instead of the implementation, make the interface's name clean. A common choice would be, in your case, UserService for the interface and UserServiceImpl for the implementation.

Interface and Baseclass can be combined together? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
After reading Interface vs Base class I understand that Inheritance should be used where there exists a "is-a" relationship and interfaces should be used in "can-do" kind of places.
If that means, base class can only have business objects and interfaces will have only the contracts?
For e.g Dog class will have a base class Animal with properties like Eye,Nose,Leg etc and interface IAnimal will have "Run", "Jump" etc.
Will design applicable for all the scenarios?
The answers on that question you linked actually say it all. Especially the accepted answer and its first comment. You use an interface to declare the contract and a base class for shared implementation.
I'd consider it a common practice to define interfaces for (almost) everything. An interface can also contain getters and setters and therefore define its subtypes properties. If two or more classes that implement that interface share some implementation, you can moved that to a base class. That base class would then also implement the interface.
Your understanding is correct, but I think it relies more on good practices than actual language rules. Please consider the following:
In languages that support multiple inheritance (C++) interfaces are just classes with all methods virtual and abstract. See this question
Languages that don't allow multiple inheritance (Java), the most important difference is that a class can have no more than 1 superclass, but can implement an arbitrary number of interfaces. There are also differences in declaring variables (variables are implicitly static and final in Java interfaces) but it's still not a big leap to think of interfaces as of 100% abstract classes.
Java 8 introduced default methods (see this question), which can kind of blur the obvious distinction between those two.
So while technically it's not true neither that interfaces must only define the contract (default methods can implement a fallback behavior in a Java 8 interface) nor that abstract classes must define behavior (because a pure abstract class with no implementations can exist), the approach that you described is kind of reasonable and common in real world.
It depends.....
That's a good starting point but it is not right to say that it will be applicable in all scenarios. Systems keep changing and as part of refactoring (http://refactoring.com/catalog/) sometimes interfaces become subclasses and the other way round. Interfaces are good for Mix-ins which you mention as "can-do" kind of behavior and Inheritance where a group of classes share certain properties and possibly some behavior enabling reuse and avoiding code duplication (which is essentially what a IS-A relationship is). You can read more about it in Effective Java by Joshua Bloch (there is an item on Interfaces and Inheritance).
If we take your example, the methods "Run" and "Jump" can be either defined in Animal base class or they can go in an interface as you mention, in fact they can actually go in multiple interfaces too. So you might start off by building a inheritance hierarchy and later refactor them into interfaces as the system evolves.

What are the pros and cons of creating a new class? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
This is a probably a very basic question, but it's one I'm actually running into as I'm learning more about Actionscript 3 in particular. However, my first question is very general: When is appropriate to put functionality in a new class rather than a new function in the same class? According to this Java tutorial, which focuses on basic object-oriented principles, a class is supposed to be a "blueprint of an object". I always understood this to mean that any functionality or behavior that the object would use should be contained within the class. However, according to the single responsibility principle, each class should have only one reason to change. For example, you should have one class to compile a report and one class to print it rather than a single Report class.
Can you guys help me understand the pros and cons to creating a new class? What are the costs to splitting an object into multiple classes? Are there compile-time or performance costs for keeping related functionality in the same class, or for splitting it into two? Are there perhaps times that you would want to split things out, while you might want to keep them together other times?
As far as I remember, there isn't a big difference between having 1 class which can do everything or several classes which can do the same.
It's about readability and how you can extend the code. It's also just about clean code and coupling.
If you have a class called "Printer" you don't want to have "WaterCoolerSound()" in it. Of course the more objects you have the higher the chance is that you can run out of memory. But I am not entirely sure whether one object with all functionality or several classes with the same functionality spread out, takes more memory.
In fact, you could say that if you JUST need a little bag to hold on to some data and not be able to dance like a bear at the same time, it would make sense to have two separate classes.
It's advisable not to think about the performance before you have the code. From the maintainability and understandability viewpoint, of course, smaller classes, with smaller methods are superior. (see The Single Responsibility Principle again :)
Don't get so confused about making classes for just a function. A class should have only related functions.If the functions are of different kinds which will do totally different functionalities and use totally different kind of variables then only u should make a separate class.

How should I document a inherited members? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Consider that I have a complex class structure where many elements inherit from other elements. I may have a method GetStuff(string stuffName, int count) defined in an interface, which is inherited by other interface, which is then implemented abstractly by an abstract class, which is then implement explicit in a concrete class etc. etc...
How should I handle inherited members such as GetStuff() when documenting my code with XML comments which will be used with a tool such as Doxygen or Sandcastle? It seems wrong to just copy and paste the same description at each level. Should I be considering a different audience at the interface level vs the concrete class level? For example the documentation for GetStuff() at the interface may consider people implementing the interface, whereas the documentation at the concrete level may instead consider people who will be using the class?
Document the interface method according to its code contract. Do not comment on its implementation, only on its semantic purpose, i.e. what it’s supposed to do, not how. The audience for this documentation is both your implementors and your users: the method will both be implemented as well as called.
Document the abstract method simply by saying that it implements the interface method and linking to it. There is nothing extra to be said about it, and duplicating the comment violates the DRY (Don’t Repeat Yourself) principle: you would have to remember to make any change to it in both places. (Of course, in the case of an abstract method that doesn’t implement an interface method, document it in the same way that you would document an interface method.)
Document the concrete implementation by saying that it implements the interface method and/or that it overrides the abstract member. Optionally add information about its implementation if it is relevant to the caller — for example, its performance characteristics, or situations in which it might throw, etc.
remark
on part of post
by Eric Anastas
It seems wrong to just copy and paste
the same description at each level.
I can imagine it being wrong to just copy. It is however possible to let doxygen copy it for you and then change what you would like to change for that implementation/scope.
For more information, you can look at the description for #copydoc.