Best practice for passing parameters, which can take two values - c#

How to write better?
public void Foo(bool isStart) {
// Code [Common]
if (is Start) {
// Code [Start]
} else {
// Code [End]
}
// Code [Common]
}
or
public enum MyEnum {
Start, End
}
public void Foo(MyEnum param) {
// Code [Common]
switch (param) {
case MyEnum.Start:
// Code [Start]
break;
case MyEnum.End:
// Code [End]
break;
}
// Code [Common]
}
Update: I'm looking for a small solution. "Common", "Start" and "End" parts are very short, I do not want to split Foo into several methods.

How about:
public class Foo
{
public void Start()
{
PreCommon();
// Code [Start]
PostCommon();
}
public void Stop()
{
PreCommon();
// Code [Stop]
PostCommon();
}
private void PreCommon()
{
// Code [Pre-Common]
}
private void PostCommon()
{
// Code [Post-Common]
}
...
}
Methods that have a single responsibility are easier to read, easier to understand and easier to maintain.

it just depends on the situation and your approach. for instance YAGNI says you aren't going to need the enum so might as well stick with the bool. but then again if you know you are going to need it, or think you may, then probably the second is the way to go. OR, really if you are going for something that's more expressive, i like the second way better because it makes it obvious to the caller what is being set; true/false is not nearly as descriptive as MyEnum.Start and MyEnum.Stop.

I'm not sure what would be best, it would depend on a number of factors but using an enum in place of a bool like you did here is not the way to go.
Here's another option. Works well if you have more than two cases of code to work with (if that was your point of the enum).
public void Foo(Action unique)
{
// Code [Common]
unique();
// Code [Common]
}
private void StartCode()
{
// Code [Start]
}
private void EndCode()
{
// Code [End]
}
// call it
Foo(StartCode);

My rule of thumb is to take a few minutes when I get to this situation, and really think about if I can make a justification in future scenarios or versions for a 3rd case (necessitating an enumeration or completely new type). If I cannot think of a 3rd case, I always go with bool because they're just easier to test.
I always name on the positive side of things and begin the propertyname with a form of 'to be'... such as "IsActive" or "HasChildren"

How about this ↓
abstract class FooBase
{
public abstract void DoSomthingBegin();
public abstract void DoSomthingEnd();
public void Foo()
{
// Code [Common]
DoSomthingBegin();
DoSomthingEnd();
// Code [Common]
}
}
class FooBegin : FooBase
{
public override void DoSomthingBegin()
{
Console.WriteLine("OnBegin");
}
}
class FooEnd : FooBase
{
public override void DoSomthingBegin()
{
Console.WriteLine("OnEnd");
}
}

Related

C# Different Behaviours in a method according to the variable state

