Doing the DRY thing the right way - c#

I have a solution with two projects each producing a separate dll that is used by another windows application. Each of those projects has a class called MyActions with only one method like so
Project1
public class MyActions
{
public SomeTypeA DoJob(string str1, string str2)
{
}
}
Project 2
public class MyActions
{
public SomeTypeB DoJob(string str1)
{
}
}
The two return types of these two classes are as below
public class SomeTypeA
{
public string stringA { get; set; }
public int someInt { get; set; }
}
public class SomeTypeB
{
public string someStringA { get; set; }
}
The method DoJob in the both the classes of these individual projects have almost 80% code that is the same. Project1 is the one whose MyActions class's DoJob method has some extra bits specific to only Project1.
Now here is the twist.. Project1 is eventually going to be scrapped and its dll will no longer be used.I want to write the code in the best possible way that ensures there is no repeat of code and so that I dont have to make any modifications to remove any un-required code in Project2 once Project1 is discontinued.
I was thinking of using inheritance and overriding the DoJob method. How would that work if their return types are different and they have different input parameters? Perhaps push one of the parameters from Project1's MyActions class to its constructor? I was also thinking of adding a link to Project2's MyActions class in Project1. But not sure about how to go ahead with implementing that and not repeating myself or possibly running into unforeseen problems later. Any tips, suggestions?

If (and only if) the parameters and the return types of the two methods in the two classes are actually different, factor out the code that is line-for-line identical, assuming it is one block, and just create a static method in a new static class, passing the parameters necessary for the common code.
If there are multiple blocks, just have multiple methods.
Call these methods as appropriate from each of the original methods.
If you wanted to create a hierarchical relationship between these classes, which you should only do if it is logical to do so, just make them both inherit a common type, and make the method above a protected method of that common class. Then just call it from the original methods.

Your thought about inheritance is a good one. From your question in read between the lines that you were considering to let Project 1 inherit from Project 2. That's a possibility but probably not the best solution. Here is what I would suggest.
Create a super class for MyActions that both projects extend. Into this class you can move all the code that is shared across both projects (your 80% code of the method). The specific implementations in your MyAction in each project then implement the DoJob method as needed and make use of the provided methods from the super class.
Once you scrap project 1 there will be no changes that have to be made to project 2's code. You end up with a super class though that you do not really need any more in that case. However you won't be repeating yourself anywhere.
I am not yet familiar with the exact differences between java and C# so bear with me if there are differences. This is what code might look like in java.
abstract class AbstractMyActions {
protected SomeType commonMethodForBothProjects() {
...
}
}
public class MyActionsA extends AbstractMyActions {
public SomeType doJob(SomeParameter ..., SomeParameter ...) {
$this->commonMethodForBothProjects();
// Additional steps
}
}
You get the idea.

public class MyActions
{
public ISomeType DoJob(ISomeParam item)
{
}
}
public class SomeTypeA : ISomeType
public class SomeTypeB : ISomeType

Related

Inherit class minus some fields - possible workarounds?

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.

Optimizing function to modify member variables in different classes

I have 2 classes that have exact two functions. The difference between them is they modify the member variables of their own class.
class A
{
public hello;
public void methodA ()
{
// code to modify hello
}
}
class B
{
public hello;
public void methodB()
{
// code to modify hello
}
}
Method A and B do the exact same thing but to different hello (one in class A one in class B).
Is there any way I can avoid duplication here? I think probably delegate will be the answer, but I don't know how. Please give me guidelines, I am a student and still learning. Thanks beforehand.
EDIT: The reason the classes have the same functionality but are separate classes, is because one is in a Windows application, and the other in a console application.
If the classes share the exact same functionality, then they should be combined into one class. If you have to share this class among different applications, you can put this class into a separate assembly, and reference the assembly from both your Windows and console applications.

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; } }
}

C# share code between classes

