Grouping methods logically - c#

Basically I have a class with a private method and lots of public methods that call this private method. I want to group these public methods logically (preferably to separate files) so it'll be organized, easier to use and maintain.
public class MainClass
{
private void Process(string message)
{
// ...
}
public void MethodA1(string text)
{
string msg = "aaa" + text;
Process(msg);
}
public void MethodA2(int no)
{
string msg = "aaaaa" + no;
Process(msg);
}
public void MethodB(string text)
{
string msg = "bb" + text;
Process(msg);
}
// lots of similar methods here
}
Right now I'm calling them like this:
MainClass myMainClass = new MainClass();
myMainClass.MethodA1("x");
myMainClass.MethodA2(5);
myMainClass.MethodB("y");
I want to be able to call them like this:
myMainClass.A.Method1("x");
myMainClass.A.Method2(5);
myMainClass.B.Method("y");
How can I achieve it? There is probably an easy way that I'm not aware of.

You're looking for object composition.
In computer science, object composition (not to be confused with
function composition) is a way to combine simple objects or data types
into more complex ones.
BTW, you shouldn't think that such refactor is grouping methods logically: it's just you need to implement your code with a clear separation of concerns:
In computer science, separation of concerns (SoC) is a design
principle for separating a computer program into distinct sections,
such that each section addresses a separate concern.
Practical example:
public class A
{
// B is associated with A
public B B { get; set; }
}
public class B
{
public void DoStuff()
{
}
}
A a = new A();
a.B = new B();
a.B.DoStuff();

You may move methods to separate classes. Classes may be new classes with dependency to MainClass with public/internal Process method, nested in MainClass or inherited from MainClass. Example with inheritance:
public class MainClass
{
protected void Process(string message)
{
// ...
}
}
public class A: MainClass
{
// methods for A go here
}
public class B: MainClass
{
// methods for B go here
}

You can use nested classes:
public class MainClass
{
// private method here
public class A
{
// methods for A go here
}
public class B
{
// methods for B go here
}
}
If you want them in different files, you can use a partial class for MainClass
// file 1
public partial class MainClass
{
public class A { }
}
// file 2
public partial class MainClass
{
public class B { }
}

Related

Making abstract methods available to sub classes

I want to be able to use the method RaiseMessage that exists on the Abstract Class AgentBase, on other classes through the program.
public class MNyTestAgent: AgentBase
{
RaiseMessage("hey", "hey")
var a = new Foo();
}
public class Foo
{
public Foo()
{
RaiseMessage("","") -<< how do i use it here
}
}
First of all, your code isn't valid C#.
Second of all, if you want to have a method accessible everywhere else, you probably want a public static. To implement a public static method you need to first reconsider your life choices, as doing so in an Agent class looks like bad design and a violation of OOP principles. If you still decide that you need it, something like this should work:
public abstract class AgentBase
{
public static RaiseMessage(string title, string message)
{
// Implementation.
}
}
public class MNyTestAgent: AgentBase
{
public MNyTestAgent()
{
AgentBase.RaiseMessage("hey", "hey");
}
}
public class Foo
{
public Foo()
{
AgentBase.RaiseMessage("hey", "hey");
}
}
Could maybe this help?
public class MNyTestAgent: AgentBase
{
RaiseMessage('hey', 'hey')
var a = new Foo(this);
}
public class Foo
{
public Foo()
{
}
public Foo(AgentBase base)
{
base.RaiseMessage('','') -<< how do i use it here
}
}

Instantiating a generic field of a class

