Optimizing function to modify member variables in different classes - c#

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.

Related

many classes inside a class

The language I use is C#.
I have a problem of architectural nature. Let Class A has the following form:
Class A
{
Class B
{
// properties goes here.
}
Class C
{
// properties goes here.
}
Class D
{
// properties goes here.
}
....
private ClassA methodX
{
// code goes here
}
private ClassB methodY
{
// code goes here
}
private ClassC methodZ
{
// code goes here
}
....
}
The classes B, C and D are classes that hold only properties. They don't express any behaviour through a public method. My problem about this approach is that the code of class A is too huge. So the future maintainance of class A will be difficult.
My question is should I remove the classes B, C and D to seperate files or should I leave them there as they are in class A?
Is there a better approach to handle the above problem?
One of my concerns, if I should put this code to separate files, is that I have also other classes like class A. So, there would be a significant increase in the number of files that my application has.
Thanks in advance for any help.
If you move them out of class A, into their own files and make them internal classes, this will achieve both keeping them private (with respect to other assemblies) and keep your classes at a more manageable size.
From experience, large numbers of files are not a problem as long as your classes are well named and the files are organised into sub-folders, with matching namespaces.

access methods from plain code files and call it in main class (like php include)

This was a general question asked by a colleague of mine....
Is it possible to "outsource" code, and then call it in the main class (e.g. Form1.cs)?
This originates from the fact that he wants to organize his amount of code better than with regions, in the main class.
My first thought was - of course it is!
Use static Extentions, reference it to the main class, and call it through this.Method().
But he meant something like the "include" pattern in PHP....
Is that even possible?
he wants to organize his amount of code better than with regions, in the main class.
You can use partial classes to split the implementation of a single class into multiple (and perhaps more manageable) source files.
In File1.cs:
public partial class MyClass {
public void F() { ... }
}
In File2.cs:
public partial class MyClass {
public void G() { ... }
}
MyClass now has two methods, F and G.
You can externalize using partial classes or decouple it using c# assembly (dll).

Doing the DRY thing the right way

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

Is there a convenient way to map all interface methods onto a subobject?

Suppose I need to inherit from two classes in C#. This is not allowed, so I can do the following: inherit from one of the classes and include the other class as a member variable, inherit from its interfaces and reimplement all methods of those interfaces by redirecting them onto that member variable:
interface SecondBaseInterface {
void FirstMethod();
void SecondMethod();
};
class MyClass : FirstBaseClass, SecondBaseInterface {
public void FirstMethod()
{
secondBase.FirstMethod();
}
public void SecondMethod()
{
secondBase.SecondMethod();
}
SecondBaseClass secondBase = new SecondBaseClass();
};
now this works, but if there's a lot of methods in SecondBaseInterface it will require lot of typing of code that in fact does nothing useful and I'll have to maintain that code in case SecondBaseInterface changes.
Is there some C# feature that would tell the compiler "for all methods of SecondBaseInterface please call corresponding methods of this member variable" or some other convenient way to do such massive redirection?
There is no simple language feature that springs to mind, here are a few ideas:
Use .NET4.0 DynamicObject, where you can add properties / members on the fly.
Use Aspect Oriented Priogramming, or IL Weaving to add a mixin. See PostSharp for example.
Use some form of code generation, e.g. ReSharper.
I'd like to have that opportunity too, but I don't think it exists. Don't be afraid of doing this, though, if you really need a class that can act as both of its superclasses: it's the well-known delegation pattern (as you probably know).
I think almost every seasoned C# developer has probably wished for this at some stage - especially those who are former Delphi developers. It's called "implementation by delegation", and it was available in Delphi.
In fact the man responsible for this Delphi feature, Steve Teixeira, now works at MSFT. Here's a blog entry where he talks about it.
Unfortunately C# can't do this as the the CLI doesn't support implementation by delegation.
I know the pain.
So much that I've started my own project to solve this: NRoles.
This brings a form of trait (pdf) to C#.
Your code would look like this:
class FirstRole : Role {
public void FirstMethod() { ... }
public void SecondMethod() { ... }
}
class SecondRole : Role {
...
}
class MyClass : Does<FirstRole>, Does<SecondRole> {
}
You can also implement interfaces through the roles, and they'll be carried over to the composing class.

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