I have a class which represents a step in a registration process. I have certain things that I want the step to perform when a user clicks save after filling out the step and then other things that I want the step to do when we are at the end of the registration process and save is invoked on the step at that stage. I have decided to use the idea of having a state but it seems to have a bad code smell about it. Any comments on how to improve this design?
public class Step1
{
public Enum State
{
InProcess = 1,
EndProcess
}
private State processState;
public Step1(State currentState)
{
processState = currentState;
}
public bool IsValid()
{
bool result;
if(processState = State.InProcess)
{
result = PerformCheck1();
}
else if(processState = State.EndProcess)
{
result = PerformCheck2();
result = PerformCheck3();
}
else
{
throw new Exception("Cannot determine process state");
}
return result;
}
public void Save()
{
if(processState = State.InProcess)
{
DoThing1();
}
else if(processState = State.EndProcess)
{
DoThing2();
DoThing3();
DoThing4();
}
else
{
throw new Exception("Cannot determine process state");
}
}
}
Disregarding other issues with the code, if you go with this design you are going to wind up with a single monolithic class for Step. I would create a IStep interface and make each step its own class:
public interface IStep
{
bool IsValid { get; }
void Save();
}
public class BeginStep : IStep
{
public bool IsValid
{
get
{
return PerformCheck1();
}
}
public void Save()
{
DoThing1();
}
}
public class EndStep : IStep
{
public bool IsValid
{
get
{
// Skipped PerformCheck2() since the result is directly overwritten
return PerformCheck3();
}
}
public void Save()
{
DoThing2();
DoThing3();
DoThing4();
}
}
If I undersdand your answer (+ your comment on Justin's answer) correctly, each step can be in a "processing" and a "completed" state and depending on which state it is in, you want to call different Save() and IsValid() methods.
Furthermore, every step is automatically "completed" once you reach the final step.
From the code you posted, it doesn't seem as if a step needs to know in which state he currently is. You just want to perform different actions depending on whether or not you are on the final page.
Is there a reason why you don't want to create specific methods that encapsulate the "completed" logic (e.g. SaveCompleted() and IsValidCompleted())?
I don't see why the Step class should decide which code to execute, since the decision is made outside the step, where you keep track of the active step.
"Magic methods" that automatically do the right thing based on some hidden state that can be modified from outside often lead to inconsistency, unexpected problems and long debugging sessions.
I would advise you to create an interface as Justin suggested, with 2 additional methods that contain the "completed" code. (There are many ways to achieve the same, like using an abstract base class instead (with the possible advantage that the "completed" methods can default to the "processing" methods) or a separate interface (to only expose the "completed" methods to the final page, without enabling it to call the regualr methods) etc. etc.)
As an addition to Justin’s answer, here is a Wikipedia link to Finite-state machine, as what you are trying to create is a Finite-state machine. The link gives theoretical background knowledge on the theme. If your registration process becomes more complicated, a State/Event table as mentioned in the article will help to formulate the flow of events.
Related
I'll start with a code example. I have a following class
public class Foo
{
public object DoSomething() {}
}
I also have some code that utilises method DoSomehting from class Foo.
public class Boo
{
privite Foo foo;
public void SomeMethod()
{
...
foo.DoSomething();
...
foo.DoSomething();
}
}
How could I distinguish those two calls foo.DoSomething() inside the Foo class?
What I came up with is to have an identification object passed in parameters for each call to DoSomething. Then in Foo class I would store the ids and compare them when new call is made.
public class Boo
{
privite Foo foo;
public void SomeMethod()
{
...
var idObjA = new IDObj(Guid.NewGuid());
foo.DoSomething(idObjA);
...
var idObjB = new IDObj(Guid.NewGuid());
foo.DoSomething(idObjB);
}
}
Maybe there is a better way to do it, or a pattern that I'm not aware of. I want the utilising code to be the least obscured so calls to the DoSomething method are as simple as possible.
To clarify my intentions. I'm implementing a message service with an ability for the user to check a checkbox on dialog box (e.g. Do not show again, or Apply to all). Code utilising the service can call the same method multiple times, to show an error message for example, but in different context. In other words, when user decided to not show that message again for particular action message box should not appear. Thus I need to know when method was called multiple times in the same context (action)
Maybe you should expand a bit on what exactly you are trying to achieve. If you're using your instantiated class like described above and are just trying to differentiate between the first and second call, you can add a respective toggle field in your Foo class:
public class Foo
{
private bool _firstCall = true;
public object DoSomething() {
if(_firstCall) {
_firstCall = false;
// first call logic
} else {
// second call logic
}
}
}
Based on the extra info in your edit, it sounds like what you perhaps need to be doing is setting a separate property in your Foo class showing whether the "apply to all" or "do not show again" option has been checked for a particular context.
Then when you call DoSomething, it can check that property to know if it should show the dialog or not.
So in the simplest case you might do something like:
public class Foo
{
public bool DoNotShow { get; set; };
public void DoSomething() {
if(this.DoNotShow == true) {
// logic
} else {
// alternative logic
}
}
}
public class Boo
{
privite Foo foo;
public void SomeMethod()
{
...
foo.DoSomething();
foo.DoNotShow = true;
...
foo.DoSomething();
}
}
The value could then be toggled on and off whenever you like.
N.B. You mentioned different "contexts" in which dialogs can be turned on and off.
For this, you could consider either giving this property the ability to store values for different contexts (e.g. in something like a Dictionary, perhaps) and then passing in the current context name to the DoSomething method when it's called. Or even pass in a totally separate "context" object to DoSomething each time, which contains the context name and the boolean indicating whether to show the dialog or not.
Or...using a different instance of Foo for each context might actually be more in line with object-oriented principles (in which case you could probably use the code exactly as per my example above). Again it depends exactly how the class the and the overall application works.
If knowing the line number of the call helps, you could use one of the methods for getting the caller information described here. So for example:
public class Foo
{
public object DoSomething() {
StackFrame frame = new StackFrame(1, true);
var method = frame.GetMethod();
var lineNumber = frame.GetFileLineNumber();
}
}
I'm multithreading a real-time game, and would like to prevent the state variables of objects on one thread from being set from another thread. This will make preventing race conditions a lot easier.
I would still like to be able to read the state of other objects, however. I'm intending to use a double buffer system, where one state object is used as the forebuffer and makes state changes while the other is used as the backbuffer and provides the (previous frame's) state to other objects. I need to be able to read state information from the backbuffer to make changes in the forebuffer.
The issue is that even if the variables setter is private, it's possible to change it from another object of the same class.
public class State
{
//Some example state information
public string StateVar1 { get; private set; }
//This method will be farmed out to multiple other threads
public void Update(State aDifferentStateObject)
{
StateVar1 = "I want to be able to do this";
string infoFromAnotherObject = aDifferentStateObject.StateVar1; //I also want to be able to do this
aDifferentStateObject.StateVar1 = "I don't want to be able to do this, but I can";
}
}
May not be the most direct solution, but one way to protect the properties is to use an interface.
public interface IState
{
string StateVar1 { get; }
}
public class State:IState
{
//Some example state information
public string StateVar1 { get; private set; }
//This method will be farmed out to multiple other threads
public void Update(IState aDifferentStateObject)
{
StateVar1 = "I want to be able to do this"; // Allowed
string infoFromAnotherObject = aDifferentStateObject.StateVar1;
aDifferentStateObject.StateVar1 = "I don't want to be able to do this, but I can"; // NOT allowed
}
}
If you're writing a class, it's assumed that you'll make the class work the way you want it to work. The purpose of making stuff private is to prevent your co-workers (or clients) from breaking your class's concerns while they work on their own classes/functions/modules.
Saying "I don't want to be able to do this thing." is somewhat missing the point.
That said, the thing that's nice about less permissive languages in general is that they prevent your co-workers from writing crappy or non-idiomatic code. The other answers show idioms you could use that would make it harder for your peers to later edit break your nice elegant pattern. Anu Viswan's get's my vote.
add field this0=this and in the setter, check that this==this0.
it's possible to change it from another object of the same class.
You cannot stop your own class from setting private setters.
I mean after all, you are the author of that class, its only your fingers you have to worry about.
public class SomeOtherNonRelatedClass
{
public void Update(State aDifferentStateObject)
{
// the world is as it should be
aDifferentStateObject.StateVar1 = "bang!!!" // compiler error
}
}
If you would like to prevent your self from changing your own member, then use an extension method
public class Extensions
{
public void Update(this State aDifferentStateObject)
{
// the world is as it should be
aDifferentStateObject.StateVar1 = "bang!!!" // compiler error
}
}
or make it truly read only (though is probably not useful)
public string StateVar1 { get; }
or a backing field, so you can set it internally
private string backingField;
public string StateVar1
{
get => backingField;
}
I'm trying to create a mechanism that will allow the application to decide (in runtime) whether to execute some functionality.
"Some Functionality" can be anything, it can be c# code which is contained in several classes in several dlls, it can be UI, it can be database query execution, etc.
Most importantly, it should fit in the current existing infrastructure I have, which I cannot re-design and build from scratch.
The more I think of it, it seems like the only solution I can use would be to hold some table which will be the "functionality repository" and it will tell (by unique key) if a functionality is on / off.
Then in code, I will have to place in each spot which handles such functionality an if else statement.
E.g.
If(functionalityEnabled)?
DoFunctionality()
Else
DoTheUsusal()
Is there a better way or a better design to implement it? I would like to keep the solution as simple as possible, but on the other hand, this solution is really ugly and will eventually make my code looks like spaghetti code.
Your thoughts will be appreciated,
I'm using c# with sql server, web api for web services.
Edit:
I want to say that I appreciate the time and effort of everyone answering my question, there were some really interesting ideas that you brought up.
I eventually marked #dasblinkenlight answer since it suited by need the best, though other answers here are really good and may be useful to others.
Thank you.
If you have two classes that implement the same interface, your application can call the functionality (methods, properties) of the class without knowing exactly if it is calling the basic functionality or the alternative functionality:
IFunctionalityX {
DoIt();
}
class BasicFunctionalityX: IFunctionalityX {
public DoIt() {
// Default behaviour goes here
}
}
class PluginFunctionalityX: IFunctionalityX {
public DoIt() {
// Alternative functionality.
}
}
If PluginFunctionalityX shares parts of its implementation with BasicFunctionalityX, you may inherit it from the other, but whether you do or not doesn't really matter. As long as you use the interface, that is what counts, and you can use this method regardless of whether the classes are related or not.
In the initialization of your program, you can make the decision once and create an instance of the right class. You may store this class in some container that holds all your functionalities. FunctionalityX is a property of interface IFunctionalityX, and you can make other interfaces (and properties) for other functionalities.
if (functionalityXEnabled) {
FunctionalityContainer.FunctionalityX = new PluginFunctionality();
} else {
FunctionalityContainer.FunctionalityX = new BasicFunctionality();
}
Then, in the rest of your application, you can call your functionality through:
FunctionalityContainer.FunctionalityX.DoIt();
Instead of implementing this from scratch you may use a dependancy injection library, like Unity. This also allows you to more easily get an instance of the right functionality at the time you need it without having to create them all at the start of your program, and without writing elaborate constructor code for all fucntionalities.
You want to dispatch your code differently at runtime dependent on a configuration setting. Conditionals and polymorphism are two ways of doing so.
Conditionals
At runtime, check for values using if, switch or other lookup methods. You're already doing these.
if (configFile.cloudAccount == null) {
saveFileToDisk();
} else saveFileToCloud();
Advantages
They're conditionals, you really can't avoid having to do one at some point in any nontrivial development project
Disadvantages
Doing them at every point in your application would be painful, though. So they're best combined with other strategies to minimise their use
Polymorphism
When loading your application, read through the configuration file and construct your application's components accordingly:
interface IFileSaver { /* Used to save files in your application */ }
class DiskSaver : IFileSaver { /* The default file saving class */ }
class CloudSaver : IFileSaver { /* If they've configured a cloud account */ }
// EXAMPLE USE
int Main (...) {
// Setup your application, load a config file.
// You'll need to check the config with a conditional
// here (uh oh) but other components of your application
// will just use the IFileSaver interface
if (configFile.cloudAccount != null) {
YourApplication.FileSaver = new CloudSaver(configFile.cloudAccount);
} else {
YourApplication.FileSaver = new DiskSaver();
}
}
// Somewhere else in your application
void SaveCurrentDocument() {
// No if's needed, it was front loaded when initialising
// the application
YourApplication.FileSaver.Save();
}
Advantages
Fits in nicely with object-oriented design
All your configuration checks are front loaded. After loading in the correct classes the rest of your program will use them, oblivious to their actual implementation. Because of that, you don't need to do if checks throughout your code.
Compiler will be able to statically check type errors in your approach
Disadvantages
Only as flexible as your class's interface. Maybe you want some extra steps and checks to occur with a CloudSaver, they'd better fit into the pre-existing interface; otherwise, they won't happen.
Long story short - conditionals let you explicitly perform the checks whenever they're needed so, in principle, you get a lot of procedural flexibility. For example, maybe the SaveAs routine needs to save files slightly differently than the Save routine. However, as you've identified, this leads to long repetitive code. In those cases, structuring your code to use polymorphism might help out.
Either way, you will almost certainly need to have some amount of conditional checks wherever there is flexibility in your application.
Note: There are many other ways of achieving runtime config checks, I'm just pointing out the most common (and usually straightforward)
A once-popular quip among OO programmers has been that every conditional in the code indicate a missed opportunity to subclass. Although this rule is far from being universal, and it falls short when it comes to composition, there is a grain of truth to it, especially when you see the same condition popping up in multiple ifs across different methods of the same class.
A common way of dealing with ifs like that is using some combination of inheritance and composition, and moving the decision to a single place where your object is being created.
The inheritance way looks like this:
interface Doer {
void doSomething();
}
class BasicDoer implements Doer {
public void doSomething() {
...
}
}
class EnhancedDoer extends BasicDoer {
public void doSomething() {
base.doSomething();
...
}
}
// At construction time:
Doer doer;
if (someCondition)
doer = new BasicDoer();
else
doer = new EnhancedDoer();
The composition way looks like this:
interface Doer {
void doSomething();
}
// Create several implementations of Activity, then...
// At construction time:
List<Doer> doers = new ArrayList<>();
if (someCondition1)
doers.add(new SomeKindOfDoer());
if (someCondition2)
doers.add(new AnotherKindOfDoer());
if (someCondition3)
doers.add(new YetAnotherKindOfDoer());
Now instead of an if you do this:
for (Doer d : doers) {
d.doSomething();
}
If it's just a single condition then you have no choice but to use if else and is perfect for single conditions.
If you have more then 1 condition, you may think of using Switch statement.
As far as you are worried about your code going to look complicated with if else statement, put your code within functions,
if(condition)
{
DoThis();
}
else
{
DoSomethingElse();
}
Maybe something similar to strategy design pattern (incapsulation of behaviour) will make it more managable if functionality doesn't require lots of interaction with object data (though interaction is possible). Pros: readable extendable code, cons: lots of code.
namespace SomethingLikeStrategy
{
public interface Behaviour {
void doThis();
void changeM(ref int m);
void doThat();
}
public class BehaviourOriginal : Behaviour {
public void doThis() {
Console.WriteLine("foo");
}
public void changeM(ref int m) {
m = 20;
}
public void doThat() {
throw new Exception("not implemented");
}
}
public class BehaviourSpecial : Behaviour {
public void doThis() {
Console.WriteLine("bar");
}
public void changeM(ref int m) {
m = 10;
}
public void doThat() {
throw new Exception("not implemented");
}
}
public class MyClass {
Behaviour mBehaviour;
int mM = 0;
public MyClass() {
mBehaviour = new BehaviourOriginal();
}
public void setSpecialBehaviour(bool special) {
if (special) {
mBehaviour = new BehaviourSpecial();
} else {
mBehaviour = new BehaviourOriginal();
}
}
public void doThis() {
mBehaviour.doThis();
}
public void doThat() {
mBehaviour.doThat();
}
public void changeM() {
mBehaviour.changeM(ref mM);
}
public void printM() {
Console.WriteLine(mM);
}
}
class Program
{
public static void Main(string[] args)
{
MyClass myClass = new MyClass();
myClass.doThis();
myClass.setSpecialBehaviour(true);
myClass.doThis();
myClass.setSpecialBehaviour(false);
myClass.printM();
myClass.changeM();
myClass.printM();
myClass.setSpecialBehaviour(true);
myClass.changeM();
myClass.printM();
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
For a personal project, I'm working on a small web-based game.
I have a Card class that has a Status property, and there are case statements all over the place. I thought, hey, this is a great oppurtunity for Replace Conditional with Polymorphism!
The problem is, I have a couple methods that do stuff like this:
public class Card
{
public void ChangeStatus()
{
switch (Status)
{
case MyStatusEnum.Normal:
Status = MyStatusEnum.Underwater;
break;
case MyStatusEnum.Underwater:
Status = MyStatusEnum.Dead;
break;
// etc...
}
}
}
When refactoring it in the new NormalCard class, I'm overriding the ChangeStatus method like this:
public override void ChangeStatus()
{
base.Status = MyStatusEnum.Underwater;
}
The problem is this object of NormalCard has a status of Underwater. I can't reassign the type of this, and I don't really want to change the return of the methods from void to CardBase. What options do I have? Is there a standard way of doing this?
Edit Tormod set me straight. I want the State Pattern. Thanks all!
In your case, I'd have a Card object that contains a CardStatus property. The subtypes of CardStatus correspond to the previous enum values. Refactor behaviour that depends on the current status except the state transition to be inside the CardStatus subtypes.
The state transition that's in your first example should, IMO, remain inside the Card object. The state changing feels more like a behaviour of the containing card than of the state object. What you can do is have the CardStatus objects tell you what state to transition to after an event.
A rough example: (obviously there's many more variations on this that could be used.)
API
interface ICardStatus {
ICardStatus NextStatus(Card card);
void DoStuff(Card card);
}
class Card {
ICardStatus Status = new NormalCardStatus();
void DoStuff() {
Status.DoStuff(this);
}
void ChangeStatus() {
Status = Status.NextStatus(this);
}
}
Status implementations
class NormalCardStatus : ICardStatus {
ICardStatus NextStatus(Card card) {
return new UnderwaterCardStatus();
}
void DoStuff(Card card) {
// ...
}
}
class UnderwaterCardStatus : ICardStatus {
ICardStatus NextStatus(Card card) {
return new DeathStatus();
}
void DoStuff(Card card) {
// ...
}
}
class DeathCardStatus : ICardStatus {
ICardStatus NextStatus(Card card) {
// ...
}
void DoStuff(Card card) {
throw new Exception("Cannot do anything while dead");
}
}
You could write the Status class with polymorphism:
class Status
{
Status GetNextStatusWhenFooHappens() {}
Status GetNextStatusWhenBarHappens() {}
Status GetNextStatusWhenBloopHappens() {}
}
Each method returns the status to move to, or anything else you're doing in a case right now. And then you can override these methods for each specific status. The Card class will not be polymorphic with this implementation, but it will hold a polymorphic Status member.
Replacing a conditional with polymorphism is useful in some cases, but it's not clear that it's appropriate here... at least not with straight enums. You could introduce a "smart enum" type instead of MyStatusEnum, where each value knew about the "next" value - then you wouldn't necessarily be using polymorphism, but you would be using a fixed set of values with more information than a standard enum.
Another alternative is to have a simple Dictionary<MyStatusEnum, MyStatusEnum> going from "current status" to "next status". It really depends on whether there's more that you need to do. I suspect we're not really going to be able to offer very good advice based just on the code you've presented.
I am having some trouble defining which kind of test doubles these two classes are.
They both contain (basic) behaviour.
Their difference is that the first in a real context would not run, while the second would (it'd be basically a does-nothing class, but it'd work! The second would crash).
They both seem like Test Spies to me. They both provide a way to get whether the Run() method was called or not. (that is these classes' reason of being!).
I can't use the second one as it is in all the contexts, as I can't also use just the first one in all contexts.
I could refactor both of them into one, but maybe that'd turn things less clear when reading the code.
class FilterTestSpy : IFilter {
private bool hasBeenRan = false;
...
public bool HasBeenRan { get { return hasBeenRan; } }
public void Run() {
hasBeenRan = true;
}
}
class FilterTestSpy2: IFilter {
private bool hasBeenRan = false;
...
public bool HasBeenRan { get { return hasBeenRan; } }
public void Run() {
...some logic...
hasBeenRan = true;
}
}
I know there are mocking frameworks, blablabla, that is not what I am asking about here.
Thanks!
Could you create a strategy to delegate to in the Run() method? That way you will be able to have just one spy class, with a single responsibility, i.e, tell whether the method was called. So, for different contexts, you can inject different strategies.