Making abstract methods available to sub classes - c#

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

Related

Grouping methods logically

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

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.

C# namespace in a class

I have basic knowledge of classes and methods. I can make classes, and define methods for them:
myClass.awesome("test"); (example)
But I saw a class have the following method:
anotherClass.something.methodName(arguments);
How do I create a method that has additional namespace(s). I tried:
public Class test
{
namespace subname
{
public void Test()
{
return;
}
}
//also i tried:
public void lol.Test()
{
return;
}
}
But they both say that its not to be done like that, how do it correctly, so I can order/group my methods better?
Please don't ask why, or give a alternative, I just want to make a class that has this kind of methods(Class.sub.Method() or Class.sub.sub....sub.Method())
Thank you for reading my question, and possibly giving ans answer :)
i saw a class have the following method:
anotherClass.something.methodName(arguments);
The method is not from the class anotherClass instead it is from the class of object something.
The class anotherClass has a field/property something which is of another class type, that class has the method methodName
What you think you have seen is not correct actually. It can be any of the followings:
anotherClass is namespace, something is class, methodName is static method
anotherClass is an object, something is a property of anotherClass, methodName is a method
If you want to group your methods you should consider using static classes like this:
public class Test
{
public static class InnerGroup
{
public static void Method1() { }
}
public static class AnotherInnerGroup
{
public static void Method2() { }
}
}
or class properties like this:
public class Test
{
public class InnerGroup
{
public static void Method1() { }
}
public class AnotherInnerGroup
{
public static void Method2() { }
}
public InnerGroup InnerGroup { get; set; }
public AnotherInnerGroup AnotherInnerGroup { get; set; }
public Test()
{
InnerGroup = new InnerGroup();
AnotherInnerGroup= new AnotherInnerGroup();
}
}
Hope you understood.

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.

Factory pattern in C#: How to ensure an object instance can only be created by a factory class?

