Inherit class minus some fields - possible workarounds? - c#

I don't have access to the definition of a class but I can inherit from it. I want in the derived class to be denied from accessing some fields that are public in the base class for obvious reasons of accidentally accessing/setting/getting the fields/properties.
What choices do I have?
EDIT:
Why the downvote? I have to refactor a large code that was using the said inherited fields and I have to manually treat the lines involving not only those but also the chained inherited fields down the hierarchical tree.
Additionally I have to make sure even I or my partners won't access those fields/properties and still using those intentedly inherited.
EDIT:
A distinction must be made between 2 separate cases: when the programmer designs the application from ground up and when s/he is compelled to proceed from inaccessible code.
In the former case s/he is responsible for applying OOP and design patterns as best fit for the future intended use s/he envisions.
In the latter, situations often come up when the programmer needs to develop from a slightly modified proprietary given class to avoid unneeded complications for the long term. Often times the original code designer can't exhaust the use cases. Thus the developer makes a custom version of the class with the "promise" the original class won't be used and even if ever used, it will only be used for the purposes originally intended, and no inheritance or other relation exists with the new version. This new version would have additional members and other missing members as compared to the original class. This would be consistent with I in SOLID, albeit adapted for classes.
In these cases I admit that inheritance is not the way to go, as it has a different purpose and the developer would break L (and conceptually I) from SOLID by using inheritance. But there's no feature of any language that provides for this, so there's no choice left.

The way I see it, you need to use the Decorator/Wrapper design pattern. Instead of inherinting it, you wrap a class around it.
The class you have:
public class SealedPerson
{
public string Prop1 {get;set;}
public string Prop2 {get;set;}
}
The class you need:
public class SealedPersonWrapper
{
public SealedPersonWrapper(SealedPerson person)
{
this.Prop1 = person.Prop1;
}
public string Prop1 {get; private set;}
}

You can do this by separating interfaces:
public class BaseClass:IBase
{
private int A;
private int B;
void IBase.SetA()
{
A=10;
}
public void SetB()
{
B=10;
}
}
public class DerivedClass:BaseClass
{
public Set()
{
base.SetB();
//method SetA will not accessible through base class, but will accessible with IBase interface
}
}

Hide the inherited fields/properties/methods that you want unusable and make so using them would generate an error, like so:
public class Base // not owned code
{
public int free {get; set;};
public int limited {get; set;};
}
public class Derived:Base // owned code
{
// public new int limited; // NOT hidden! Still accessing Base.limited!
// working:
[Obsolete("Inaccessible hidden inherited variable", true)]
public new int limited {get; set;}
}
true is necessary to prohibit the compilation (trigger an error) instead of compiling with warning.
It's way much easier to write code especially for the unwanted fields than for the wanted ones, since using 90% of the base class.

Related

Best practice to set large amount of properties in C# base class from derived class

