I am encapsulating access to a database in connection classes that all inherit from the same base implementation. This base implementation has a protected LINQ provider for database access that many child classes will use - but not all of them. Some might need their own provider and would then generally have no use for the "default" one.
This "other" provider would not be derived from the default one (but share a common quasi-abstract ancestor which in itself is of no use anywhere), but would have exactly the same role within the respective class, so it would seem nice to be able to use it in exactly the same way, i.e. use the same syntax. I could achieve this by hiding the respective members using the new keyword, but I'm unsure whether this is good practice.
On one hand, doing so would help avoiding accidentally using the wrong one because there is only one. On the other hand, being used to using the same name for the default and specific providers might lead to actually forgetting to implement a specific one and working with one that's not correct to use here. So it might make sense to name the default one appropriately; whoever will be developing a particular connection class will know when they need to use a specific provider and be reminded that they need to create the code to get to that.
Which reasoning is the more plausible one? I'm now leaning a bit towards the latter.
The new keyword is almost always a bad idea. It's one of those "last resort" features for cases where you have no other option, and in this case you definitely have other options.
Do the two providers have different semantics/APIs, or is the usage exactly the same? If the latter, you might want to look into the adapter pattern, and implement the property as a simple virtual property of type ILinqProviderAdapter (which you would define and implement), overriden where appropriate.
Related
This issue comes up for me so often in my coding that I'm astonished I can find so little reference to it, and would value other people's thoughts and ideas.
I define lots of APIs, for the frameworks I work on, and within large domain models that I want to break up. Those APIs consist almost entirely of interfaces (meaning, in my case, C# interfaces). I find, over and over again, that I want to distinguish between two kinds of interface. In the absence of finding any more widely used terms, I define these two as follows:
'Role' interfaces are intended to be implemented by objects outside of the API, in order that those objects can be used as arguments for methods defined on the API.
'Result' interfaces are implemented by objects inside the API and made available to other parts of the system via the API. The intent of defining a result interface rather than exposing the object that implements it is to restrict the view of the object to the outside world.
To pick one example, a Payments sub-system might define IPayableItem as a Role interface, implemented by many types in other parts of the application in order that Payments may be generated for them. Those generated Payment objects may be retrieved via the API but defined by the Result interface IPayment.
The only way I can currently distinguish these is by naming convention and/or commenting. Ideally, I would like the distinction enforced by the language, and have it enforce the rule: you can't implement a Result interface outside the API, only use it. But C# doesn't provide any such mechanism. (Can anyone advise me of a language that does?). I could define an attribute, but this still wouldn't enforce anything.
Another important significance of the distinction lies in Semantic Versioning of the API. If I add a new member to a Role interface then this should be seen as a breaking change (and hence a first-level version) - because any existing external implementations will need to add that member. But if I add a member to what I deem to be a 'Result' interface then it should only be my own code that is impacted - it is just a new feature (second-level version) for everyone else. But with no enforced distinction between the two types there's some risk that people are implementing the Result interfaces and hence their code would be broken.
Has anyone else encountered this dilemma? If so, how have you dealt with it? I look forward to your answers.
But please don't both to respond with either of the following arguments (which I have heard all too often):
My Result interfaces should be abstract classes rather than interfaces. This does not solve the problem, and potentially makes it worse, since external code can sub-class them.
I should be returning the concrete type and ensuring that anything I don't want accessible outside the API is marked 'internal'. There are lots of cases where I need things inside the API to be public, e.g. to be accessible to other frameworks (not going through the API).
I think what you're asking is it possible to expose an interface, but determine that a given instance is one you created?
If so, you could also create an internal private interface, and mark all your implementations as also implementing the private interface. Then upon being given an object from the outside world, verify it has the internal interface implementation as well.
public interface IPublic
{
...
}
internal interface ISecret { }
public class PublicImplementation : IPublic, ISecret
{
...
}
Only you can implement the ISecret, so even if someone implements the IPublic and passes it to you, it will fail the ISecret test.
I have some integrations (like Salesforce) that I would like to hide behind a product-agnostic wrapper (like a CrmService class instead of SalesforceService class).
It seems simple enough that I can just create a CrmService class and use the SalesforceService class as an implementation detail in the CrmService, however, there is one problem. The SalesforceService uses some exceptions and enums. It would be weird if my CrmService threw SalesforceExceptions or you were required to use Salesforce enums.
Any ideas how I can accomplish what I want cleanly?
EDIT: Currently for exceptions, I am catching the Salesforce one and throwing my own custom one. I'm not sure what I should do for the enums though. I guess I could map the Salesforce enums to my own provider-agnostic ones, but I'm looking for a general solution that might be cleaner than having to do this mapping. If that is my only option (to map them), then that is okay, just trying to get ideas.
The short answer is that you are on the right track, have a read through the Law of Demeter.
The fundamental notion is that a given object should assume as
little as possible about the structure or properties of anything else
(including its subcomponents), in accordance with the principle of
"information hiding".
The advantage of following the Law of Demeter is that the resulting
software tends to be more maintainable and adaptable. Since objects
are less dependent on the internal structure of other objects, object
containers can be changed without reworking their callers.
Although it may also result in having to write many wrapper
methods to propagate calls to components; in some cases, this can
add noticeable time and space overhead.
So you see you are following quite a good practise which I do generally follow myself, but it does take some effort.
And yes you will have to catch and throw your own exceptions and map enums, requests and responses, its a lot of upfront effort but if you ever have to change out Salesforce in a few years you will be regarded a hero.
As with all things software development, you need to way up the effort versus the benefit you will gain, if you think you are likely never to change out salesforce? then is it really needed? ... for you to decide.
To make use of good OOP practices, I would create a small interface ICrm with the basic members that all your CRM's have in common. This interface will include the typical methods like MakePayment(), GetPayments(), CheckOrder(), etc. Also create the Enums that you need like OrderStatus or ErrorType, for example.
Then create and implement your specific classes implementing the interface, e.g. class CrmSalesForce : ICrm. Here you can convert the specific details to this particular CRM (SalesForce in that case) to your common ICrm. Enums can be converted to string and the other way around if you have to (http://msdn.microsoft.com/en-us/library/kxydatf9(v=vs.110).aspx).
Then, as a last step, create your CrmService class and use in it Dependency Injection (http://msdn.microsoft.com/en-us/library/ff921152.aspx), that's it, pass a type of ICrm as a parameter in its constructor (or methods if you prefer to) . That way you keep your CrmService class quite cohesive and independent, so you create and use different Crm's without the need to change most of your code.
In the example I'm thinking of I have about 4 lines of code that could be encapsulated by a function, and this function will surely be used in other classes in the same hierarchy.
I have the following options for reusing that code:
Copy paste the function around to the classes that need it.
Make a base class for the classes that need the function and put it there.
Make a class that contains the function which gets passed into the classes that need it through DI or is just a member of the class. (seems like major overkill)
Make a static utility class and put that method in it.
I definitely wouldn't do 1 or 4. I would have done 2 in the past but I'm trying to keep to the composition over inheritance principle so I'm leaning towards 4 however it seems like a lot for something that will most likely never be used outside the hierarchy and is only 4 lines. I know this is very nitpicky but I want to figure out the right way to do it.
Inheritance was created for a reason. The fact that it has been overused doesn't mean that it doesn't have legitimate uses. The key is that whether you use it should not depend on whether you can get easy reuse out of it, but whether it makes sense for it to belong to the base class, based on what your base class represents.
Without better understanding what your classes are, and what the method is that you're trying to reuse, I can't give specific advice in your particular case. But think of it this way: When you say it will "most likely never be used outside the hierarchy," is that because it purely just doesn't make sense outside of that hierarchy? Or is it just that you don't think somebody's going to build something that happens to use this feature, even though it could conceivably make sense outside of the hierarchy?
If this method would make any sense outside of the specific hierarchy you're talking about, I would suggest approach #3.
And of course, all of this assumes that your class hierarchy is really a hierarchy in the first place. Another common abuse of inheritance is when people force a hierarchy on objects that don't need to be hierarchical in the context of their application.
I agree that composition is a better option than inheritance IN GENERAL. But composing your objects with some logic, perhaps via the strategy pattern, is a different issue than reusing the same code by multiple classes.
If those classes that need this functionality all have the same base class, then it makes sense to put it in the base class. It's not like the subclasses need to know the inner workings of the base class to make this call.
If various subclasses need different versions of this code, then creating behaviors via the strategy pattern (using composition) is the way to go. But I'm making an assumption that the same code satisfies every subclass.
I wouldn't do #4 because then that code is available to other classes that have no business calling it. If the code is in the base class, then you can make it protected and therefore only available to the classes that need it.
if such function arguments are going to be fields of the classes, than it is intended to be operating on your class state and thus should be a member of the base class that addresses such a manipulation.
if you operate on some data that makes sense outside of your hierarchy or from several branches of the hierarchy and meaning of the parameters is not bound to object state make it a function in a utility class.
If it's specifically related to your class hierarchy, use a base class. If not, use option 4. There is no need for composition here.
I know this is a subjective question, but I'm always curious about best-practices in coding style. ReSharper 4.5 is giving me a warning for the keyword "base" before base method calls in implementation classes, i.e.,
base.DoCommonBaseBehaviorThing();
While I appreciate the "less is better" mentality, I also have spent a lot of time debugging/maintaining highly-chained applications, and feel like it might help to know that a member call is to a base object just by looking at it. It's simple enough to change ReSharper's rules, of course, but what do y'all think? Should "base" be used when calling base members?
The only time you should use base.MethodCall(); is when you have an overridden method of the same name in the child class, but you actually want to call the method in the parent.
For all other cases, just use MethodCall();.
Keywords like this and base do not make the code more readable and should be avoided for all cases unless they are necessary--such as in the case I described above.
I am not really sure using this is a bad practice or not. base, however is not a matter of good or bad practice, but a matter of semantics. Whereas this is polymorphic, meaning that even if the method using it belongs to a base class, it will use the overriden method, base is not. base will always refer to the method defined at the base class of the method calling it, hence it is not polymorphic. This is a huge semantic difference. base should then be used accordingly. If you want that method, use base. If you want the call to remain polymorphic, don't use base.
Another important point to take into consideration is that while you haven't currently overridden that method that doesn't mean you won't ever in the future and by prefacing all of your calls with base. you won't get the new functionality without performing a find and replace for all your calls.
While prefacing calls with this. will not do anything other than decrease / increase readability (ignoring the situation where two variables in scope have the same name) the base. prefix will change the functionality of the code you write in many common scenarios. So I would never add base. unless it is needed.
I think generally you should use base only when overriding previous functionality.
Some languages (C# does not) also provide this functionality by calling the function by it's base class name explicitly like this: Foo.common() (called from somewhere in Bar, of course).
This would allow you to skip upwards in the chain, or pick from multiple implementations -- in the case of multiple-inheritance.
Regardless, I feel base should be used only when needed to explicitly call your parent's functionality because you are or have overridden that functionality in this class.
It's really a matter of personal preference. If you like seeing "base." at the beginning of your members, you can easily turn off the rule (Go to Options>Inspection Severity>Code Redundancies>Redundant 'base.' qualifier). Don't let non-behavioral static code analysis rules affect your preferred coding style.
EDIT
One thing to consider is that the static code analysis in FXCop and R# are there to provide rules for all possible needs. To actually adhere to all of the rules simultaneously is a little onerous. You should define your preferred coding style (if you're working in a team, do it collectively), and stick with it. Modify your rules to match your coding standards, not vice versa.
Are there specific cases when one should use custom attributes on class instead of properties?
I know that properties are preferrable because of their discoverability and performance, but attributes... When should I definitely use them?
UPDATE:
Here is a post by Eric Lippert about this decision.
Eric Lippert has a great blog post tackling exactly this decision.
His summary is:
In short: use attributes to describe your mechanisms, use properties to model the domain.
I'd also add to that the consideration that an attribute value is effectively static - in other words it's part of the description of the type rather than any instance of the type.
One tricky bit can come when every instance of some base type has to have a property (e.g. a description) but different concrete derived types want to specify descriptions on a per-type basis rather than per-instance. You often end up with virtual properties which always return constants - this isn't terribly satisfactory. I suspect Delphi's class references might help here... not sure.
EDIT: To give an example of a mechanism, if you decorate a type to say which table it's from in the database, that's describing the data transfer mechanism rather than saying anything about the model of data that's being transferred.
There are two use cases:
1) Using a custom attribute that someone else has defined, such as the System.LoaderOptimization attribute that may be used on the Main method. These kinds of attributes are used to direct platform code such as the CLR, WPF, WCF or the debugger to run the code in a certain way, and can be very useful at times. Reading books on various platform topic is a good way to learn when and how to use these attributes.
2) Creating your own custom attribute and using it to decorate a class (or method, property, etc). These have no effect unless you also have code that uses Reflection to notice those attribute usages and change the behavior in some way. This usages should be avoided whenever possible because of very poor performance, orders of magnitude larger than, say, accessing a static member of a class.