Adding a property without touching the class? (not inheritance) - c#

I got a requirement in my project to add another property to some class.
Now I want to avoid changing the class because I figured it shouldn't be aware that he has this property (this property only has significance in the context of this project).
The way I thought to accomplish this was (Please critic this because I wanna know if there are simpler ways of doing this)
Adding a new singleton class that has a mapping between objects of my class and the type of the property I wanted to add
adding in this class an extension method (extension property?) to access the mapping and fetch the property.
Is there a simpler alternative?
Is this just unnecessary complexity? Maybe I should just add a new property to my class?
Thanks!

The design you've described is actually the one used by Microsoft to implement the DependencyProperty system and, in particular, Attached Properties, though in the greater context of a binding framework. That said, using a dictionary with 'attached' data is a very typical solution when you need to tag a class with additional context for a particular use, but don't want to modify the class.

Why do you say "not inheritance"? Surely the way to do this, if you don't want to alter the original class, would be to inherit from the original class and then add your property to the derived class?
BTW, there are only extension methods, not properties, so you can't do it via property.

I would suggest the DECORATOR pattern. I know you say you don't want to use inheritence, but sometimes it's cleaner to do so. The pattern only uses inheritance to define the interface.

An extension method makes sense and it's also relatively simple.
[visibility] [type] [methodName](this [class to extend] c, ... more args if necessary)
{
....
}

Adding a property doesn't break the class's interactions with existing clients, so that really seems the "simplest" approach.
More important, though, is the function of the new property. Is it logically part of the existing class? Change the class. If not, then an extension method might be preferable, but the problem then becomes the visibility of the extension method, and scope of its clients.
As always, complexity is the enemy. In this case, it sounds as though the singleton is a very complex solution, and the extension method is hit-and-miss, depending on scope and visilbity issues. Changing the class is simplest, and will probably make long-term maintenance much easier.
UPDATE: Note that extension methods are static, and that makes it pretty difficult for the extension method to hold data of any time, as a property would be exptected to do.
SECOND UPDATE: If you have access to the source for the class, consider making it a partial class, and put your new property in a separate file, but part of the same partial class. This keeps it separate from the main body of the class for maintenance purposes, and will work with most ORMs. However, there is a restriction that the partial class members have to be in a single assembly.

Define a Nullable values with their Properties(while the Property has significance only for this project)
your major problem is that you don't want to change the class itself because this requirement is ONLY for 1 project (build), i think you are considering SOLID priniciples, one of these principles is OCP (Open-Closed Principle), that is,
your Entity must be open for extension
but closed for modification

Related

C#, is it okay to use nested classes for logical structure?

