I am trying to separate multiple parts of a function using Scopes but it doesn't see to work as shown in the following code
private static void Method()
{
{
//Code execution stops here. Although the return is defined inside a scope.
return;
}
{
Console.WriteLine("Whowaaah");
}
}
So what am i doing wrong ?
A block (i.e. a sequence of statements within curly braces) affects the visibility of variables defined within it, not program flow. What you are seeing is completely normal behavior.
Perhaps you are looking for separate methods?
It's OK to have many methods even if they contain only a line of code. This will be easier to maintain, especially since it sounds like you want to have one method that controls many other methods.
Two possible solutions for what you are doing could be this:
If you need to do multiple things:
private static void Method()
{
if(ShouldDoSenseless1())
{
Senseless1();
}
if(ShouldDoSenseless2())
{
Senseless2();
}
if(ShouldDoSenseless3())
{
Senseless3();
}
// etc.
}
Or, if you should only do a single thing among a list of choices:
private static void Method1()
{
var doWhatNow = WhatStepShouldBePerformed();
switch(doWhatNow)
{
case 1:
DoSenseless1:
break;
case 2:
DoSenseless1:
break;
case 3:
DoSenseless1:
break;
break;
// etc.
}
}
Related
So I'm trying to make a 2D game (C#) where the player has different skills that they can use. The problem is that I don't know how to call a function with the string containing the skill name. There is always another way to do it, which is by making a really long list full of if-statements to check if the skill is named something, but this seems far from ideal.
Let's say a skill is called "Skill1". Is there any way to call a function called Skill1() by using the string "Skill1"? It would really help with making the code look good.
Thanks in advance
What you're looking for are delegates (and more specifically a dictionary of delegates).
void Main()
{
var things = new Dictionary<string, Action>
{
{"Thing1", DoThing1},
{"Thing2", DoThing2},
{"Thing3", DoThing3},
};
things["Thing1"]();
things["Thing3"]();
things["Thing2"]();
}
public void DoThing1()
{
Console.WriteLine("In Do Thing 1");
}
public void DoThing2()
{
Console.WriteLine("In Do Thing 2");
}
public void DoThing3()
{
Console.WriteLine("In Do Thing 3");
}
For more information, search for Delegates, Actions and Funcs.
Delegates are a good option but if you want to keep it simple you can use switch statement instead of if statements and it will be easy to maintain.
It's basic but maybe it will help
static void Main(string[] args)
{
Console.WriteLine("call skill");
string _skill = Console.ReadLine();
CallSkills(_skill);
}
public static void CallSkills(string skillname)
{
switch (skillname)
{
case "skill1":
//call skill1 method
break;
case "skill2":
//call skill2 method
break;
case "skill3":
//call skill3 method
break;
case "skill4":
//call skill4 method
break;
case "skill5":
//call skill5 method
break;
default:
break;
}
}
An alternative to using a dictionary with delegates is to using a switch expression with delegates.
One possible approach is to create a method that associates all relevant skill names with the appropriate Skill* method, as well as using the discard pattern (_ => ...; here: _ => null) to define a default value for any skillName that does not match any defined skill names in the expression:
private static Action GetSkillAction(string skillName)
{
return skillName switch
{
"Skill1" => Skill1,
"Skill2" => Skill2,
_ => null
};
}
To make it easier to use that method, you could create a method to actually perform a skill (by skill name). This method handles receiving a non-existing skill by only calling the associated action if the action is unlike null:
public static void PerformSkillAction(string skillName)
{
var action = GetSkillAction(skillName);
if (action != null)
{
action();
}
}
Now, calling
PerformSkillAction("Skill1");
will result in a call to Skill1(), whereas calling
PerformSkillAction("Banana");
will not call anything.
Example fiddle here.
Although this question might sound stupid at first glance, please hear me out.
c#'s get{} and set{} methods are increadibly usefull in situations when you do not know how you porgramming goals will evolve while you build your code. I enjoyed their freedom many a time and now I wonder if there is something similar for methods but in a bit different light.
As I am working in gamedev, it is a very common practice to extend/update/improve existing code day-in day-out. Therefore, one of the patterns I taught myself to follow is to never use "return" statement more than once in the most of my methods.
The reason why I do this is to always be able to write something at the bottom of the method and be sure that the line I have written is always called 100% of the time once my method ENDS.
Here is an example:
public void Update()
{
UpdateMovement();
if (IsIncapacitated)
return;
if (IsInventoryOpened)
{
UpdateInventory();
return;
}
if (Input.HasAction(Actions.Fire))
{
Fire();
return;
}
else if (Input.HasAction(Actions.Move))
{
Move(Input.Axis);
return;
}
}
Now imagine that this method is called dozens of times in many places across the entirety of your project. And then the next day you decide that you need to call UpdatePhysics() method at the very end of your Update() method. In this case there are only 4 returns, it could be much worse in reality.
Then imagine that such decesions happen several times a day every day. Bad planning you may say? I might agree with you, but I do think that freedom of development is essential in modern coding. I don't think you should kill yourself trying to anticipate every turn your project might take before you start writing code.
One way to insure that problems like the one I described above never happen is to rewrite the method as follows:
public void Update()
{
UpdateMovement();
if (!IsIncapacitated)
{
if (IsInventoryOpened)
{
UpdateInventory();
}
else
{
if (Input.HasAction(Actions.Fire))
{
Fire();
}
else if (Input.HasAction(Actions.Move))
{
Move(Input.Axis);
}
}
}
}
In this case you can always add a line at the bottom and be sure it will always get called nomatter what.
So I wanted to ask if there is another approach that could allow for placing "return"-s wherever you wish while still being able to add extra code easily at the bottom of the method any time. Maybe there is any form of syntax in c# that does it for you? Or maybe there is a better coding practice that eliminates such problem?
UPDATE: As I started receiving answers, I realized that I need to clarify things a bit.
'try/catch/finally' is an overkill - I will never use them. They have severe performance penalty on catch(), they screw up 'Edit and continue' feature in Visual Studio and they just look ugly.
Idealy I need to be able to access local variables in the Update() method from any code I decide to add at the end of the method,
When I wrote the question, I already had an answer - nesting. My second code sample has no returns and, therefore I can add code to the very bottom of the method and it will work 100% of the time, while I will be able to use local variables. Nesting is bad though, and that is why I am here searching for a BETTER solution.
UPDATE 2: I was actually mistaken about try/catch because I did not know that you can skip catch alongside it's performance penalties and only have finally. However, this solution is still worse than the nesting solution provided in the question, because in your newly added finally block you no longer can use return statements. So basically you can do whatever you want when you write the method the first time, but once you extend it - you are back to nesting.
One simple suggestion is to wrap your function. For example:
public void UpdateCall()
{
Update();
AfterUpdate code goes here.
}
Using a try/finally block should work;
public void Update()
{
try
{
UpdateMovement();
if (IsIncapacitated)
return;
if (IsInventoryOpened)
{
UpdateInventory();
return;
}
if (Input.HasAction(Actions.Fire))
{
Fire();
return;
}
else if (Input.HasAction(Actions.Move))
{
Move(Input.Axis);
return;
}
}
finally
{
//this will run, no matter what the return value
}
}
The performance costs of using try/finally (not try/catch!) are minimal
You cannot use return in the finally block;
If you were able to return a different value from the Finally block,
this value would always be returned, whatever the outcome of the
instructions above. It just wouldn't make sense..
I suggest wrapping the code into try..finally block:
public void Update() {
try {
...
// you can return
if (someCondition)
return;
...
// throw exceptions
if (someOtherCondition)
throw...
...
}
finally {
// However, finally will be called rain or shine
}
}
You can use try-catch-finally (C#-Reference) without a catch block.
try
{
//your business logic here
}
finally
{
//will be called anytime if you leave the try block
// i.e. if you use a return or a throw statement in the try block
}
With the modern c# 8 syntax you may introduce some disposable 'ScopeFinalizer' object or name whatever you want:
public class ScopeFinalizer : IDisposable
{
private Action delayedFinalization;
public ScopeFinalizer(Action delayedFinalization)
{
this.delayedFinalization = delayedFinalization ?? throw new ArgumentNullException(nameof(delayedFinalization));
}
public void Dispose()
{
delayedFinalization();
}
}
//usage example
public async Task<bool> DoWorkAsyncShowingProgress()
{
ShowActivityIndicator();
using var _ = new ScopeFinalizer(() =>
{
// --> Do work you need at enclosure scope leaving <--
HideActivityIndicator();
});
var result = await DoWorkAsync();
HandleResult(result);
//etc ...
return true;
}
Useful link:
https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#using-declarations
Don't use the returns as it makes your code smelly.
public void Update()
{
UpdateMovement();
if (IsIncapacitated){
return;
}
if (IsInventoryOpened)
{
UpdateInventory();
}
else if (Input.HasAction(Actions.Fire))
{
Fire();
}
else if (Input.HasAction(Actions.Move))
{
Move(Input.Axis);
}
}
Also, your second solution has too much nesting, also confusing and smelly.
A problem with the current approach is that it requires changes to the Update() method whenever we want to add a new action.
Another approach is to remove the hard-coding of the update actions and configure the class with a set of update actions.
From the code given here we have
Actions that always happen (e.g. UpdateMovement)
Actions that happen if a test is passed (e.g. UpdateInventory)
Actions that cause a return if they are executed (e.g. Fire())
We can encapsulate these in an interface
public interface IUpdateAction
{
bool ShouldUpdate();
// return true if we want this to be the last action to be executed
bool Update();
}
and wrap various actions and decisions in the class using
public class DelegateUpdateAction : IUpdateAction
{
private Func<bool> _updateAction;
private Func<bool> _shouldUpdateCheck;
public DelegateUpdateAction(Action action, bool isLastAction = false, Func<bool> shouldUpdateCheck = null)
: this(() =>
{
action();
return isLastAction;
},
shouldUpdateCheck)
{ }
public DelegateUpdateAction(Func<bool> updateAction, Func<bool> shouldUpdateCheck = null)
{
if(updateAction == null)
{
throw new ArgumentNullException("updateAction");
}
_updateAction = updateAction;
_shouldUpdateCheck = shouldUpdateCheck ?? (() => true);
}
public bool ShouldUpdate()
{
return _shouldUpdateCheck();
}
public bool Update()
{
return _updateAction();
}
}
To replicate the example we could use
public class Actor
{
private IEnumerable<IUpdateAction> _updateActions;
public Actor(){
_updateActions = new List<IUpdateAction>{
new DelegateUpdateAction((Action)UpdateMovement),
new DelegateUpdateAction((()=>{ }), true, () => IsIncapacitated),
new DelegateUpdateAction((Action)UpdateInventory, true, () => IsInventoryOpened),
new DelegateUpdateAction((Action)Fire, true, () => Input.HasAction(Actions.Fire)),
new DelegateUpdateAction(() => Move(Input.Axis), true, () => Input.HasAction(Actions.Move))
};
}
private Input Input { get; set; }
public void Update()
{
foreach(var action in _updateActions)
{
if (action.ShouldUpdate())
{
if (action.Update())
break;
}
}
}
#region Actions
private bool IsIncapacitated { get; set; }
private bool IsInventoryOpened { get; set; }
private void UpdateMovement()
{
}
private void UpdateInventory()
{
}
private void Fire()
{
}
private void Move(string axis)
{
}
#endregion
}
The actions are executed in the order in which they are registered, so this gives us the ability to inject a new action into the execution sequence at any point.
UpdateMovement() always happens and doesn't return
IsIncapacitated() is a test with a null action. It returns if executed so we get our 'do-nothing-else-if-incapacitated' behaviour
UpdatedInventory() occurs if the inventory is open and then returns
Each of the HasAction checks return if executed.
Note If I have read the question better before writing the code I would have reversed the defaults as most actions seem to be 'return if executed'.
If we need to add 'UpdatePhysics()', we add a method to the class and add an entry in the appropriate place in the list of update actions. No changes to the Update method.
If we have derived classes with different actions we can add the facility to add (or remove) actions in the derived classes and either inherit and modify the default actions or replace them with a different set.
After seeing the other solutions I can't think of a truly dynamic solution that has only the functions you want to call in the update loop.
Here are some ideas though I doubt any of them are better than making a good design. Joe C has the correct idea of how you should structure this kind of thing.
You could make a container of actions that need to be performed each update loop. Remove and add specific actions depending on the changes to circumstances. Such as a IsNowIncapacitated event that remove the Handling action from the list. Though I have little experience with actions, I believe you can set up delegates that the actions point to. Not sure what the cost to performance is.
A temporary thing you could do so you can keep adding logic is have your return statements return a void function with some constant logic you want performed, though all it really will do is separate your update code between two methods. It is not very neat or as efficient as structuring your code appropriately like in Joe C's example.
public void PostUpdate()
{
//stuff that always happens
PhysicsUpdate();
}
public void Update()
{
UpdateMovement();
if (IsIncapacitated)
return PostUpdate();
if (IsInventoryOpened)
{
UpdateInventory();
return PostUpdate();
}
}
Maybe I came up with nonsense but I wonder such a decision.
There are several resource files in library-project Resources:
Resources.File1
Resources.File2
Resources.File3
I add a class to the Resources project:
public static class Foo {
static ? GetResource(Object obj) {
switch (obj) {
case obj.1: { return Resources.File1; }
case obj.2: { return Resources.File2; }
case obj.3: { return Resources.File3; }
}
}
Of course what I have written is completely wrong, but I think it's obvious what I want to do.
The auto-generated Resources class exposes its underlying ResourceManager. You can simply use it manually:
var data = Resources.ResourceManager.GetObject("File" + n);
Make sure to use the appropriate function: GetString, GetStream etc.
I have the following code which executes in sequence, method after another.
I load the request, perform a couple of checks like checking if a response already exists for this request, if not, I call the service and receive the response which I save to the DB.
I was looking for a design pattern I can use in such a case, I thought of posting this here and get some ideas.
public class Manager
{
public void PutRequest()
{
//Do Something
if (loadRequest())
{
callService();
//Do Something
saveResponse();
}
}
private bool loadRequest()
{
bool isExist = checkIfResponseExists();
if (!isExist)
{
// If false, load request from DB
}
return !isExist;
}
private bool checkIfDataExists()
{
//Check if a response already exists in the DB for this request
}
private void callService()
{
//Call the service and receive the response
}
private void saveResponse()
{
//Store the response in the DB
}
}
Patterns are used for solving some problems. What problem your current code have? I don't see any duplicated code, beside names of methods. There is no pattern, which fixes method naming problem.
Yes, your code need some refactoring, but not to patterns. Better class and method naming is a first step. Also, I'd removed field isExist.
public class Manager
{
public void PutRequest()
{
//Do Something
if (!CheckIfResponseExists()) // returns boolean value
LoadRequestFromDB()
CallService();
//Do Something
SaveResponse();
}
}
Check the design pattern called Strategy, it defines an interface common to all supported algorithms and each concrete strategy implements an algorithm
http://www.oodesign.com/strategy-pattern.html
It seems like it'd be more useful for several of these methods to be functions. So instead of having a method who's responsibility is to both check for a condition and do some other actions, you have a function that checks for a condition then the method that called it does some action depending on the result. (Kind of the SRP applied to methods...)
public void DoAllTheThings!() // Oops, Ruby syntax creeping in :P
{
if(!WeCanDoIt())
{
MakeItSo(); // So that we can do it...
}
NowWeCanDoAllTheThings();
}
private bool WeCanDoIt() {}
private void MakeItSo() {}
private void NowWeCanDoAllTheThings() {}
Command + Composite.
Some people consider the use of an if/then Command - in your case that would be in putRequest - in a Composite a kind of Chain Of Responsibility.
While selecting a pattern you should consider scalability of the application
One of the pattern you can apply is state pattern
There will be two states.
Response is already there
Need to process the new response
been looking but not much luck, i want to create a function that only allows certain items to be passed as the first parameter.
e.g. it should only allow the following strings:
"error", "warning", "info"
then the call would be
showme("error");
or showme("warning");
or showme("info");
can this be done? I know I can define
showme(string type){}
but ideally I need showme(string type "error"){}
I suggest an enum
public enum ErrorType {
error,
warning,
info
}
public void ShowMe(ErrorType errorType) {
switch (errorType) {
case ErrorType.error:
//do stuff
break;
case ErrorType.warning:
//do stuff
break;
case ErrorType.info:
//do stuff
break;
default:
throw new ArgumentException("Invalid argument supplied");
break;
}
}
//Invoke the method
ShowMe(ErrorType.info);
As per Rozuur's comment, an Enum would be a clean option. Failing that you could try using code contracts: http://www.cauldwell.net/patrick/blog/CodeContracts.aspx
You can wrap up the logic that depends on your set of values into a class with private constructor, and retrieve instances either through singleton properties or through a factory method.
Something like:
public class StringConstraint
{
private StringConstraint()
public static readonly StringConstraint error = new StringConstraint()
...
public void DoStuffWithStringValue()
{
// Here you do the logic that depends on your particular string value
// e.g. (always) log a message as an error
}
}
This obliges you to only ever pass instances that conform to the logic you want to implement for each of your three strings.