Our project requires us to interact with multiple sources for information like Oracle DB, SalesForce, etc. So we want to wrap all the calls under a WCF layer, so that anybody inside the company can use it. For implementing the Domain Objects, this is a consideration:
public class NoteTypeA : INote, INoteTypeA {}
public class NoteTypeB : INote, INoteTypeB {}
public class Customer : INote, ICustomer {}
All the Note classes such as NoteTypeA, NoteTypeB, NoteTypeC all would inherit from INote, however they also would Inherit from INoteTypeA, in the case of NoteTypeA.
I agree with the idea of using INote as it helps you implement Multiple Inheritance. But I don't get the reason behind using INoteTypeA and its looks like anti-pattern for me.
What do you guys think?
Does that protect me from a future change?
Does it help me smoothly add an out of scope change?
I think will be largely subjective and depend on the implementation.
I usually don't make interfaces for my classes if they are just data containers, but if they have business logic functions, then I do.
Related
I'm creating an API where MANY objects share MANY functionalities.
My primal instinct is to use inheritance however they do not strictly adhere to "is-a" type relationship - it's only the "functionalities" that are shared. For example, it is not engine->turbo_engine, engine->combustion_engine type relationship. Loosely speaking, it's more so brand->car, brand->plane.
Inheritance is convenient because brand obj has useful functionality such as company name, etc. that are useful in many classes. Inheritance makes it easy to expose functions of the brand class. However, I'm afraid to use inheritance as it would make everything strongly coupled. Likely leading to fragile base class issues in the future.
My concern with composition is having to manually write MANY wrapper functions to expose public methods of the brand class in the above example (is that a valid concern?). To make it easy to expose functionality, I used std::function and std::bind.
Below is a dummy code showing my approaches.
With inheritance (with this approach, I would have to do multiple inheritances)
Class Identity //Stores name, id and has functions such as Get/SetName, Get/SetId, etc.
Class TypeA : Public Identity
Class TypeB: Public Identity
...
My solution with composition (to avoid copying code/writing wrapper functions):
Class Identity
{
int GetId(){}
}
Class TyepA
{
Identity identity_;
std::function<int(void)> GetId;
TypeA():
GetId(std::bind(&Identity::GetId, &identity_))
{
}
}
Can you please share your thoughts on this? I'm inexperienced with large software designs so I'm struggling to start off on the right path.
Thank you!
I want to use inherited types in WCF ,but i dont want to add KnownType attribute of all types in the base class, because the base is in another assembly ,also to avoid dependencies.
So, what are the other way to achieve that?
I think there are at least two ways to do this.
You can create your own classes (DTO) and map data from other assembly to your classes. For mapping you can use AutoMapper. It has following advantages:
Your communication layer is separeted from your logic (I'm assuming that this other assembly contains logic)
You will decide how your API looks like and your protocol will not change without your knowledge (I'm assuming here that this other assembly is a library or someone else is responsible for it).
You can add ServiceKnownType to your ServiceContract interface more or less like below (I did not test the code):
[DataContract]
public class BaseClass {}
[DataContract]
public class DerivedClass : BaseClass {}
[ServiceKnownType(typeof(BaseClass))]
[ServiceKnownType(typeof(DerivedClass))]
[ServiceContract()]
public interface IYourContract
{
[OperationContract]
BaseClass[] GetClasses();
}
For more information check out documentation here. There is really good example.
Which is beter?
It depends on what you need. If your are developing prototype or you need to do something fast go for option 2. If you need more reliable solution, that will stay with you longer choose option 1.
There are more ways of specifying the known types. One of them is to put them in your configuration file. That way your service doesn't know about them at compile time. But in order to serialize them, it has to know about them at runtime.
I quite often find myself creating interfaces that I am using just at the signature to inject a dependency, ending up with class AIface and class AImpl : public AIface. And quite often I never implement any other subclass of class AIface
Is there any advantage of this approach vs using directly the implementation with all public method virtual?
Longer Explanation:
Say we have a zoo with a cleaning service. We do TDD, and we want to be able to test the Zoo with a fake FeedingSvc, so we go for dependency injecton.
What is the difference between:
class FeedingSvcIface{
virtual void performFeeding() = 0;
} ;
class RoboticFeedingSvc: public FeedingSvcIface{
void performFeeding();
};
Class Zoo{
Zoo(FeedingSvcIface&);
//...
};
vs
class RoboticFeedingSvc{
virtual void performFeeding();
};
Class Zoo{
Zoo(RoboticFeedingSvc&);
//...
};
(And if ever needed, extract the interface in the future)
In terms of testing, the former seems easier.
I usually find natural to add interfaces when there is a I speak to a class that "crosses layers" but some times it is just about testing.
I know that in the future I might have to implement other types of FeedingSvcs but why doing the abstraction today if I don't really needed?,
I might split two classes just to encapsulate some logic.
The advantage of sticking to best practices, design patterns or other idioms is that although you make a bit of extra effort now, you gain more in the long run.
Imagine the scenario where you work in a team, with multiple developers, some experienced, some not.
You are the creator of the Zoo mechanism, but you decide, that for the time being, you will implement the Zoo on a KISS principle without adding the extra abstraction . You set yourself a mental note (or a even a nice little comment) stating that "If there shall be multiple distinct behaviors of the RoboticFeedingSvc there shall be Abstraction over the dependency injection !".
Now , because of your really awesome work, you get to go on a vacation and some junior developer will remain to mantain your code.
One of the tasks of the developer will be to introduce a ManualFeeding option and a hybrid option. How many ways to do this can you think about (with disregards to any coding principle) ?
Because you, the creator, didn't enforce the way the mechanism grows, the junior developer will look at your comment, add a "LoL u mad bro :) " comment , and then choose one of the following :
Create a base interface to be derived by other FeedingSvcs (you got lucky here)
Create a dependency injection to the RobotFeedingSvc using a strategy pattern (have some functors to be set in terms of how to feed something)
Make RobotFeedingSvc a composite between Feeder, Feeded, and some Action function
Make the RobotFeedingSvc a singleton factory (because singletons factories are awesome and fancy ) that somehow is used inside the Zoo to return the apropriate feeding technique (important thing here is that he used singleton and factory)
Create a templated version of the Zoo that takes a templated version of RobotFeedingSvc that is partially sepecialized according to given FeedingPolicy and Feeder (because he just bumped into templates, and templates should be used everywhere).
I guess we could sum up the story in fewers lines :
Making the initial effort to properly make the abstractions layer required in your application to make it scalable in terms of functionality will help other developers (including here future you ) to quickly understand the proper way to implement new features using the existing code instead of just hacking through it with some wild ideas.
Forcing your Zoo Class to take an interface instead of a concrete class is pretty much equivalent to leave a comment saying that new functionalities need to implement this interface.
Allowing a concrete class to be passed as parameter might switch focus on how to change the concrete class rather then implement something on top of it.
Another more technical reason would be the following :
He needs to add new functionality , but he's not allowed to change the Zoo implementation. What now ?
I have a class A which has public methods and used by 100 other classes implemented in different applications. Now I want to make those public methods as private so that no new classes access them, but I want the existing client classes to still access them.
But I don't want to even touch those client classes , because the owners seldom allow even any ripple in their classes.
I checked
Can I access private members from outside the class without using friends?
C++: Is there a way to limit access to certain methods to certain classes without exposing other private members?
friend class with limited access
But all ( not all really ) demand a change in the client's code. The client code should not change.
One straight forward way is to make all those N classes friends , But I am somewhat not comfortable doing that. Is there any pattern or an acceptable technique ( not a hack please ) to achieve this access restriction?
Thank you and I apologize if this is a duplicate.
Classes in C++ are made friends in order to indicate an special intentional strong coupling between classes. This use of friend infact enhances Encapsulation rather than break it as maybe the popular feeling.
How?
Without friendship the only non-hack way to expose the functionality to other class would be to provide public, get and set member functions,this in fact breaks encapsulation because all classes(even those who don't need to) now have access to these methods and hence the members increasing the risk of potentially breaking down the class data.
Back to your situation, If you have a 100 classes which need access to this particular class, then you already had the right design in-place by having those methods as public. Now trying to make those methods private to future classes is a trying to hack your existing design, Your design does not support it.
Making the existing classes as friends does not ideally fit in the above mentioned criteria and hence is not a good choice for the scenario.
However, given the situation there is no other way in which you can implement this. Making the existing classes as friend and granting them the special access seems the only way. This is still bad because the 100 classes which only had access to the few methods will now have access to your entire class.
I think you can extract an interface of the A class (let it be IA) and make A to implement IA. You should not define those public methods in IA at all.
Then, old code will continue using A and will have access to A public methods, while new code will use restricted interface, that code would receive through some fabric .
Of cause, this can be unimplementable, if you need to (copy-)construct class, or smth like this, but I can't say it now without knowing the usage of class.
Also, you get a little overhead due to virtual functions
I am using bada and refer to the tutorial here, which begins:
class MainForm:
public Osp::Ui::Controls::Form,
public Osp::Ui::IActionEventListener,
public Osp::Ui::ITouchEventListener
{
I am running code where I recently removed the public specifier to cut down on my public API. You'll see that the functions implementing those interfaces where all also declared publicly, for which I saw no need and made private. I would do this without hesitation when implementing my own interfaces when those interfaces may provide more access than I would wish regular clients of my concrete class to receive.
What is the reason for making them public, what am I missing?
I guess it is advocated to aid extensibility, but for a dev making apps not libraries I would challenge this wisdom.
If Form, IActionEventListener and ITouchEventListener already support many usable methods, in most cases why hide them? On the contrary: if you hide them and in the future someone will need them, it will be harder for you to maintain the class because you'll need to provide them again.
If you need to hide the parent's methods, there's another way to do this: instead of inheriting, enclose the "parent" as a field in your new class.
In some languages such as C#, public inheritance is the only option.
For me private inheritance of "interfaces" is a non sens.
The interface of an object is its set of public methods. As llya said, if you want to use the functionalities provided by a class internally, use object composition. If you want to provide a subset of the interface, then either compose or simply declare a more restrictive interface.
If the "interface" and the functions taking object from this interface are in a third party library then its means that the developers wanted to force you to implement every methods, so you have to provide them.