I'm working on refactoring some legacy code, and have a large set of data objects that share the same properties and fields.
I'm also doing some reading on refactoring and at first glance it looks like I should use Extract Superclass. Is this a good idea when all I'm combining are properties? I mean they're really just fields with methods auto created so if we're talking about combining GetXYZ functionality that fits...?
With that in mind, let's assume all my objects share 5 common properties:
public string Name { get; private set; }
public string Status {get; private set; }
public int IDNumber { get; private set; }
public int LocationID { get; private set; }
public Location LocationObj { get; private set; }
What's the best way to set these from the subclasses? Also I'll change the private set to protected set.
1) Should I pass in the values/object and set the base class properties in each subclass constructor? This has some code duplication
2) Pass in the parameters and have the derived class call the base class constructor?
3) Create a protected method on the base class like SetBaseProperties? that takes all of them as parameters? (This seems a lot like #2 except a method vs ctor)
Any other methods I'm not aware of?
Method #1 is not a good idea, as it can easily be simplified by letting the base class handle it as you suggest.
Method #2 would reduce the amount of repeated code you need to write, and would leave all of the logic in the base class.
public SubItem(string name, string status, int id, int locID, Location loc) : base(name, status, id, locID, loc)
Method #3 is essentially the same idea, as you said, but using a constructor as opposed to a method guarantees these properties will be set. (You could easily forget to call the method).
Using properties and method #2 is your best bet. If your base class is just used to hold these common properties, and isn't used, remember to mark it abstract so it can't be instantiated. (Only implemented by derived classes)
If you have ReSharper, you can press Alt-Insert, C to create the derived constructor in your derived class. (I'm fairly certain VS does not have this feature by default)

How to write a good curiously recurring template pattern (CRTP) in C#

A while back I wanted to create my own data mapper that would be much simpler than your average ORM. In doing so I found the need to have access to the type information of inheriting classes in my base class. My first thought was reflection, but it's too slow (if you use reflection though, check out Fasterflect as it 'almost' eliminates the performance problems of reflection).
So I turned to a solution that I later found out had it's own name: The Curiously Recurring Template Pattern. This mostly solved my problem, but learning how to correctly implement this pattern was a little challenging. The two main questions I had to solve were:
1) How can I let my consuming code work with my generic objects without needing to know the generic parameters the objects were created with?
2) How can I inherit static fields in C#?
The challenging part was actually figuring out the questions. Once I realized what I needed to do, solving these questions was pretty easy. If you find yourself in need of the CRTP, you will likely find yourself needing to answer these questions... they seem to go hand in hand.
Working with generics without knowing the generic parameter types
When using the CRTP it's good to have a non-generic base class (abstract if possible, but that's not too important) that your 'base' generic class inherits from. Then you can make abstract (or virtual) functions on your non-generic base class and allow consuming code to work with your objects without having to know the generic parameters. For example:
abstract class NonGenBase
{
public abstract void Foo();
}
class GenBase<T>: NonGenBase
{
public override void Foo()
{
// Do something
}
}
Now consuming code that has no knowledge of what T is supposed to be can still call the Foo() procedure on your objects by treating them as instances of the base class.
How to solve the static field inheritance problem
When using the CRTP to solve a problem, it's often beneficial to provide access to static fields in inheriting classes. The problem is that C# doesn't allow inheriting classes to have access to those static fields, except through the type name... which often seems to defeat the purpose in this situation. You may not be able to think of a clear example of what I'm talking about and explaining one is beyond the scope of this answer, but the solution is simple so just tuck it away in your knowledgebase and when you find a need for it you'll be glad it's there :)
class GenBase<T>: NonGenBase
{
static object _someResource;
protected object SomeResource { get { return _someResource; } }
}
This 'simulates' inheritance of static fields. Keep in mind, however, that static fields on a generic class are not scoped across all your generic implementations. Each generic implementation has its own instance of the static field. If you want a single static field that is available to all the implementations, then you simply need to add it to your non-generic base class.
How can I inherit static fields in C#?
I know it's been a long time since you asked this, but, note that in the .NET 6 Preview, you can put static abstract members on an interface. (IIRC, this feature won't be in the release for .NET 6, it will be in preview status until .NET 7).
So, you can do something like this:
public interface IBoundedCollection
{
public static abstract int MaximumItemCount { get; }
}
public abstract class BaseCollection
{
public abstract int Count { get; }
public abstract int GetMaximumItemCount();
public abstract BaseCollection CreateUntypedCopy();
}
public abstract class BoundedCollection<TDerived> : BaseCollection
where TDerived : BoundedCollection<TDerived>, IBoundedCollection
{
public override int GetMaximumItemCount() => TDerived.MaximumItemCount;
public abstract TDerived CreateTypedCopy();
public override BaseCollection CreateUntypedCopy()
=> CreateTypedCopy();
}
public class LimitTenCollection : BoundedCollection<LimitTenCollection>, IBoundedCollection
{
public static int MaximumItemCount => 10;
public override int Count { get; }
public override LimitTenCollection CreateTypedCopy() => new LimitTenCollection();
}
Note the following:
You can work with BaseCollection without working with type arguments. For example, you can use Count, GetMaximumItemCount(), and CreateUntypedCopy().
BoundedCollection<TDerived> can provide the implementation for MaximumItemCount since TDerived is constrained to IBoundedCollection

Shortcuts, Suggestions When Using Static Wrappers for Direct Function Calls to Ubiquitous Interface-Wrapped Classes?