Is there a way to have a generic field in a class to specialize to a specific type in the constructor?
For example:
class concreteClass1
{
private int a;
public concreteClass1( int a)
{
this.a = a;
}
}
class concreteClass2
{
string b;
public concreteClass2(string b)
{
this.b = b;
}
}
class A<T>
{
private T field;
public A(int x)
{
field = new concreteClass1(x); //error here CS0029
}
public A(string y)
{
field = new concreteClass2(y); //error here CS0029
}
}
So T can be either concreteClass1 or concreteClass1 and their respective ctors will have different signatures.
I would refactor this to use dependency injection. That way the class doesn't contain code to create other classes that it depends on, like myConcreteField = new ConcreteA<T>(4);. Dependency injection is used to keep code from getting tied into difficult knots like this.
(Your example is very, very abstract, which makes it a little difficult. If you use class names like "Concrete" and "Implementation" then it makes the answer harder to read because we use those same words to describe concepts.)
Instead, whatever that Concrete thing is, declare an interface, like
public interface ISomethingThatTheOtherClassNeeds<T>
{
public int MySomething {get;set;}
}
public class SomethingThatTheOtherClassNeeds : ISomethingThatTheOtherClassNeeds<string>
{
public int MySomething {get;set;}
}
Then in your Implementation class:
class Implementation<T>
{
private readonly ISomethingThatTheOtherClassNeeds<T> _something;
public Implementation(ISomethingThatTheOtherClassNeeds<T> something)
{
_something = something;
}
void DoSomething()
{
Console.Write(_something.MySomething.ToString());
}
}
The difference is that instead of being responsible for creating whatever that class is, it's passed to Implementation in the constructor. Implementation doesn't even know what the class is - it just knows that it matches the interface.
This is especially helpful if those other classes in turn depend on more classes. If you're creating them by calling new in your class then that class has to know how to create those classes.
Then to wire it up you would use a dependency injection container like Windsor, Unity, Autofac, and many more. That's not very commonly done with console applications, but I'm guessing this is more experimental than real.
Well this was a bit tricky due to having to convert types. Maybe this will work for you?
class Program
{
static void Main(string[] args)
{
var myImplementation = new Implementation<int>(4);
var myImplementation2 = new Implementation<string>("Hello World");
Console.WriteLine(myImplementation.myConcreteField); // outputs 4!
Console.WriteLine(myImplementation2.myConcreteField); // outputs Hello World
}
}
abstract class MyAbstract<T>
{
public T MySomething;
public MyAbstract(T something)
{
MySomething = something;
}
}
class ConcreteA<T> : MyAbstract<T>
{
public ConcreteA(int something) : base((T)Convert.ChangeType(something, typeof(T)))
{
}
}
class ConcreteB<T> : MyAbstract<T>
{
public ConcreteB(string something) : base((T)Convert.ChangeType(something, typeof(T)))
{
}
}
class Implementation<T>
{
public MyAbstract<T> myConcreteField;
public Implementation(T a)
{
myConcreteField = new ConcreteA<T>(4);
}
void DoSomething()
{
Console.Write(myConcreteField.MySomething.ToString());
}
}

Exposing only some inherited methods in the derived class