public class Tile
{
State state ;
public void OnStep()
{
if(state == State.normal) { // Do something; }
else if(state == State.empty) { // Do something; }
else if(state == State.hazard) { // Do something; }
}
}
Basically, OnStep will do different behaviours according to the 'state' variable.
I really want to remove those 'if statements' yet I do not want to change Tile class into an abstract class. It works now but I want to know if there is a better technique to manage this. Currently 'State' is enum. ( I am wondering if there is anything that can bind both state and action at the same time ).
So I get you want to extract the logic away from Tile class ...
public class Tile
{
private IState _state;
public void OnStep()
{
_state = _state.Step();
}
}
public interface IState
{
IState Step();
}
public class NormalStep: IStep
{
public IStep Step()
{
/*Step logic*/
// Just an example
if( encounter.HazardousObject ) return new HazardStep();
return this;
}
}
public class HazardStep: IStep
{
public IStep Step(){ /*Step logic*/ }
}
public class EmptyStep: IStep
{
public IStep Step(){ /*Step logic*/ }
}
That would be the simplest scenario. From here you always can get more complex. For example with state data ...
To pick up on madreflection's comments: Everything has its price.
In this case ...
you get rid of the if statements.
you "bundle" behavior with type (== state)
But you pay with substantially more code, more classes, more interfaces. So you always need to take into consideration with what to go and live. What if you have to change/add something in two week's time? Will you be able to without problem?
One last thing: Please do mind, that the above example is just a brief and very simple "something like this". It is of course far away from being production-quality.
I think using a switch statement produces the cleanest code
public enum State
{
Empty,
Normal,
Hazard,
}
public class Tile
{
public State State { get; set; }
public void OnStep()
{
switch (State)
{
case State.Empty:
// do things
break;
case State.Normal:
// do things
break;
case State.Hazard:
// do things
break;
default:
throw new NotSupportedException($"Unknown state {State}");
}
}
}
This is not meant to be a "better" solution, just suggesting another way to do it.
You may name individual action methods in some convention e.g. RunNormalState(), so inside OnStep() you can use Reflection to invoke it.

Is this efficient and should I be using encapsulation in a better way?

Here is the code. Please see my questions at the bottom of this post.
public partial class myClass : Other.Class
{
long check1parameter = CurrentSession.CurrentFile.ID;
protected override void EnquiryLoaded(object sender, System.EventArgs e)
{
disableFields();
}
private void disableFields()
{
if (checkEverything()) {
EnquiryForm.GetControl("Status").Enabled = true;
}
}
public bool check1_method(long check1parameter) {
bool Check1 = false;
string stringToCheck = check1parameter.ToString();
if (stringToCheck.Contains("something")) {
Check1 = true;
}
return Check1;
}
public bool checkEverything() {
bool roleCheck = CurrentSession.CurrentUser.IsInRoles("RequiredRole");
bool check1 = check1_method(check1parameter);
bool checkEverything = false;
if (roleCheck && check1) {
checkEverything = true;
}
return checkEverything;
}
//other methods
}
The code is to check that someone has a role and also that a string contains a bit of info and then disable a field. I have simplified this from the actual code to outline the key points. Although the intention is only to run these simple checks and disable a field, I thought it best to create individual methods for these tasks so they can be expanded later on.
I do get an object reference error with long check1parameter being defined in that position. It was in check1_method() and worked correctly but it's something I'd like to be declared once and used across multiple areas if possible.
I also want to pass parameters\variables to check1_method rather than declaring them inside it. What's the best way to approach making check1parameter available to all methods in this partial class? It refers to another class which is linked to Other.Class in some way.
My main question is - how do I make this as efficient as possible and should I be using private in place of public anywhere here? I'm still very new to C# and haven't quite figured out encapsulation yet, so please go easy on me! :)
myClass doesn't need to be declared as partial unless you intend to continue implementing it in a different file.
When using a simple if statement they can be removed, for example you could write:
public partial class myClass : Other.Class
{
long check1parameter = CurrentSession.CurrentFile.ID;
protected override void EnquiryLoaded(object sender, System.EventArgs e)
{
disableFields();
}
private void disableFields()
{
EnquiryForm.GetControl("Status").Enabled = checkEverything();
}
public bool check1_method(long check1parameter) {
return check1parameter.ToString().Contains("something");
}
public bool checkEverything() {
bool roleCheck = CurrentSession.CurrentUser.IsInRoles("RequiredRole");
bool check1 = check1_method(check1parameter);
return (roleCheck && check1);
}
//other methods
}
In order to save yourself from declaring unnecessary bools. Beyond that you'd be sacrificing readability for fewer lines.
When it comes to public vs private, it's good practice to always specify private unless you need to access it from outside of the class. At a glance, disableFields() should probably be public, and check1_method() and checkEverything() be private.
EDIT:
Also, if check1parameter is instantiated globally to myClass, then you don't need to pass it in as a parameter to check1_methods()
The code you provided looks ok. I've made a couple of changes, mostly code aesthetics. The main one is to make the 2 check methods into properties.
public partial class myClass : Other.Class
{
long check1parameter = CurrentSession.CurrentFile.ID;
protected override void EnquiryLoaded(object sender, System.EventArgs e)
{
disableFields();
}
private void disableFields()
{
if (checkEverything)
{
EnquiryForm.GetControl("Status").Enabled = true;
}
}
// the parameter name was the same as a variable in the class
// renamed to avoid confusion
public bool check1_method
{
get {return check1parameter.ToString().Contains("something");}
}
public bool checkEverything
{
get { return CurrentSession.CurrentUser.IsInRoles("RequiredRole")
&& check1_method; }
}
//other methods
}

Replace Conditional with Polymorphism - How to handle when your type changes?

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.

Is this the example of polymorphism?

I kinda know what polymorphism is but failed to understand it clearly. Also my code is following:
class Human
{
public virtual void CleanTheRoom()
{
}
}
class Woman:Human
{
public override void CleanTheRoom()
{
//women clean faster
}
}
class Man:Human
{
public override void CleanTheRoom()
{
//men clean slower, different code here
}
}
class Child:Human
{
public override void CleanTheRoom()
{
//empty ... children are lazy :)
}
}
Should I explain this is polymorhism because all derived classes from base class Human contain method CleanTheRoom but each of them it implements differently?
The benefit of polymorphism comes when you want to invoke the method on some type of Human, but you don't care which one specifically.
By having CleanTheRoom() defined at the base class level, Human, you can write shorter, cleaner code elsewhere in your application whenever you are working with an instance of Human, whether it be a Child or otherwise.
Polymorphism, for example, lets you avoid lengthy conditional statements where you explicitly check for each type of Human and call a different method:
Good:
private void SomeMethod(Human h)
{
//some logic
h.CleanTheRoom();
//more logic
}
Bad:
private void SomeMethod(Human h)
{
//some logic
if (h is Adult)
CleanTheRoom();
else if (h is Child)
GoofOff();
//some logic
}
What you have is a good example of inheritance. Polymorphism refers specifically to being able to refer to objects of different types by using a single type (the parent class or interface), something this type of inheritance makes possible. Like so:
List<Human> humans = new ArrayList<Human>();
humans.add(new Woman());
humans.add(new Woman());
humans.add(new Man());
humans.add(new Child());
humans.add(new Child());
foreach(Human hum in humans) {
hum.CleanTheRoom(); //I don't know the type of hum, but I don't care
}
Say I've been collecting instances of Human from various locations -- I don't know what type each one is. But I can still iterate over them and call CleanTheRoom(), because they share a parent class.
I'll add a real-world example. Say I have an Invoice class with various subclasses for different types of Invoices -- maybe there are different kinds of Invoices for service clients versus customers who make one-time purchases. Sometimes I care deeply about the differences, and I only deal with one type. But sometimes I want to loop through all of the invoices for this month and print them out. If the parent class has a print() method (which may well be implemented differently by different types) then I can do that.
Yes, that is correct. And you can call the method CleanTheRoom() without knowing which "kind" of human is it.
Here you have some basic examples.
I think you fail to see the benefit, that's the key you're missing to fully understand polymorphism. I will try to make an example:
Let's say you have a simple CRUD form. This is the code of the save button:
var Client = PopulateDTO(); //put all the values in the controls, to an object
if(Action==Actions.Create){
_repository.Create(Client);
}
else if(Action==Actions.Update){
_repository.Update(Client);
}
else if(Action==Actions.Delete){
_repository.Delete(Client);
}
this.Close();
This code works, but it's bad code, and difficult to read. Let's use polymorphism (and the strategy pattern):
public abstract class BaseStrategy{
abstract void Do(ClientDto Client);
}
public class CreateStrategy:BaseStrategy{
public override void Do(ClientDto Client){
_repo.Save(Client);
}
}
public class UpdateStrategy:BaseStrategy{
public override void Do(ClientDto Client){
_repo.Update(Client);
}
}
public class DeleteStrategy:BaseStrategy{
public override void Do(ClientDto Client){
_repo.Delete(Client);
}
}
So, we have an abstract class, and 3 implementations, each one doing something with the client object. Now, the code of the save button in the form will be:
BaseStrategy stg = GetCorrectStrategy();
var Client = PopulateDTO();
stg.Do(Client);
this.close;
And the method GetCorrectStrategy() will instantiate the correct Strategy implementation, depending if the user is creating, editing or deleting the client.
I hope this answer will help you. But if didn't help you, I suggest you read about strategy pattern, It's one of the best uses of polymorphism in my opinion
Since several people have already given fine examples of polymorphism, I'll offer a different perspective that really helped me to grok it.
In functional programming, functions are the first class concepts in contrast to OOP where objects are supreme.
Polymorphism is to OOP what pattern matching is to FP. Here is a function that uses pattern matching (using an ML style syntax).
let f x =
match x with
| T -> //do stuff with a T to return some value
| S -> //do stuff with an S to return some value
| U -> //do stuff with a U to return some value
| V -> //do stuff with a V to return some value
So when you use the function f, you can pass it an object of either type T, S, U, or V. In strongly typed FP languages like F#, the type of x is denoted T|S|U|V. Such types are commonly referred to as Sum types or Tagged Unions.
If we fix up your example to make Human an abstract class, then it will become clear that polymorphism in OOP just gives you a way of expressing a sum type.
Thus, CleanTheRoom is a function that takes a type Human. But Human is just the name for the type Man|Woman|Child which is a sum type. The big difference between languages like C# and functional languages like F# is that one treats objects as top level things while the other treats functions as top level things. Also, everything in OOP languages like C# must have names. In a functional language we could denote the type Man|Woman|Child without having to explicitly name it.
The key is not to think of the code as having different CleanTheRoom methods, but rather think of CleanTheRoom as one method that takes a type Man|Woman|Child (which is named Human). Polymorphism is just the implementation detail.
In summary, polymorphism (especially with abstract classes) basically just give you a way to name sum types and do pattern matching.
See:
http://en.wikipedia.org/wiki/Tagged_union
http://en.wikipedia.org/wiki/Algebraic_data_type
An example in C#:
This is my class file
class parent
{
public virtual string saySomething(string s)
{
return s+":Parent";
}
}
class man : parent
{
public override string saySomething(string s)
{
return s+":Man";
}
}
class woman : parent
{
public override string saySomething(string s)
{
return s+":Woman";
}
}
class child : parent
{
public override string saySomething(string s)
{
return s+":Child";
}
}
Create Four Buttons and a label.
Here is the implementation on a simple form1
private void Form1_Load(object sender, EventArgs e)
{
p1= new parent();
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = p1.saySomething("I am parent!");
}
private void button2_Click(object sender, EventArgs e)
{
p1 = new man();
label1.Text = p1.saySomething("I am man!");
}
private void button3_Click(object sender, EventArgs e)
{
p1 = new woman();
label1.Text = p1.saySomething("I am woman!");
}
private void button4_Click(object sender, EventArgs e)
{
p1 = new child();
label1.Text = p1.saySomething("I am child!");
}
Is it run-time polymorphism?
P1 is an object. Depending upon the situation (Context), a button click, it is executing different piece of code. So, p1 is behaving differently depending upon the click event.
class Program
{
static void Main(string[] args)
{
List<ICleanTheRoom> cleanerList = new List<ICleanTheRoom>
{
new Child(),
new Woman(),
new Man()
};
foreach (var cleaner in cleanerList)
{
cleaner.CleanTheRoom();
}
}
}
internal interface ICleanTheRoom
{
void CleanTheRoom();
}
// No need for super type
//class Human : ICleanTheRoom
//{
// public virtual void CleanTheRoom()
// {
// }
//}
internal class Woman : ICleanTheRoom
{
public void CleanTheRoom()
{
throw new NotImplementedException();
}
}
class Man: ICleanTheRoom
{
public void CleanTheRoom()
{
throw new NotImplementedException();
}
}
class Child: ICleanTheRoom
{
public void CleanTheRoom()
{
throw new NotImplementedException();
}
}
Is it a new object created each time at runtime, clearly inheriting but no polymorphing.

How to cast an interface to its sub interface?

imagine you have the following interfaces:
public interface IInterfaceA : IInterfaceX
{
//
// declarations
//
}
public interface IInterfaceB : IInterfaceX
{
//
// declarations
//
}
public interface IInterfaceC : IInterfaceX
{
//
// declarations
//
}
Now I want to replace the following three methods which perform almost the same with a single function:
class SomeClass
{
IInterfaceA myVarA;
IInterfaceB myVarB;
IInterfaceC myVarC;
void SomeMethodA(IInterfaceX someVarX)
{
myVarA = (IInterfaceA)someVarX;
}
void SomeMethodB(IInterfaceX someVarX)
{
myVarB = (IInterfaceB)someVarX;
}
void SomeMethodC(IInterfaceX someVarX)
{
myVarC = (IInterfaceC)someVarX;
}
}
I thought about something like:
void SomeMethod(IInterfaceX targetVar, IInterfaceX someVarX)
{
//
// here's my problem
//
targetVar = (CastIDontKnowHowToPerform)someVarX;
}
which is used sth. like
SomeMethod(myVarA, someVarX);
SomeMethod(myVarB, someVarX);
SomeMethod(myVarC, someVarX);
So my questions are:
Is it possible what I want to get?
How to perform this cast I don't know how to perform?
Perhaps a design pattern is more appropriate
I'm just looking for the best way to refactor those three functions by replacing them by a single one.
Things I've tried so far:
I used things like object.GetType() and object.GetType().GetInterfaces() which works well to get the type of an object or its interface(s) but none to set the type of an object to its interface.
Hope you can help me...
Regards,
Inno
[EDIT]
Ah, damn it... after clicking "Ask your question" and having a short look at it this seems to a be typical case for a generic function (or a template in C++-term).
[/EDIT]
void SomeMethod<T>(out T targetVar, IInterfaceX someVarX) where T: IInterfaceX
{
targetVar = (T) someVarX;
}
One possibility is the "is" operator:
void SomeMethod(IInterfaceX someVarX)
{
if (someVarX is IInterfaceA)
SomeMethodA((IInterfaceA)someVarX);
else if (...
}
A better method would be to put the operation into the IInterfaceX to avoid casting altogether:
void SomeMethod(IInterfaceX someVarX)
{
someVarX.SomeMethod();
}

Categories