So I've (mostly) wrapped my head around C#'s componentization paradigm and why that's a superior (more predictable, flexible) alternative to confusing and quasi-unpredictable multiple inheritance of c++.
However, I have a couple things that are trouble me.
So if I understand correctly the general approach to adding a component is:
Create an interface that has that component of name I<ClassName adjective>
public interface IHasGear { Gear gear { get; set; } }
public interface IBladeEquipped { Blade blade { get; set; } }
Create an extension class that calls appropriate methods in the interfaced classes.
public static class GearExtensions
{
public static void Stop(this IHasGear machine)
{
machine.gear.KineticStop();
}
public static void Accelerate(this IHasGear machine)
{
machine.gear.ApplyAngularAcceleration();
}
}
public static class BladeExtensions
{
public static void Cut(this IBladeEquipped machine)
{
machine.blade.Cut();
}
public static void ReSharpen(this IBladeEquippeded machine)
{
machine.blade.ReSharpen();
}
}
And then finally add the interface reference and instance of the referenced class to my class that uses the selected component.
public class MeatGrinder : IHasGear, IHasBlade
{
public Gear oldToothyOne { get; set; }
public Blade mrPointy { get; set; }
public MeatGrinder() { oldToothyOne = new Gear(); mrPointy = new Blade();}
}
Now my couple of questions:
Why ALWAYS force the instantiation of the var?
I understand that you might want this if there is inheritance, as you could implement the var with different children. But what about the simplest case of non-inheritance? Why not build in an automatic mechanism to auto-implement in the compiled code the base class(es) in the interfaces is (are) implemented if they are not explicitly implemented
Is there a way to template this process in a ubiquitous fashion?
Obviously this is a repetitive task, if you have several components. Given the ambiguity, is there a way to streamline the workload??
Is there a superior componentization(/inheritance) scheme to the method I describe?
Things to keep in mind:
There's only a few component classes.
I want to be able to use the component class functions as direct calls in the composited class.
There are multiple composited classes (component classes << composited classes)
The components are dissimilar and thus not appropriate for unification in one class.
Given the above considerations an approach that forces me to write individualized code for each composited class is not a desirable approach.
EDIT 1:
I shouldn't have been ambiguous. The reason why I'm not using direct inheritance here is because I have multiple "key" components with functionality that I want to be able to directly address ubiquitously and publicly... e.g. I want to be able to say:
Machine myMachine = new Machine();
myMachine.Accelerate();
myMachine.Cut();
myMachine.ReSharpen();
Hopefully that helps to clarify my question and why I'm adopting this scheme.
Also, I had a couple errors in my example code (a var was non-public and my naming was consistent... these have been corrected.
EDIT 2:
Things that don't make sense for me (to my understanding):
a) Abstract Classes
Why? No multiple inheritance
b) Implicit Operators, a la, hcb's suggestion:
http://www.codeproject.com/Articles/10072/Simulated-Multiple-Inheritance-Pattern-for-C
Why? This approach requires you to create operators for ever class utilizing the component classes, which would result in much more code in a scheme where the interface is commonly used. To me if you're going to go that route, just make traditional wrapper functions rather than get all fancy.
My need for a more elegant solution is driven by ubiquity and mass use of a couple common components that perform redundant functionality, but are dissimilar and thus inappropriate to lump in a single class (despite the convenience that would provide).
Edit 3:
Props to svick for showing me how to format my code nicely without edit diving! :)
Retitled the question to make it more clear, added more precise requirements for suggesting alternate solutions.
What you're doing is just an attempt to emulate multiple inheritance. I don't think it's “the general approach to adding a component”.
I don't think what you're doing is a good way of using extension methods, it looks more like an anti-pattern to me. Especially since you're doing it just to save a few keystrokes, it doesn't add you any other benefit.
I think the answer to your questions about why you can't use some simpler way to do that is that C# tries to be explicit and consistent.
Explicit in that it won't guess what you mean, it makes you spell it out. This is because its guess could be very easily wrong. And the rules how exactly does it guess would probably have to be very complicated and thus confusing. (“I made this little change and now my code behaves completely differently.”)
Another thing is consistency: if you usually implement interface one way, but sometimes you do it differently, it makes the language more complicated and more confusing. Of course, there are cases where inconsistencies like this are worth it.
Specifically, if the feature of automatic implementation of properties from interfaces would work, your code would compile, but wouldn't work correctly: IBladeEquipped defines the property blade, but your class contains the property mrPointy. The compiler would see that you don't implement the required property and implement it for you. And then your code would fail with a NullReferenceException, because blade will always be null. So I think your code presents a good argument against that feature.
Also, I think your example is actually quite good at explaining why you shouldn't write the code the way you want. If you want to resharpen the knife of a meat grinder, do that: grinder.blade.Resharpen(). Writing it differently would feel less natural and more confusing to me.
I'm not sure if this is what your looking for but i like to couple interfaces with abstract base classes to implement default methods and properties:
public interface IHasGear { Gear gear { get; set; } }
public abstract class BHasGear : IHasGear { public virtual Gear gear { get; set; } }
public class MeatGrinder : BHasGear
{
//no need to implement gear, the abstract class already implemented it
private Gear oldToothyOne { get; set; } }
}

