I had a class that had lots of methods:
public class MyClass {
public bool checkConditions() {
return checkCondition1() &&
checkCondition2() &&
checkCondition3();
}
...conditions methods
public void DoProcess() {
FirstPartOfProcess();
SecondPartOfProcess();
ThirdPartOfProcess();
}
...process methods
}
I identified two "vital" work areas, and decided to extract those methods to classes of its own:
public class MyClass {
private readonly MyClassConditions _conditions = new ...;
private readonly MyClassProcessExecution = new ...;
public bool checkConditions() {
return _conditions.checkConditions();
}
public void DoProcess() {
_process.DoProcess();
}
}
In Java, I'd define MyClassConditions and MyClassProcessExecution as package protected, but I can't do that in C#.
How would you go about doing this in C#?
Setting both classes as inner classes of MyClass?
I have 2 options: I either define them inside MyClass, having everything in the same file, which looks confusing and ugly, or I can define MyClass as a partial class, having one file for MyClass, other for MyClassConditions and other for MyClassProcessExecution.
Defining them as internal?
I don't really like that much of the internal modifier, as I don't find these classes add any value at all for the rest of my program/assembly, and I'd like to hide them if possible. It's not like they're gonna be useful/reusable in any other part of the program.
Keep them as public?
I can't see why, but I've let this option here.
Any other?
Name it!
Thanks
Your best bet is probably to use partial classes and put the three clumps of code in separate files adding to the same class. You can then make the conditional and process code private so that only the class itself can access them.
For "Helper" type classes that aren't going to be used outside the current assembly, Internal is the way to go if the methods are going to be used by multiple classes.
For methods that are only going to be used by a single class, I'd just make them private to the class, or use inner classes if it's actually a class that's not used anywhere else. You can also factor out code into static methods if the code doesn't rely on any (non-static) members of your class.
I can
define MyClass as a partial class,
having one file for MyClass, other for
MyClassConditions and other for
MyClassProcessExecution.
Maybe it's my C++ background, but this is my standard approach, though I bundle small helper classes together into a single file.
Thus, on one of my current projects, the Product class is split between Product.cs and ProductPrivate.cs
I'm going for something else - the issue of public / protected / private may not be solved specifically by this, but I think it lends itself much better to maintenance then a lot of nested, internal classes.
Since it sounds like you've got a set of steps in a sequential algorithm, where the execution of one step may or may not be dependent upon the execution of the previous step. This type of sequential step processing can sometimes use the Chain of Responsibility Pattern, although it is morphed a little bit from its original intention. Focussing only on your "processing method", for example, starting from something like below:
class LargeClass
{
public void DoProcess()
{
if (DoProcess1())
{
if (DoProcess2())
{
DoProcess3();
}
}
}
protected bool DoProcess1()
{
...
}
protected bool DoProcess2()
{
...
}
protected bool DoProcess3()
{
...
}
}
Using Chain of Responsibility, this could be decomposed into a set of concrete classes for each step, which inherit from some abstract step class. The abstract step class is more responsible for making sure that the next step is called, if the necessary preconditions are met.
public class AbstractStep
{
public AbstractStep NextStep { get; set; }
public virtual bool ExecuteStep
{
if (NextStep != null)
{
return NextStep.ExecuteStep();
}
}
}
public class ConcreteStep1 : AbstractStep
{
public bool ExecuteStep
{
// execute DoProcess1 stuff
// call base
return base.ExecuteStep();
}
}
...
public class ConcreteStep3 : AbstractStep
{
public bool ExecuteStep
{
// Execute DoProcess3 stuff
// call base
return true; // or false?
}
}
To set this up, you would, in some portion of the code, do the following:
var stepOne = new ConcreteStep1();
var stepTwo = new ConcreteStep2();
var stepThree = new ConcreteStep3();
stepOne.NextStep = stepTwo;
stepTwo.NextStep = stepThree;
bool success = stepOne.ExecuteStep();
This may help clean up the code bloat you've got in your single class - I've used it for a few sequential type algorithms in the past and its helped isolate each step nicely. You could obviously apply the same idea to your condition checking (or build them into each step, if that applies). You can also do some variation on this in terms of passing state between the steps by having the ExecuteStep method take a parameter with a state object of some sort.
Of course, if what you're really concerned about in this post is simply hiding the various steps, then yes, you could make each of your substeps a protected class within your class that creates the steps. Unless you're exposing your library to customers in some form or fashion however, and you don't want them to have any type of visibility into your execution steps, this seems to be a smaller concern then making the code maintainable.
Create the classes with the same access modifier as the methods you have refactored. Partial classes are only really usefull when you have multiple people or automat5ed code generating tools frequently modifying the same classes. They just really avoid source merge hell where your source controll mashes your code because it can't merge multiple edits to the same file.
Related
Currently I am confronted often with code that follows the pattern demonstrated by the code bellow. It is kind of a strategy pattern.
I am not fine with this, it feels somehow smelly. It breaks the actual strategy pattern and the additional indirection is confusing. Also it leads often to methods called similiar like in the example, because the purpose of the method in the derived class is very similar to the in the base class. On the other side I am not able to point with the finger to the problem core.
Am I the onlyone who finds this fishy? And if not, what problems can this code cause, esepecially with regard to SOLID principles?
namespace MyTest
{
abstract class Base
{
public void DoSomething()
{
var param = Prepare();
DoItReally(param);
}
private string Prepare()
{
return "Hallo Welt";
}
protected abstract void DoItReally(string param);
}
class DerivedOne : Base
{
protected override void DoItReally(string param)
{
Console.WriteLine(param);
}
}
class DerivedTwo : Base
{
protected override void DoItReally(string param)
{
Console.WriteLine(param.ToUpper());
}
}
static class Program
{
public static void Main(string[] args)
{
Base strategy = new DerivedOne();
strategy.DoSomething();
strategy = new DerivedTwo();
strategy.DoSomething();
}
}
}
If you separate the code into its two constituent parts, you should see that both of them are perfectly fine.
1. Abstracting some logic to a private method
public void DoSomething()
{
var param = Prepare();
DoItReally(param);
}
private string Prepare()
{
return "Hallo Welt";
}
Given that the method bodies for both methods are fixed, and in this case really short, we can argue about the private method not being necessary here. But this is just an example, and in cases where your initialization logic becomes much more complex (e.g. a complex data query and calculation), the need to abstract this into a private method increases.
2. Subclasses implementing abstract base methods
That's exactly why abstract exists as a keyword.
Your base class know how to fetch the data, but since there are multiple ways of handling this data, there are subclasses which each define one of those options. You've maximized reusability in the base class, the only thing that's not reusable is each subclass' custom handling logic.
I think you're getting caught up on labeling patterns and antipatterns much more than is actually productive.
Clean code doesn't come from the quest to find antipatterns. Clean code comes from understanding your needs, realizing that the code does not suit your purpose or has an unwanted side effect, and then refactoring the code to keep its benefit while losing or minimizing its drawbacks.
As of right now, you have not shown any issue with the code itself, or why it may be causing an unwanted side effect. Your question is hypochondriac in nature, you're over-eagerly looking for issues, rather than simply trying to fix an issue that concretely affects you.
I am trying to structure my code so that I can easily extend it in the future, however I think I am overthinking things and struggling to accomplish this.
My scenario is:
Based upon some data being passed to me I need to generate a class.
The class that I need to generate is not similar in nature to any of the other classes.
For example I have several classes that can be created:
public class File1{
public string Name {get;set;}
// etc...
}
public class File2{
public int ID {get;set;}
// etc...
}
public class File3{
public string MyType {get;set;}
// etc...
}
In my main class I have:
switch (myExtension)
{
case ".abc":
ProcessABC(myContents);
break;
case ".def":
ProcessDEF(myContents);
break;
case ".ghi":
ProcessGHIL(myContents);
break;
//etc...
}
I have tried creating an interface with a common method:
public ProccessStuff(data);
but I don't think that will work since I don't have a common return type.
Then I thought about an abstract class, but then it seems I'll be pushing a lot of work into that abstract class.
public abstract class MyAbstractClass
{
public void ProcessStuff(string data)
{
// Parse the data into an object
// Update some DB fields
// Log some data
}
}
Am I on the right path with just creating an abstract class to handle all of my logic?
You're saying the classes don't have any similarities. But that's not actually true - they all take a string to do some processing, and it's exactly this that you want shared between the classes.
Make an interface, IDataProcessor (or something). There, have a single method - void Process(string). The file classes will implement the method in a way they require.
This changes your main classes switch to a simple
IDataProcessor actualDataProcessor = ...;
actualDataProcessor.Process(myContents);
Of course, you still need some way to create the proper IDataProcessor based on e.g. the extension. Depending on your exact needs, a simple Dictionary<string, Func<IDataProcessor>> might be quite enough. Otherwise, there's plenty of other ways to bind classes more dynamically if you so desire, or use an explicit factory class.
Have you tried using generics?
Here is an example :
public void Process<T>(string contents)
where T : IProcessStuff, new ()
{
// Common work to do here
// ...
// Specific processing stuff
T t = new T();
t.ProcessStuf(contents);
}
public interface IProcessStuff
{
void ProcessStuf(string contents);
}
Instead of running a code in a Initialize() method for example, i want to just write a line, something like somecode.run() and it will run everything for me, allowing me to write all the code in a different location for the sake of organization.
I want the code to act like it was in that spot though, so i have access to privates etc.
whats the best way to do this?
edit to clarify:
Here is an example
public class game
{
public void Initialize()
{
I want to run some code here but I don't want to write it here,
I want to write it in another file for the sake of organization,
and just reference it somehow here, but yet still be able to use the
privates as if it was in this spot
}
}
Partial classes and methods should be able to do what you're talking about (MS Documentation http://msdn.microsoft.com/en-us/library/wa80x488.aspx).
I'm not sure why you'd need to do anything more complex than what's defined in the MSDN document. You can use virtuals to allow for overrides and call the base function, to call the original implementation. There's a proper way to use inheritance to allow a lot of "tweaking" at the proper levels, but the initial partial classes and methods should allow you to do the basic format.
You normally see examples of partials in code that's pre-written (for instance in LINQ by the DataContext).
//auto-generated (or half implemented) code
public partial User
{
public partial void OnFirstNameChanged();
private string _FirstName = "";
public string FirstName
{
get
{
return _FirstName;
}
set
{
_FirstName = value;
OnFirstNameChanged();
}
}
}
//MyCustomStuff.cs
public partial User
{
public partial void OnFirstNameChanged()
{
Console.Write(string.Format("Your name is {0}", FirstName));
}
}
The only way to do what you want is to use partial classes. Something like the following:-
// In file: game1.cs
public partial class game
{
private int Value;
public void Initialize()
{
Run();
}
}
// In file: game2.cs
public partial class game
{
private void Run()
{
Value = 2; // Access private field.
}
}
Edit:
You mentioned that you don't want to use partial classes unless it meets your requirements. I think that it is the only way to meet your requirements since one of your requirements is for the new method to be able to access private members of the original class.
The only possible situation where partial classes may not meet your requirements is if you also want the method to access your local variables. But then you could just pass those local variables through the parameters of that new method.
Having said all these, I personally discourage the use of partial classes since it's not normally considered a good practice. That means that you will need to change your requirements if you want to do it in a different way.
Well my question is pretty self-explanatory. I have a class and I want to ensure that there is just 1 public constructor to this class. Moreover, I also want to ensure that the constuctor should have just 1 parameter. My class will be modified by many different developers, and I am looking for a way to ensure that they do not write any more constructors than are currently specified. Is it possible? If yes, then how?
Note, my class inherits from another class which currently does not have any constructor but it might have in the future. I don't know if this information will affect the answer or not but just thought of adding it.
Please help!
Thanks in advance!
You could consider writing a unit test to encode this design constraint. As long as the test isn't fiddled with, this will warn when the contraint is broken.
This would be a good case for a nice comment in your class detailing this constraint.
The following testing approach can be expanded to provide a test which could test derived types, rather than a single type. This approach is a type of static analysis, and removes the overhead that would be incurred by expensive runtime checking through reflection for instance. A test ensures that the design constraint is validated at build time, rather than at runtime which could be after code is released.
[Test]
public void myClass_must_have_one_single_paramter_ctor()
{
Type type = typeof(MyClass);
const BindingFlags Flags = (BindingFlags.Public | BindingFlags.Instance);
ConstructorInfo[] ctors = type.GetConstructors(Flags);
Assert.AreEqual(1, ctors.Length, "Ctor count.");
ParameterInfo[] args = ctors[0].GetParameters();
Assert.AreEqual(1, args.Length, "Ctor parameter count.");
Assert.AreEqual(typeof(string), args[0].ParameterType, "Ctor parameter type.");
}
public class MyClass
{
public MyClass(string woo) {}
}
All classes have one constructor. If you don't specify one in the source code, the compiler will add an empty public constructor - the equivalent of:
public class MyClass
{
public MyClass()
{
}
}
However if you specify at least one constructor in the source, only the constructors that you explicitly specify will be created, e.g. the following class has one public constructor that takes a single string parameter:
public class MyClass
{
public MyClass(string myParameter)
{
...
}
}
In short, there's nothing special you need to do. If you only want one public constructor then ... just write one public constructor.
Only the person who codes the class can restrict the number and type of constructors.
So if that is you, then you can just code it the way you want.
This could be achieved using reflection. The only thing you need to take care is, the base class code shouldn't be accessible to or editable by developers.
class Program
{
static void Main(string[] args)
{
Inherited obj = new Inherited("Alpha");
obj.test();
Inherited1 obj1 = new Inherited1(); //This will fail as there is no ctor with single param.
obj1.test();
}
}
public class MyBase
{
private static IList<string> ValidatedClasses = new List<string>();
public MyBase()
{
if(!ValidatedClasses.Contains(this.GetType().FullName) &&
!ValidateConstructorLogic())
{
throw new ApplicationException("Expected consturctor with single argument");
}
}
public bool ValidateConstructorLogic()
{
bool ValidConstFound = false;
foreach (var info in this.GetType().GetConstructors())
{
if(info.GetParameters().Length ==1)
{
lock (ValidatedClasses)
{
ValidatedClasses.Add(this.GetType().FullName);
}
ValidConstFound = true;
}
}
return ValidConstFound;
}
}
public class Inherited:MyBase
{
public Inherited(string test)
{
Console.WriteLine("Ctor");
}
public void test()
{
Console.WriteLine("TEST called");
}
}
public class Inherited1 : MyBase
{
public void test()
{
Console.WriteLine("TEST called");
}
}
You could use FxCop to validate your code against a set of predefined rules. I beleive this might be the apt solution to your problem. If you need help on creating custom FxCop rules, please refer this article.
Constructors are not inherited from base classes.
Your class will have only the constructors that you write, except for (as others have pointed out) a default public constructor that is generated by the compiler when you do not explicitly provide one of your own.
You could try using a nested builder, as described by Jon Skeet. Basically: You force the user to go through the builder which then calls the private class constructor. Since the class constructor is private, only the nested builder has access to it.
Alternative: Use static factory methods, make the constructor private & document your intentions.
Based on your comments, I don't think this is a "coding" problem. This is a policy & enforcement problem. You don't want other developers in your team creating more constructors.
In that case, go tell them that. Whoever is in charge of your source code repository can enforce it by rejecting changes that break the policy. Adding code to deal with this is just going to add runtime penalties to users for no reason.
I would like to force subclasses to implement the singleton pattern.
I originally thought of having an abstract static property in the parent class, but upon closer though, that didn't make sense (abstract requires and instance).
Next, I thought of having an interface with a static property, but that also doesn't make sense (interfaces also require an instance).
Is this something which is possible, or should I give up this train of thought and implement an abstract factory?
Please reconsider. You do NOT want to use singletons here. You are making some functionality available to users who derive from your class. That's fine. But you're also dictating one specific way in which it must always be used, and for absolutely no reason. That is not good.
It may make sense to only instantiate one object of this class the majority of the time, but in that case, simply just instantiate the object once. It's not like you're very likely to accidentally instantiate a dozen objects without noticing.
Moreover, how can you tell that having two instances will NEVER be useful? I can think of several cases even now.
Unit testing: You might want each test to instantiate this object, and tear it down again afterwards. And since most people have more than one unit test, you'll need to instantiate it more than once.
Or you might at some point decide to have multiple identical/similar levels in your game, which means creating multiple instances.
A singleton gives you two things:
A guarantee that no more than one instance of the object will ever be instantiated, and
Global access to that instance
If you don't need both these things, there are better alternatives.
You certainly don't need global access. (globals are bad, and usually a symptom of bad design, especially in mutable data such as your game state)
But you don't need a guarantee that no more than one instances will ever be instantiated either.
Is it the end of the world if I instantiate the object twice? Will the application crash? If so, you need that guarantee.
But in your case, nothing bad will happen. The person instantiating the object simply uses more memory than necessary. But he might have a reason.
Simply put in the class documentation that this is a very big and expensive class, and you shouldn't instantiate it more often than necessary. Problem solved. You don't remove flexibility that might turn out to be useful later on, you don't grant global access to data for no reason. Because you can control who can see the object, you don't need to drown it in locks that will become a bottleneck in multithreaded applications. You don't have hidden dependencies scattered throughout your code, making it harder to test and harder to reuse.
Try using an IOC container. Most good IOC containers enable the use of the singleton pattern without having to implement it yourself (ie: spring framework) - I like this better than forcing a static GetInstance() method.
Besides, it's not really possible in java, it would work in C++ with templates though.
Why? If someone wants to use multiple instances of a subclass of your class they might have a perfectly valid reason to.
If you want to do something that only should be done once for each class that subclasses your class (why, I have no idea, but you might have a reason to), use a Dictionary in the base class.
I would define a sealed class that gets its functionality from delegates passed to the constructor, something like this:
public sealed class Shape {
private readonly Func<int> areaFunction;
public Shape(Func<int> areaFunction) { this.areaFunction = areaFunction; }
public int Area { get { return areaFunction(); } }
}
This example does not make a lot of sense, it just illustrates a pattern.
Such a pattern cannot be used everywhere, but sometimes it helps.
Additionally, it can be extended to expose a finite number of static fields:
public sealed class Shape {
private readonly Func<int> areaFunction;
private Shape(Func<int> areaFunction) { this.areaFunction = areaFunction; }
public int Area { get { return areaFunction(); } }
public static readonly Shape Rectangle = new Shape(() => 2 * 3);
public static readonly Shape Circle = new Shape(() => Math.Pi * 3 * 3);
}
I think you will be better off with a factory pattern here to be honest. Or use an IoC tool like Brian Dilley recommends. In the c# world there are loads, here are the most popular : Castle/windsor, StructureMap, Unity, Ninject.
That aside, I thought it would be fun to have a go at actually solving your problem! Have a look at this:
//abstract, no one can create me
public abstract class Room
{
protected static List<Room> createdRooms = new List<Room>();
private static List<Type> createdTypes = new List<Type>();
//bass class ctor will throw an exception if the type is already created
protected Room(Type RoomCreated)
{
//confirm this type has not been created already
if (createdTypes.Exists(x => x == RoomCreated))
throw new Exception("Can't create another type of " + RoomCreated.Name);
createdTypes.Add(RoomCreated);
}
//returns a room if a room of its type is already created
protected static T GetAlreadyCreatedRoom<T>() where T : Room
{
return createdRooms.Find(x => x.GetType() == typeof (T)) as T;
}
}
public class WickedRoom : Room
{
//private ctor, no-one can create me, but me!
private WickedRoom()
: base(typeof(WickedRoom)) //forced to call down to the abstract ctor
{
}
public static WickedRoom GetWickedRoom()
{
WickedRoom result = GetAlreadyCreatedRoom<WickedRoom>();
if (result == null)
{
//create a room, and store
result = new WickedRoom();
createdRooms.Add(result);
}
return result;
}
}
public class NaughtyRoom :Room
{
//allows direct creation but forced to call down anyway
public NaughtyRoom() : base(typeof(NaughtyRoom))
{
}
}
internal class Program
{
private static void Main(string[] args)
{
//Can't do this as wont compile
//WickedRoom room = new WickedRoom();
//have to use the factory method:
WickedRoom room1 = WickedRoom.GetWickedRoom();
WickedRoom room2 = WickedRoom.GetWickedRoom();
//actually the same room
Debug.Assert(room1 == room2);
NaughtyRoom room3 = new NaughtyRoom(); //Allowed, just this once!
NaughtyRoom room4 = new NaughtyRoom(); //exception, can't create another
}
}
WickedRoom is a class that properly implements the system. Any client code will get hold of the singleton WickedRoom class. NaughtyRoom does not implement the system properly, but even this class can't be instantiated twice. A 2nd instantiation results in an exception.
Although this will not enforce the user to have a singleton subclass, you can enforce the user to create only one instance of the class (or its sub-classes) as below. This will throw error if a second instance of any subclass is created.
public abstract class SuperClass {
private static SuperClass superClassInst = null;
public SuperClass () {
if(superClassInst == null) {
superClassInst = this;
}
else {
throw new Error("You can only create one instance of this SuperClass or its sub-classes");
}
}
public final static SuperClass getInstance() {
return superClassInst;
}
public abstract int Method1();
public abstract void Method2();
}