I am having a bit of a debate about the use of nested classes. The situation is that a class name makes sense to be repeated in two or more places, and while there is moderate similarity between each of the different instances, they are generally different. The nested classes are not often (if at all) needed beyond the scope of their parent class.
So then, rather than just coming up with three different class names, this seems to make more sense to me.
class A {
class B {
}
class M {
class B {
}
}
class Q {
class B {
}
}
The obvious problem with that is not functionality, but rather consistency/repetition. I was wondering if other developers have ever struggled with the same thing, and what some of the opinions were.
The .net Design Guide advises against it:
"Do not use public nested types as a logical grouping construct; use namespaces for this."
"Avoid publicly exposed nested types. The only exception to this is when variables of the nested type need to be declared in rare scenarios such as subclassing or other advanced customization scenarios."
That's also what the base class library does: In the System.Web.UI namespace, you have DataGridItem, DataListItem, ListViewItem, MenuItem, RepeaterItem, etc. All of these could be called Item and nested inside DataGrid, DataList, etc. However, this would violate the two principles outlined above.
It looks okay when your classes are small. Once they get bloated, you really start thinking about moving them in separate files.
More to your point, if you want to use both A.B and M.B in the same code you have to always type A.B and M.B, which can be a pain.
If class B has any similarities between each inner class instance, would it make sense for you to abstract the similarities of B to a base class that exists alongside A, M, and Q? (I think so.) Then your inner classes, while they may have the same name, would be a little cleaner.
With that said, this type of structure can be seen for things like Metadata in an MVC application. In that instance you'd have something like:
[MetadataType(typeof(A.Metadata))]
class A
{
protected class Metadata
{
...
}
}
[MetadataType(typeof(B.Metadata))]
class B
{
protected class Metadata
{
...
}
}
In these case the inner classes each serve the same purpose but their implementations vary with each parent class. Also, with the Metadata definitions here, it makes a lot of sense to keep a class that helps describe its parent as an inner class. If there's any chance you might want to re-use the inner classes elsewhere then I would move them outside of their parents.
I think it's a little atypical to see this in practice otherwise. I'm sure there are good examples, but I bet there are more bad examples of this type of pattern.
I would say it is sometimes ok, but usually not a good design, to use private nested classes. I once refactored an existing very large class in my project to give it private nested classes. The reason why I did this was that some methods took dozens of parameters and this gave them a more logical grouping. In this sense I see nested classes as a good quick fix. It made sense because no one outside that class had any use for any of those fields.
Generally, I would shy away from using nested classes in an initial design - and think twice before considering them in a redesign. In maintenance, if you have the time, it is better to redesign the whole class and split them out into separate classes in separate files that are internal.
I think this strategy is also better for testability than using nested classes is. Due to greater dependencies with the outer class and other classes in the application, my refactored nested classes weren't much easier to unit test than the original large class that passed around many parameters. If you split nested classes so that they are on their own, you can write more discrete unit tests that actually test units rather than, effectively, combining the unit tests for the outer class and the inner class. This will give you more confidence in saying, "Yes, the inner class works at the unit test level" and "Yes, the outer class works at the unit test level" (which also tests how it fits together with the inner class, e.g. in computing formulas).
I understand your sample is sort of contrived. Still, if your class names are similar enough - or identical - you really shouldn't make them nested classes. As a general rule you should shy away from using nested classes at all.
If I'm remembering correctly, the .NET Framework Guidelines recommends against using nested classes as well. Nested Type Usage Guidelines is a little old (back to version 1.1), but the principles still apply.
Do not use nested types if the following are true:
The type must be instantiated by client code. If a type has a
public constructor, it probably should not be nested. The rationale
behind this guideline is that if a nested type can be instantiated, it
indicates that the type has a place in the library on its own. You can
create it, use it, and destroy it without using the outer type.
Therefore, it should not be nested. An inner type should not be widely
reused outside of the outer type without a relationship to the outer
type.
References to the type are commonly declared in client code.
Well you can use namespaces to do things like this too (just create a new folder in VS). Which is better for organising and will pretty much give you the same result.
But if the subclass is only relevant to the parent class then I don't see the harm in it.
Then again, if you are calling them the same thing I would guess they do a similar drop and you may want to look into abstraction, perhaps your parent classes could be done differently too. Really depends on what you need them to do though
I like doing that, for me it makes the use more clearer and especially finding names less of a problem. But usally i try to limit this on private classes or public enums.
For example
class Text {
enum Alignment
class UIElement {
enum Alignment
or
class Quadtree {
private class Node
class Octree {
private class Node
Don't create a nested class if there is any chance (or business reason) that you'll have to use it in some other place (use namespace instead and dot not hesitate to create class with long name if you need to).
For instance I use nested class for DTO between my controller and my view, or in a class to represent a cache entry.
If you want to name them the same but have different types you could use different namespaces.
Namespace1.MyClass{}
Namespace2.MyClass{}
This will end up with two different types despite the classes being named the same.
It really depends on the functionality of the nested class. That is very similar to the way the C++ STL defined iterator differently in each class. There's nothing wrong with the practice, per se, as long as the concept of each is truly different based on the encompassing class.
It can be, somewhat, a matter of style and taste, but personally I don't see an issue as long as they are truly different and dependent on the definition of the encapsulating class. It does tend to get more confusing, though, if they are publicly visible outside the class. Thus, I would not personally expose the classes publicly.
There's nothing inherently wrong about nested classes, as long as you stick to the following rules of thumb:
Never public or internal. There are special cases, such as when you're using a nested class to implement IEnumerator. But even then, the class itself should be kept private, since instances of it are being returned as IEnumerator, and it's really just being done as a way to avoid junking up the namespace with classes that aren't supposed to be instantiated.
Keep them small. A private nested class that's really just used for storing and passing around data in a more organized way is fine, and can sometimes be a very useful tool. (Not entirely unlike how anonymous classes are useful.) But if you're looking to use them to package up large chunks of functionality, it becomes a code smell that suggests you might want to consider refactoring the outer class instead.

Do private classes need to be accessed by properties?

I am using an instance of a private class as the state object supplied to a stream.BeginRead operation. (The class is private to my main stream reading/writing class.)
public class MainClass
{
// ...
private class ResponseState
{
public IResponse response;
public Stream stream;
public byte[] buffer = new byte[1024];
}
}
Access to the class is via the fields directly. Should I really be providing access to the class via properties in this case, even though it is only to be used for holding state?
Interested to know what others do.
It's not required by the C# language, but it is good practice never to expose a field directly for maintainability reasons - it is suggested to use a property instead.
See StyleCop SA1401: FieldsMustBePrivate.
TypeName - FieldsMustBePrivate
CheckId - SA1401
Category - Maintainability Rules
Cause
A field within a C# class has an access modifier other than private.
Rule Description
A violation of this rule occurs whenever a field in a class is given non-private access. For maintainability reasons, properties should always be used as the mechanism for exposing fields outside of a class, and fields should always be declared with private access. This allows the internal implementation of the property to change over time without changing the interface of the class.
Fields located within C# structs are allowed to have any access level.
How to Fix Violations
To fix a violation of this rule, make the field private and add a property to expose the field outside of the class.
If your class is purely state for the containing class then you could consider placing the members directly inside the class that uses them. If your class is more than just state (and I suspect it is) then it should follow the usual maintainability rules.
I would - encapsulation is useful inside the class as well as outside the class. By funneling all access to a member through a well know interface (i.e. the property) you are giving yourself the flexibility to add logic around that access later without changing calling code.
It may seem like overkill but honestly, given automatically implemented properties, it is so easy to declare a property that you may as well go ahead and use one to give yourself maximum flexibility.
In my organization, when a class was private or internal, and it's a entity class, we used public fields to access it.
However, since C# 3.0 we use automatic properties, so we always use properties to access private fields.
Anyway, the effect is the same, in our case it was to do the code more readable.
Best practice is to use properties for every member accessible by other types. Automatic properties at C# 3.0 makes this quite easy.
I have just done some reading on this a week or two ago. There are the two camps. One the majority say you must wrap in the property because my teacher said so and everyone else does it. They say that is easier to add extra logic to a property or more maintainable and some other weak reasons. The other camp, call themselves "the true OO guys" tend to be along the line of if you use properties at all you are doing it wrong (with some exceptions of course). Your case would be the exception as far as I can tell. Actually, thinking about it, they would probably still say you are doing it wrong :) Just cant win. Anyway, they also say if you are going to use them don't bother wrapping unless you need the extra logic in your setters and getters. Why slow your program down for nothing. (apparently they can measure how slow too).
I tend to use properties over fields as I do a lot of MVVM and need to implement INotifyPropertyChanged which requires them. In your case I wouldn't worry about wrapping them in properties just makes for pointless fat. But if it was in a class that needed a property then I would wrap them to keep things similar in that class.
If after all that you didn't wrap them, and needed to later, it's a right click refactor->encapsulate field to wrap a property if you have Resharper.

Can't specify static methods as part of an Interface?

I have a set of objects that I want to conform to an interface, say ISpecialObject.
However a part of my implementation I want to encapsulate the instantiation trigger of these specialobjects within the implementation of each ISpecialObject.
So say for instance I have as list of class types that implement ISpecialObject, I then want to go through each one and call a static method like CanCreate(some data) which tells me whether or not to create an instance of one of these.
However, .net doesn't seem to let me specify this static CanCreate as part of the ISpecialObject interface.
Can anyone suggest a way to get around this, or alternatively a better approach to solving the problem of encapsulation of the instantiation of these objects? I may just be thinking about this all wrong.
Thanks.
Edit: I may have phrased some parts of this poorly. I don't want to provide the implementation in the interface, but rather specify that there will be one, and that it will be static. Essentially I want the objects to be self defining by allowing a higher level object to query when to create them at runtime.
From what I understand, your main issue is the instantiation of a set of objects that conform to the same interface. If that is so, you may want to look at the Factory Design Pattern which is the standard way to encapsulate such logic.
.NET does not allow static method declarations on interfaces. They don't really make sense since interfaces are all about the contract and avoid implementation entirely. Static methods are specifically about implementation. Additionally, interface methods are virtual function calls depending on the type of the instance, whereas static methods are independent of an instance or even a class (they could be put on any concrete type).
If you have many implementations of ISpecialObject, you could use a factory pattern. In order to do this, you would define define an interface called ISpecialObjectFactory alongside ISpecialObject:
class ISpecialObjectFactory
{
ISpecialObject CreateInstance(...);
bool CanCreate(...);
}
Each class that implements ISpecialObject should have a corresponding ISpecialObjectFactory (e.g. UserObject would have also have a UserObjectFactory). This would require a bit more code, but it's a common pattern and I believe it solves your problem.
I dont see the issue. The typename is just a prefix when dealing with static methods. It will make no difference what so ever if the static method lives somewhere else.
That said, look at extension methods, which may do want you really want it to :)
Edit: Another option might be using attributes.
We just discussed something very similiar to this on another thread. Extension methods are definitely a way to solve this problem. They can provide an implementation for an interface, and the methods can be treated as static or used as a method on an instance of an object which is being extended.
It is not exactly a duplicate in the way that you've phrased the question, but it is duplicate in nature so check out the link below.
StackOverflow - subclass-needs-to-implement-interface-property-as-static
Maybe you can use an abstract class as super class for your purpose. So the static methods go in the abstract class and all derived classes have that as well. However, I agree to the the posts above that may be using the factory pattern is a better approach here.

Do I need an abstract class or interface here (or neither)?

I have a warehouse. Sometimes I want to lookup a box location by a name, sometimes by a description, sometimes by a UPC, maybe something else, etc. Each of these lookup methods call the same various private methods to find information to help locate the data.
For example, upc calls a private method to find a rowid, so does name, so does X. So I need to have that method for all of them. I might use that rowid for some way to find a shelf location (it's just an example.)
But my question is should I have an abstract class (or something else) because I am looking up my box in different ways.
In other words, say my code for lookups is very similar for UPC and for location. Each method may call something with (select * from xxxx where location =, or select * from xxxx where upc =). I could just create two different methods in the same class
LocateByUPC(string upc)...
LocateByLocation(string location)...
LocateByDescription(string description)
... again, this would be in one big class
Would there be any reason that I would want a super class that would hold
abstract class MySuper
{
properties...
LocateBox(string mycriteria)...
}
and then inherit that and create a second class that overrides the LocateBox method for whichever version I need?
I don't know why I'd want to do this other than it looks OOD, which really means I'd like to do this if I have a good reason. But, I know of no advantage. I just find that my class gets bigger and bigger and I just slightly change the name of the methods and a little bit of code and it makes me think that inheritance might be better.
Using C# if that matters.
Edit - Would I do this if I only gave someone a .dll with no source but the class definition? The class def. would tell my properties, etc. and what methods to override.
Neither
neither using an abstract class nor an interface will simplify the protocol, i.e. you will still end up with a bunch of LocateXXX methods
I would recommend having a generic Locate(string criteria) method as the basis, and only defining specialized method signatures for the ones you know you will use frequently; the generic can be a catch-all for future expansion in case you need it (and relying on the generic simplifies coding and testing)
It sounds like you might want to implement the design pattern called Template Method. Basically you would define the outline of the lookup algorithm in a base class as final methods, placing common code in those methods. For the methods that require different behavior depending on the type, simply have the base class' final methods call protected methods in the children, and have each child type implement that behavior.
You can take a look online at some resources, just do a google search for Template Method design pattern. Hopefully it will shed some light on your question.
Abstraction helps when you have multiple implementations. And for future-proofing (hoping that a newer implementation will crop up). An interface acts as a contract between the client and the implementer. This is an invariant. Implementations are free to add any number of methods they wish to. Do you have any such needs?
Does that help answer your question?
What you are proposing is (basically) the Strategy pattern. I don't like to link to wikipedia, but its a good place to start at least. Take a look at the pros and cons and see if it would be beneficial to you.
I don't think there's really a need for you to do it this way. You can simply make the LocateBox method public and have it call private helpers based on which search you want to do. It's generally a bad idea to overly complicate your class structure just for the sake of using some OO design principles. Wait until you find a need for them, and then refactor appropriately. This will help point out what is really necessary and what is a waste of your time.
Edit: Another approach that I was thinking of would be to create a data class that has properties based on the various things you could search by. Ie. a BoxSearchData class that has properties such as UPC, etc, and then pass that to LocateBox() and construct the query as necessary based on the properties that are null. This would help you construct searches on multiple criteria later down the line.
It wouldn't seem necessary in my opinion. Just have a single repository that has the different search functions. Then just use the functions you need when they're needed.
However, the interface portion would only become useful if you have tools that are queueing up different types of searches. Then you could have a factory creating different types of Search classes that all implement an Interface. At which point you could enumerate through your queued Search classes, cast to the interface, and execute the function which would be virtual and point to the correct search type. Example: ReturnDataObject GetItem(object param);
On a side note, there are other uses for interfaces when pulling data. That is just the first example that comes to mind.
When in this example you look closely, you see that only the property, used for lookup, changes. When representing this in an OO way, you end up with a class I would call "Lookup" (representing a search, maybe in SQL, maybe in another query language: an object that can return a rowId based on some property and searched-for value of that property.
The real behavioral change would be in the query language. So if you are to create an abstract class or an interface, it should serve that purpose. The concern of variation in property and value can be separated by adding a "property" argument to the query call.
An abstract class is useful when you need a substantial amount of
functionality to be identical across the subclasses, for example in a
shopping cart with multiple methods of payment available, you could
have an abstract class which defines a generic payment method, and
have subclasses inherit from the superclass for each actual payment
method you want to support (paypal, credit card, account, etc). The
mechanics of how a payment is authorized would be different for each
subclass, but they all perform essentially the same function - they
validate that a user can prove that they can pay for the goods or
services in question.
An example of where an interface is useful is where you have unrelated
items that need to provide some similar functionality in a uniform
way. For example, you might have a CMS where articles are stored in a
database, but where the system caches them to disc as well as HTML
pages until the article in the database is modified, at which point
the physical file is deleted until the next time someone access the
copy in the database. Your CMS might also support the ability for
users to upload images, PDFs, etc to be stored for access on the disc,
but you definitely don't want these files to be deleted as the copy on
the disc represents the file itself and not a cached version. In this
case, you could create a Cacheable interface that says what methods a
class which is cached to disc needs to implement, while leaving it up
to the class itself to implement them. This makes more sense as
classes that represent different kinds of data almost certainly need
to implement their caching scheme (if any) differently.
Every class that allows caching would be defined as Class
implements Cacheable, which is something you can then check for in
your code. Less experienced coders might test the class of an object
they are working with by getting the class and processing the result
with a big switch statement. This isn't the correct approach because
it means that you're assuming that certain classes objects implement
certain functionality, and if you add a new class to the system you
need to modify every switch statement in your software to take it into
account. If yo uimplement an interface you can test if an object
implements that interface with the instanceof keyword.
if ($thisObject instanceof Cacheable)
{
// Manage item's cache
}
This approach is better because it eliminates the switch statement and
thus makes your software easier to maintain. If you add a new class
to the system that also implements its own caching scheme then you
just need to declare that it implements Cacheable. As the interface
requires all classes to implement it to declare the methods specified
in the interface you can be sure that any class that implements
Cacheable will provide certain methods for you to use. Your code
doesn't need to know how the class implements these methods, just that
it does implement them.
These concepts are somewhat trickier to explain than to actually learn
to use I'm afraid, hopefully I've got the basic ideas across well
enough for you to figure them out for yourself.
Obviously the entity that is polymorphic here is the constraint. Using string is the quick and dirty way of achieving the same but your type system is completely out of the loop and garbage string values will be just as valid for input as meaningful constraint specs.
So,
LocateBy (Constraint constraint);
and
abstract class Constraint {
String toString ();
}
class LocationConstraint extends Constraint { /* ... */}
etc.

Is it correct to use inheritance instead of name aliasing in c#?

In other words, is it correct to use:
public class CustomerList : System.Collections.Generic.List<Customer>
{
/// supposed to be empty
}
instead of:
using CustomerList = System.Collections.Generic.List<Customer>
I'd rather use the first approach because I'd just define CustomerList once, and every time I needed a customer list I'd always use the same type. On the other hand, using the name aliasing approach not only forces me to have to redefine it everywhere, but also a different alias could be given every time someone wanted to use it (think of a big team), and thus cause the code to be less readable.
Please note that the intention in this case would never be to extend the class, just to create an alias.
well, unless you are adding some functionality to the base class there is no point in creating a wrapper object. I would go with number two if you really need to, but why not just create a variable?
List<Customer> customerList = new List<Customer>();
Don't do it. When people read:
List<Customer>
they immediately understand it. When they read:
CustomerList
they have to go and figure out what a CustomerList is, and that makes your code harder to read. Unless you are the only one working on your codebase, writing readable code is a good idea.
I'd agree with not using an alias in that manner. Nobody in your team should be using aliases in the manner presented; it's not the reason aliasing was provided. Additionally, from the way generics work, there is only ever one List class no matter how many places you use it.
In addition to just declaring and using List<Customer>, you're going to eventually want to pass that list to something else. Avoid passing the concrete List<Customer> and instead pass an IList<Customer> or ICollection<Customer> as this will make those methods more resilient and easier to program against.
One day in the future, if you really do need a CustomerList collection class, you can implement ICollection<Customer> or IList<Customer> on it and continue to pass it to those methods without them changing or even knowing better.
Actually you shouldn't use either. The correct approach according to the framework design guidelines is to either use or inherit from System.Collections.ObjectModel.Collection<T> in public APIs (List<T> should only be used for internal implementation).
But with regards to the specific issue of naming, the recommendation appears to be to use the generic type name directly without aliasing unless you need to add functionality to the collection:
Do return Collection<T> from object
models to provide standard plain
vanilla collection API.
Do return a subclass of Collection<T>
from object models to provide
high-level collection API.
Using inheritance to do aliasing/typedefing has the problem of requiring you redefine the relevant constructors.
Since it will quickly become unreasonable to do that everywhere, it's probably best to avoid it for consistency's sake.
This is one of those 'It depends' questions.
If what you need is a new class that behaves as a List of Customers in addition to your other requirements then the inheritance is the way.
If you just want to use a list of customers then use the variable.
If you're just trying to save on typing, then use the latter. You're not going to run into any bizarre inheritance issues that way.
If you actually want to expose a logically distinct collection type, then use the former - you can go back and add stuff to it then.
Personally, i would just use List<Customer> and call it a day.
I essentially agree with Ed. If you don't need to actually extend the functionality of the generic List construct, just use a generic List:
List<Customer> customerList = new List<Customer>();
If you do need to extend the functionality then typically you would be looking at inheritance.
The third possibility is where you need significantly changed functionality from the generic list construct, in which case you may want to simply inherit from IEnumerable. Doing so make the class usable in enumerable operations (such as "foreach") but allows you to completely define all class behaviour.
One programmer's saving on typing could very well be the next programmer's maintenance nightmare. I'd say just type out the generic correctly, as so many here have said. It's cleaner and a more accurate description of your code's intent, and it will help the maintenance programmer. (Who might be you, six months and four new projects down the road!)

Categories