Should one use self-referencing generic inheritance like Customer : Entity<Customer>

Is it advisable to use self-referencing generic inheritance?
public abstract class Entity<T> {
public Guid Id {get; set;}
public int Version {get; set;}
public T Clone() {
...
// clone routine
...
return T;
}
}
public class Customer : Entity<Customer> {
public string CustomerName {get; set;}
...
}
How does one cast Customer to the base Entity class? What advantage does "Customer : Entity" provide? I see this kind of inheritance in examples showing NHibernate domain modeling.
Is it better to use "Customer : Entity" without the generics?
You should use it when you need it, not just because you can. In the example above, it makes some sense to implement Clone(). However, as you rightly point out, it means that your entity classes won't actually have a common base class, and properties that are truly common to them won't be accessible. The correct way to handle this is to split it in generic and non-generic parts:
public abstract class Entity {
public Guid Id {get; set;}
public int Version {get; set;}
}
public abstract class Entity<T> : Entity where T : Entity<T> {
public T Clone() {
...
// clone routine
...
return T;
}
}
Also, note the where part that I've added to declaration of Entity<T> - it ensures that this class can only be used as a part of this recursive pattern.
In the company i work for, the project I work on uses heavily this kind of trick. In fact, it is even promoted as a pattern in the code. Thus i can speak from experience: don't use it.
They may be cases where the self-referencing implementation is far simpler, more efficient and easier to read, but I have never encountered such a case. Heavy use of it makes code maintenance a nightmare, and in most cases can be avoided with only a normal inheritance and a casting of your method result if needed. And the performance cost of a casting into the derived class is negligible compared to the maintenance cost of your code.
So if you find the rare example where it is advisable to use self-referencing generic inheritance, go ahead and do so. But think twice beforehand, as there is probably a better way to do it.

It this an example of the Single Responsibility Principle?