I stumbled across an interview question related to OOPS. Here is the question:
There is a base class A with 5 methods. Now how should I design the class such that if a class B inherits class A, only 3 methods are exposed. And if a class C inherits class A, the rest of the 2 methods are exposed.
Any thoughts ??
if A is partial and you have 2 namespaces then:
namespace the_impossible
{
class Program
{
static void Main(string[] args)
{
B b = new B();
C c = new C();
b.m1();
b.m2();
b.m3();
c.m4();
c.m5();
}
}
namespace A_1
{
public partial class A
{
public void m1() { }
public void m2() { }
public void m3() { }
}
}
namespace A_2
{
public partial class A
{
public void m4() { }
public void m5() { }
}
}
class B : A_1.A
{
}
class C : A_2.A
{
}
}
It should not be possible in any object-oriented language, otherwise it would break the Liskov substitution principle. Substituting a B for an A should not reduce its correctness (meaning methods should not suddenly be unavailable)
However, there is still some ambiguity in the question that allows for some "out-of-the-box" thinking. Here are questions I would pose back to the interviewer:
What do you mean by "exposed"?
Do the 5 methods in A have to be public?
Does the "exposition" by C need to be implicit or can the be explicitly exposed (e.g. pass-through)
Based on those answers you could either come up with possible options using internal, explicit interface implementations, etc.
I think it was a trick or even dumb question. To achieve this, we must break the Liskov substitution principle. You shouldn't preseve the hierarchy of the classes.
Maybe you just should use interfaces instead:
public class A {} //why we even need this class?
public class B : A, I3Methods
{
public void Method1() { }
public void Method2() { }
public void Method3() { }
}
public class C : A, I2Methods
{
public void Method4() { }
public void Method5() { }
}
public interface I3Methods
{
void Method1();
void Method2();
void Method3();
}
public interface I2Methods
{
void Method4();
void Method5();
}
The only way I can think of is to have them all private in A and then expose them through encapsulation in B and C... But they are not exposed, only executed... So it is half right.
I also think that's impossible.
But to give an approximate answer:
Make 3 methods in A virtual, then implement them in B. Then override those 2 methods in C.
Nobody says that the 5 methods of class A should be exposed when writing them. In C# you could simply write 5 protected methods in class A and expose those you wish to be accessible by writing some hiding methods with the new modifier like this - although this wouldn't actually expose the methods directly they are merely wrapped.
class A
{
protected void M1() { }
protected void M2() { }
protected void M3() { }
protected void M4() { }
protected void M5() { }
}
class B : A
{
public new void M1()
{
base.M1();
}
public new void M2()
{
base.M2();
}
public new void M3()
{
base.M3();
}
}
class C : A
{
public new void M4()
{
base.M4();
}
public new void M5()
{
base.M5();
}
}
In your comments, you mentioned that you were interested if this could be done in any other language. You can kind of do it in C++ through the use of the using keyword. So, starting with class A:
class A {
public:
int Method1() { return 1; }
int Method2() { return 2; }
int Method3() { return 3; }
int Method4() { return 4; }
int Method5() { return 5; }
};
Then you define class B, using private inheritance (essentially you can't auto cast from B to A and all public methods in A become private methods in B).
class B: private A {
public:
// We want to expose methods 1,2,3 as public so change their accessibility
// with the using keyword
using A::Method1;
using A::Method2;
using A::Method3;
};
Do the same for class C, exposing the other two methods instead:
class C: private A {
public:
using A::Method4;
using A::Method5;
};
Or if you're supposed to expose all the methods through C, simply use public inheritance and everything exists:
class C: public A {
public:
};
For usage:
B *b = new B();
b->Method1(); // This works, Method1 is public
b->Method4(); // This fails to compile, Method4 is inaccessible
The reason I said kind of above is because you can work around it by explicitly casting the instance of B to an A:
A *brokena = b; // This wouldn't compile because the typecast is inaccessible
A *a = (A*)b; // This however does work because you're explicitly casting
a->Method4(); // And now you can call Method4 on b...
I know, it is to late to respond. Just thought of sharing my thoughts:
Define Class A as a base class.
Have intermediate child classes A1 -> M1,M2,M3 and A2 -> M4, M5 deriving from Class A
Now, you can have
1) Class B inheriting A1
2) Class C inheriting A2
These two classes are still derived from Class A.
And also we are not breaking liskov substitution principle.
Hope, this gives clarity.

Does accessing a static member invoke the base class constructor?