In Visual Studio 2008 using C#, what is the best way to share code across multiple classes and source files?
Inheritance is not the solution as the classes already have a meaningful hierarchy.
Is there some neat feature that's like a C include file that let's you insert code anywhere you want in another class?
EDIT:
ok, i guess we need a concrete example...
There are several hundred classes in the domain with a well thought out class heirarchy. Now, many of these classes need to print. There is a utility printer class that handles the printing. Let's say there are 3 different print methods that are dependent on the class that is being printed. The code that calls the print method (6 lines) is what I'm trying to avoid copying and pasting across all the different client class pages.
It'd be nice if people wouldn't assume they knew more about the domain that the op - especially when they specifically mention techniques that don't fit...
If you have functionality that you use frequently in classes that represent very different things, in my experience that should fall into just a few categories:
Utilities (e.g. string formatting, parsing, ...)
Cross-cutting concerns (logging, security enforcement, ...)
For utility-type functionality you should consider creating separate classes, and referencing the utility classes where needed in the business class.
public class Validator
{
public bool IsValidName(string name);
}
class Patient
{
private Validator validator = new Validator();
public string FirstName
{
set
{
if (validator.IsValidName(value)) ... else ...
}
}
}
For cross-cutting concerns such as logging or security, I suggest you investigate Aspect-Oriented Programming.
Regarding the PrintA vs. PrintB example discussed in other comments, it sounds like an excellent case for the Factory Pattern. You define an interface e.g. IPrint, classes PrintA and PrintB that both implement IPrint, and assign an instance of IPrint based on what the particular page needs.
// Simplified example to explain:
public interface IPrint
{
public void Print(string);
}
public class PrintA : IPrint
{
public void Print(string input)
{ ... format as desired for A ... }
}
public class PrintB : IPrint
{
public void Print(string input)
{ ... format as desired for B ... }
}
class MyPage
{
IPrint printer;
public class MyPage(bool usePrintA)
{
if (usePrintA) printer = new PrintA(); else printer = new PrintB();
}
public PrintThePage()
{
printer.Print(thePageText);
}
}
You can't just load in code that you'd like to have added into a class in C# via a preprocessor directive like you would in C.
You could, however, define an interface and declare extension methods for that interface. The interface could then be implemented by your classes, and you can call the extension methods on those classes. E.g.
public interface IShareFunctionality { }
public static class Extensions
{
public static bool DoSomething(this IShareFunctionality input)
{
return input == null;
}
}
public class MyClass : Object, IShareFunctionality
{
public void SomeMethod()
{
if(this.DoSomething())
throw new Exception("Impossible!");
}
}
This would allow you to reuse functionality, but you cannot access the private members of the class like you would be able to if you could, say, hash include a file.
We might need some more concrete examples of what you want to do though?
A C# utility class will work. It acts like a central registry for common code (or like the VB.NET Module construct) - it should contain code that's not specific to any class otherwise it should have been attached to the relevant class.
You don't want to start copying source code around if you don't have to because that would lead to code update problems considering the duplication.
As long as the source doesn't need to retain state, then use a static class with static method.
static public class MySharedMembers {
static public string ConvertToInvariantCase(string str) {
//...logic
}
// .... other members
}
If the classes are in the same namespace, there's no need for an include analog. Simply call the members of the class defined in the other function.
If they're not in the same namespace, add the namespace of the classes you want to use in the usings directives and it should work the same as above.
I'm confused by the question: it seems you need to work on your basic OO understanding.
Checkout extension methods: http://msdn.microsoft.com/en-us/library/bb383977.aspx
I don't know of a way to include portions of files but one thing we do frequently is to add an existing file and "link" it from its current location. For example, we have an assemblyInfo.cs file that every project refers to from a solution directory. We change it once and all the projects have the same info because they're referring to the same file.
Otherwise, suggestions about refactoring "common" routines in a common.dll are the best thing I've come up with in .Net.
I am not sure exactly what you mean by a "meaningful" structure already, but this sounds like a place where you could use base class implementation. Though not as "verbose" as C++ multiple inheritance, you might get some benefit out of using chained base class implementation to reuse common functions.
You can preserve class hierarchy, at least visually and override behavior as needed.
Pull out the repetitive code into services. The repetitive code is a clue that there might be some room for refactoring.
For example, create a "PrintingService" which contains the logic needed to print. You can then have the classes that need to print have a dependency on this service (either via the constructor or a parameter in a method which requires the service).
Another tip i have along these lines is to create interfaces for base functionality and then use the interfaces to code against. For example, i had bunch of report classes which the user could either fax, email, or print. Instead of creating methods for each, i created a service for each, had them implement an interface that had a single method of Output(). I could then pass each service to the same method depending on what kind of output the user wanted. When the customer wanted to use eFax instead of faxing through the modem, it was just a matter of writing a new service that implemented this same interface.
To be honest I can't think of anything like includes in Visual C#, nor why you would want that feature. That said, partial classes can do something like it sounds what you want, but using them maybe clashes against your "classes already have a meaningful hierarchy" requirement.
You have many options, TT, extension method, delegate, and lambda

Categories

Resources