I made the following code example to learn how to use a generics method signature.
In order to get a Display() method for both Customer and Employee, I actually began replacing my IPerson interface with an Person abstract class.
But then I stopped, remembering a podcast in which Uncle Bob was telling Scott Hanselman about the Single Responsibility Principle in which you should have lots of little classes each doing one specific thing, i.e. that a Customer class should not have a Print() and Save() and CalculateSalary() method but that you should have a CustomerPrinter class and a CustomerSaver class and a CustomerSalaryCalculator class.
That seems an odd way to program. However, getting rid of my interface also felt wrong (since so many IoC containers and DI examples use them inherently) so I decided to give the Single Responsibility Principle a try.
So the following code is different than I have programmed in the past (I would have made an abstract class with a Display() method and got rid of the interface) but based on what I have heard about decoupling and the S.O.L.I.D. principles, this new way of coding (the interface and the PersonDisplayer class) I think this is the right way to go.
I would like to hear if others think the same way on this issue or have experienced positive or negative effects of this (e.g. an unwieldy number of classes each doing one particular thing, etc.).
using System;
namespace TestGeneric33
{
class Program
{
static void Main(string[] args)
{
Container container = new Container();
Customer customer1 = container.InstantiateType<Customer>("Jim", "Smith");
Employee employee1 = container.InstantiateType<Employee>("Joe", "Thompson");
Console.WriteLine(PersonDisplayer.SimpleDisplay(customer1));
Console.WriteLine(PersonDisplayer.SimpleDisplay(employee1));
Console.ReadLine();
}
}
public class Container
{
public T InstantiateType<T>(string firstName, string lastName) where T : IPerson, new()
{
T obj = new T();
obj.FirstName = firstName;
obj.LastName = lastName;
return obj;
}
}
public interface IPerson
{
string FirstName { get; set; }
string LastName { get; set; }
}
public class PersonDisplayer
{
private IPerson _person;
public PersonDisplayer(IPerson person)
{
_person = person;
}
public string SimpleDisplay()
{
return String.Format("{1}, {0}", _person.FirstName, _person.LastName);
}
public static string SimpleDisplay(IPerson person)
{
PersonDisplayer personDisplayer = new PersonDisplayer(person);
return personDisplayer.SimpleDisplay();
}
}
public class Customer : IPerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Company { get; set; }
}
public class Employee : IPerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int EmployeeNumber { get; set; }
}
}
I like to think of the Single Responsibility Principle as an implementation of separation of duties. Before I start splitting my classes as you have, I try to think of what each class should be responsible for.
Your classes are quite simple and lend themselves well to an abstract class with an implemented Print() and Save() functions as you mentioned. I would tend to keep that design over your current one.
However, if printing and saving were more complicated tasks which might be performed in different ways then a dedicated Printer or Saver class would be warranted, since that responsibility is now more complex. The 'complexity' threshold for making a new class is very subjective and will depend on the exact situation, but in the end, the code is just an abstraction for us lowly humans to understand, so make it such that it's the most intuitive.
You Container class is a little misleading. It doesn't actually 'contain' anything. It actually implements the Factory Method Pattern and would benefit from being named a factory.
Also, your PersonDisplayer is never instantiated and can provide all of its functionality through static methods, so why not make it a static class? It's not uncommon for utility classes such as Printers or savers to be static. Unless you have a need to have separate instances of a printer with different properties, keep it static.
I think you're on the right track. I'm not entirely sure about the Container class though. I'd generally stick with the simpler solution of just using "new" for these objects unless you have some business-driven need for that interface. (I don't consider "neat" to be a business requirement in this sense)
But the separation of "being" a customer responsibility from "displaying a customer" is nice. Stick with that, it's nice interpretation of SOLID principles.
Personally I have now completely stopped used any kind of static methods in this kind of code, and I rely on DI to get all the right service objects at the right place & time. Once you start elaborating further on the SOLID principles you'll find you're making a lot more classes. Try to work on those naming conventions to stay consistent.
Well, I've never heard of this 'single responsibility principle' before, but what it appears to me that what you're doing by having these CustomerPrinter class and CustomerSaver classes is simply converting classes back to structs, and de-object-orienting everything.
For example, this would mean that different customer types would need different cases in the CustomerPrinter class if they needed to be printed differently. But as I understand it, one of the point of OO organisation, and of using inheritance trees and all that, is to do away with the need of this CustomerPrinter to know how to print everything: Customers know how to print themselves.
I don't believe in following these paradigms rigidly in any case. For example I'm unsure what the difference between an Interface and an Abstract Class is in your case. But then again I'm a C++ programmer not a C# programmer...
A few notes:
Generally speaking SRP is all good, as is separation of display formatting from data.
Considering display etc. I would rather think in terms of services, i.e. a PersonDisplayer is single, stateless and offers a string Display(IPerson) function. IMHO, a special class wrapper just to provide display does not provide any advantage.
However, if you used data binding for wpf, you might have a DisplayablePerson class that would propagate PropertyChanged if Person changed. You would put DisplayablePerson objects into ObservableCollection and serve it as ItemsSource of some list control.
What do you need Container for, is it only for instantiating and configuring instance?Try then Customer customer1 = new Customer{FirstName= "Jim", LastName= "Smith"};
On a side note, I've tried object.Method < SomeType>(...) invocation a few times, as it seemed quickest and simplest solution. However, after some time I've always run into troubles with that one and ended up with object.Method(Type someTypeType, ...)
You might have a look at IFormattable and IFormatProvider.
The framework has formatting classes for support.

Categories

Resources