Even though all common sense says no, I still am asking this question just to get a second opinion and become sure.
If I have a class hierarchy like so:
public class IntermediateObjectContext : System.Data.Objects.ObjectContext
{
public static Action<string> PrintHello { get; set; }
}
public class MyDatabaseContext : IntermediateObjectContext
{
public ObjectSet<Foo> Foos
{
get { // ... }
}
}
Then from a third, unrelated to Entity Framework object, if I access the static member of the IntermediateObjectContext class, in this case, if I subscribe to the delegate of the class, will that somehow instantiate a new ObjectContext?
class SomeClass
{
public void SomeMethod()
{
IntermediateObjectContext.PrintHello += SayHello;
}
public void SayHello(string s)
{
Debug.Print(s);
}
}
All reason says no, common sense says it won't, but I just want to make sure. I am trying to track down a memory hogger object.
What happens if
What happens to the memory situation if I have a static collection for SomeClass types like so:
public class SomeClassCollection
{
private static Collection<SomeClass> _col =
new Collection<SomeClass>();
public void Add(SomeClass c) { _col.Add(c); }
public void Remove(SomeClass c) { _col.Remove(c); }
}
And then some code adds SomeClass instances to SomeClassCollection like so:
public SomeClassCollectionConfig
{
public static RegisterSomeClasses()
{
SomeClassCollection.Add(new SomeClass());
SomeClassCollection.Add(new DerivesClassOfSomeClass());
}
}
(1) No, it won't instantiate an object.
(2) What happens if:
There it will allocate the empty collection col the first time any member of SomeClassCollection is accessed.
From the code, that's all it will do. You aren't using _col anywhere in the code presented.

Using marker classes to control logic flow

I have been going through some code seen that a colleague of mine is using 'marker classes' to control program logic (see contrived example below). It seems to work well, and the code reads really nicely, but there is just something about it that smells...
namespace ConsoleApplication4983
{
public class MyClass
{
static void Main()
{
var c = new MyClass();
c.DoSomething(new Sequential());
c.DoSomething(new Random());
}
public void DoSomething(ProcessingMethod method)
{
if (method is Sequential)
{
// do something sequential
}
else if (method is Random)
{
// do something random
}
}
}
public class ProcessingMethod {}
public class Sequential : ProcessingMethod {}
public class Random : ProcessingMethod {}
}
What would be a better way of achieving the same effect? Enums? Attributes?
Marker interfaces are a better practice as they offer much more flexibility.
However in this specific case I think that virtual dispatch is a better solution.
using System;
namespace ConsoleApplication4983
{
public class MyClass
{
static void Main()
{
var c = new MyClass();
c.DoSomething(new Sequential());
c.DoSomething(new Random());
}
public void DoSomething(ProcessingMethod method)
{
method.Foo();
}
}
public class ProcessingMethod
{
public virtual void Foo() { }
}
public class Sequential : ProcessingMethod
{
public override void Foo() { }
}
public class Random : ProcessingMethod
{
public override void Foo() { }
}
}
What you'd like to do is replace this with a strategy pattern. A strategy defines how something is done -- i.e., an algorithm.
public interface IProcessingMethod
{
void Process();
}
public class SequentialProcess : IProcessingMethod
{
public void Process( IProcessable obj )
{
do something sequentially with the obj
}
}
public class ParallelProcess : IProcessingMethod
{
public void Process( IProcessable obj )
{
do something in parallel with the obj
}
}
public interface IProcessable
{
void Process( IProcessingMethod method );
}
public class MyClass : IProcessable
{
public void Process( IProcessingMethod method )
{
method.Process( this );
}
}
...
var obj = new MyClass();
obj.Process( new SequentialProcess() );
Now if I have a new type of ProcessingMethod, I simply need to create the class for that method and change the code that determines what processing method is injected to the Process method of my IProcessable object.
He was almost there, but not quite, and that's probably what you're seeing. The if statement on the type is the bad smell. The do something should have been on the ProcessingMethod base class and each type that extended it should have their own version.
public void DoSomething(ProcessingMethod method) {
method.DoSomething();
}
I see that this question is old, but I feel that all the answers missed the point.
If the example fully illustrates the extent of the required functionality, then the appropriate construct to use here would be an Enum type. Enum types are value types; they function essentially like named numerical constants, with great IDE autocomplete support. Here is the example modified to use an Enum type:
namespace ConsoleApplication4983
{
public class MyClass
{
static void Main()
{
var c = new MyClass();
c.DoSomething(ProcessingMethod.Sequential);
c.DoSomething(ProcessingMethod.Random);
}
public void DoSomething(ProcessingMethod method)
{
if (method == ProcessingMethod.Sequential)
{
// do something sequential
}
else if (method == ProcessingMethod.Random)
{
// do something random
}
}
}
public enum ProcessingMethod
{
Sequential,
Random
}
}
The other answers are making reference to more elaborate patterns. I think they read too much into the term "marker class". Sometimes strategy pattern, virtual dispatch etc. are a good way to go, but in this case I think an Enum is the simplest improvement to be made to this code.
How about delegating the processing logic to the specific subclass? ProcessingMethod would have some abstract method that is implemented by each subclass.
public void DoSomething(ProcessingMethod method)
{
method.Process();
}
public abstract class ProcessingMethod
{
public abstract void Process();
}
public class Sequental : ProcessingMethod
{
public override void Process()
{
// do something sequential
}
}
public class Random : ProcessingMethod
{
public override void Process()
{
// do something random
}
}
Yeah, this smells bad. If you want to do something parallel:
public class Parallel : ProcessingMethod{}
then you're going to have to change a lot of code.
The Framework Design Guidelines book recommends against using marker interfaces (and presumably marker classes), preferring attributes intead. Having said that, the book does go on to say that using is (as you've done) is much quicker than using reflection to check for an attribute.

Categories

Resources