Recently I've been thinking about securing some of my code. I'm curious how one could make sure an object can never be created directly, but only via some method of a factory class. Let us say I have some "business object" class and I want to make sure any instance of this class will have a valid internal state. In order to achieve this I will need to perform some check before creating an object, probably in its constructor. This is all okay until I decide I want to make this check be a part of the business logic. So, how can I arrange for a business object to be creatable only through some method in my business logic class but never directly? The first natural desire to use a good old "friend" keyword of C++ will fall short with C#. So we need other options...
Let's try some example:
public MyBusinessObjectClass
{
public string MyProperty { get; private set; }
public MyBusinessObjectClass (string myProperty)
{
MyProperty = myProperty;
}
}
public MyBusinessLogicClass
{
public MyBusinessObjectClass CreateBusinessObject (string myProperty)
{
// Perform some check on myProperty
if (true /* check is okay */)
return new MyBusinessObjectClass (myProperty);
return null;
}
}
It's all okay until you remember you can still create MyBusinessObjectClass instance directly, without checking the input. I would like to exclude that technical possibility altogether.
So, what does the community think about this?
You can make the constructor private, and the factory a nested type:
public class BusinessObject
{
private BusinessObject(string property)
{
}
public class Factory
{
public static BusinessObject CreateBusinessObject(string property)
{
return new BusinessObject(property);
}
}
}
This works because nested types have access to the private members of their enclosing types. I know it's a bit restrictive, but hopefully it'll help...
Looks like you just want to run some business logic before creating the object - so why dont you just create a static method inside the "BusinessClass" that does all the dirty "myProperty" checking work, and make the constructor private?
public BusinessClass
{
public string MyProperty { get; private set; }
private BusinessClass()
{
}
private BusinessClass(string myProperty)
{
MyProperty = myProperty;
}
public static BusinessClass CreateObject(string myProperty)
{
// Perform some check on myProperty
if (/* all ok */)
return new BusinessClass(myProperty);
return null;
}
}
Calling it would be pretty straightforward:
BusinessClass objBusiness = BusinessClass.CreateObject(someProperty);
Or, if you want to go really fancy, invert control: Have the class return the factory, and instrument the factory with a delegate that can create the class.
public class BusinessObject
{
public static BusinessObjectFactory GetFactory()
{
return new BusinessObjectFactory (p => new BusinessObject (p));
}
private BusinessObject(string property)
{
}
}
public class BusinessObjectFactory
{
private Func<string, BusinessObject> _ctorCaller;
public BusinessObjectFactory (Func<string, BusinessObject> ctorCaller)
{
_ctorCaller = ctorCaller;
}
public BusinessObject CreateBusinessObject(string myProperty)
{
if (...)
return _ctorCaller (myProperty);
else
return null;
}
}
:)
You could make the constructor on your MyBusinessObjectClass class internal, and move it and the factory into their own assembly. Now only the factory should be able to construct an instance of the class.
After so many years this got asked, and all the answers I see are unfortunately telling you how you should do your code instead of giving a straight answer. The actual answer you were looking for is having your classes with a private constructor but a public instantiator, meaning that you can only create new instances from other existing instances... that are only available in the factory:
The interface for your classes:
public interface FactoryObject
{
FactoryObject Instantiate();
}
Your class:
public class YourClass : FactoryObject
{
static YourClass()
{
Factory.RegisterType(new YourClass());
}
private YourClass() {}
FactoryObject FactoryObject.Instantiate()
{
return new YourClass();
}
}
And, finally, the factory:
public static class Factory
{
private static List<FactoryObject> knownObjects = new List<FactoryObject>();
public static void RegisterType(FactoryObject obj)
{
knownObjects.Add(obj);
}
public static T Instantiate<T>() where T : FactoryObject
{
var knownObject = knownObjects.Where(x => x.GetType() == typeof(T));
return (T)knownObject.Instantiate();
}
}
Then you can easily modify this code if you need extra parameters for the instantiation or to preprocess the instances you create. And this code will allow you to force the instantiation through the factory as the class constructor is private.
Apart from what Jon suggested, you could also either have the factory method (including the check) be a static method of BusinessObject in the first place. Then, have the constructor private, and everyone else will be forced to use the static method.
public class BusinessObject
{
public static Create (string myProperty)
{
if (...)
return new BusinessObject (myProperty);
else
return null;
}
}
But the real question is - why do you have this requirement? Is it acceptable to move the factory or the factory method into the class?
Yet another (lightweight) option is to make a static factory method in the BusinessObject class and keep the constructor private.
public class BusinessObject
{
public static BusinessObject NewBusinessObject(string property)
{
return new BusinessObject();
}
private BusinessObject()
{
}
}
So, it looks like what I want cannot be done in a "pure" way. It's always some kind of "call back" to the logic class.
Maybe I could do it in a simple way, just make a contructor method in the object class first call the logic class to check the input?
public MyBusinessObjectClass
{
public string MyProperty { get; private set; }
private MyBusinessObjectClass (string myProperty)
{
MyProperty = myProperty;
}
pubilc static MyBusinessObjectClass CreateInstance (string myProperty)
{
if (MyBusinessLogicClass.ValidateBusinessObject (myProperty)) return new MyBusinessObjectClass (myProperty);
return null;
}
}
public MyBusinessLogicClass
{
public static bool ValidateBusinessObject (string myProperty)
{
// Perform some check on myProperty
return CheckResult;
}
}
This way, the business object is not creatable directly and the public check method in business logic will do no harm either.
In a case of good separation between interfaces and implementations the
protected-constructor-public-initializer pattern allows a very neat solution.
Given a business object:
public interface IBusinessObject { }
class BusinessObject : IBusinessObject
{
public static IBusinessObject New()
{
return new BusinessObject();
}
protected BusinessObject()
{ ... }
}
and a business factory:
public interface IBusinessFactory { }
class BusinessFactory : IBusinessFactory
{
public static IBusinessFactory New()
{
return new BusinessFactory();
}
protected BusinessFactory()
{ ... }
}
the following change to BusinessObject.New() initializer gives the solution:
class BusinessObject : IBusinessObject
{
public static IBusinessObject New(BusinessFactory factory)
{ ... }
...
}
Here a reference to concrete business factory is needed to call the BusinessObject.New() initializer. But the only one who has the required reference is business factory itself.
We got what we wanted: the only one who can create BusinessObject is BusinessFactory.
public class HandlerFactory: Handler
{
public IHandler GetHandler()
{
return base.CreateMe();
}
}
public interface IHandler
{
void DoWork();
}
public class Handler : IHandler
{
public void DoWork()
{
Console.WriteLine("hander doing work");
}
protected IHandler CreateMe()
{
return new Handler();
}
protected Handler(){}
}
public static void Main(string[] args)
{
// Handler handler = new Handler(); - this will error out!
var factory = new HandlerFactory();
var handler = factory.GetHandler();
handler.DoWork(); // this works!
}
I don't understand why you want to separate the "business logic" from the "business object". This sounds like a distortion of object orientation, and you'll end up tying yourself in knots by taking that approach.
I'd put the factory in the same assembly as the domain class, and mark the domain class's constructor internal. This way any class in your domain may be able to create an instance, but you trust yourself not to, right? Anyone writing code outside of the domain layer will have to use your factory.
public class Person
{
internal Person()
{
}
}
public class PersonFactory
{
public Person Create()
{
return new Person();
}
}
However, I must question your approach :-)
I think that if you want your Person class to be valid upon creation you must put the code in the constructor.
public class Person
{
public Person(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
Validate();
}
}
This solution is based off munificents idea of using a token in the constructor. Done in this answer make sure object only created by factory (C#)
public class BusinessObject
{
public BusinessObject(object instantiator)
{
if (instantiator.GetType() != typeof(Factory))
throw new ArgumentException("Instantiator class must be Factory");
}
}
public class Factory
{
public BusinessObject CreateBusinessObject()
{
return new BusinessObject(this);
}
}
Multiple approaches with different tradeoffs have been mentioned.
Nesting the factory class in the privately constructed class only allows the factory to construct 1 class. At that point you're better off with a Create method and a private ctor.
Using inheritance and a protected ctor has the same issue.
I'd like to propose the factory as a partial class that contains private nested classes with public constructors. You're 100% hiding the object your factory is constructing and only exposing what you choose to through one or multiple interfaces.
The use case I heard for this would be when you want to track 100% of instances in the factory. This design guarantees no one but the factory has access to creating instances of "chemicals" defined in the "factory" and it removes the need for a separate assembly to achieve that.
== ChemicalFactory.cs ==
partial class ChemicalFactory {
private ChemicalFactory() {}
public interface IChemical {
int AtomicNumber { get; }
}
public static IChemical CreateOxygen() {
return new Oxygen();
}
}
== Oxygen.cs ==
partial class ChemicalFactory {
private class Oxygen : IChemical {
public Oxygen() {
AtomicNumber = 8;
}
public int AtomicNumber { get; }
}
}
== Program.cs ==
class Program {
static void Main(string[] args) {
var ox = ChemicalFactory.CreateOxygen();
Console.WriteLine(ox.AtomicNumber);
}
}
I don't think there is a solution that's not worse than the problem , all he above require a public static factory which IMHO is a worse problem and wont stop people just calling the factory to use your object - it doesnt hide anything . Best to expose an interface and/or keep the constructor as internal if you can that's the best protection since the assembly is trusted code.
One option is to have a static constructor which registers a factory somewhere with something like an IOC container.
Here is another solution in the vein of "just because you can doesn't mean you should" ...
It does meet the requirements of keeping the business object constructor private and putting the factory logic in another class. After that it gets a bit sketchy.
The factory class has a static method for creating business objects. It derives from the business object class in order to access a static protected construction method that invokes the private constructor.
The factory is abstract so you can't actually create an instance of it (because it would also be a business object, so that would be weird), and it has a private constructor so client code can't derive from it.
What's not prevented is client code also deriving from the business object class and calling the protected (but unvalidated) static construction method. Or worse, calling the protected default constructor we had to add to get the factory class to compile in the first place. (Which incidentally is likely to be a problem with any pattern that separates the factory class from the business object class.)
I'm not trying to suggest anyone in their right mind should do something like this, but it was an interesting exercise. FWIW, my preferred solution would be to use an internal constructor and the assembly boundary as the guard.
using System;
public class MyBusinessObjectClass
{
public string MyProperty { get; private set; }
private MyBusinessObjectClass(string myProperty)
{
MyProperty = myProperty;
}
// Need accesible default constructor, or else MyBusinessObjectFactory declaration will generate:
// error CS0122: 'MyBusinessObjectClass.MyBusinessObjectClass(string)' is inaccessible due to its protection level
protected MyBusinessObjectClass()
{
}
protected static MyBusinessObjectClass Construct(string myProperty)
{
return new MyBusinessObjectClass(myProperty);
}
}
public abstract class MyBusinessObjectFactory : MyBusinessObjectClass
{
public static MyBusinessObjectClass CreateBusinessObject(string myProperty)
{
// Perform some check on myProperty
if (true /* check is okay */)
return Construct(myProperty);
return null;
}
private MyBusinessObjectFactory()
{
}
}
Would appreciate hearing some thoughts on this solution.
The only one able to create 'MyClassPrivilegeKey' is the factory. and 'MyClass' requires it in the constructor.
Thus avoiding reflection on private contractors / "registration" to the factory.
public static class Runnable
{
public static void Run()
{
MyClass myClass = MyClassPrivilegeKey.MyClassFactory.GetInstance();
}
}
public abstract class MyClass
{
public MyClass(MyClassPrivilegeKey key) { }
}
public class MyClassA : MyClass
{
public MyClassA(MyClassPrivilegeKey key) : base(key) { }
}
public class MyClassB : MyClass
{
public MyClassB(MyClassPrivilegeKey key) : base(key) { }
}
public class MyClassPrivilegeKey
{
private MyClassPrivilegeKey()
{
}
public static class MyClassFactory
{
private static MyClassPrivilegeKey key = new MyClassPrivilegeKey();
public static MyClass GetInstance()
{
if (/* some things == */true)
{
return new MyClassA(key);
}
else
{
return new MyClassB(key);
}
}
}
}

Categories

Resources