Hi guys I have one question,
If I have a sequence of methods for example:
Main()
{
Method1();
}
Method1()
{
Method2();
}
Method2()
{
Method3();
}
Method3()
{
ObtainsUserPermission(httpContext.Current.User.Name);
}
How is the best way to do it, using the parammeter "httpContext.Current.User.Name" in the last Method3, or passing by parammeter in each method? Like this:
Main()
{
Method1(httpContext.Current.User.Name);
}
Method1(string name)
{
Method2(name);
}
Method2(string name)
{
Method3(name);
}
Method3(string name)
{
ObtainsUserPermission(name);
}
thank you for all.
This smells like magic parameters.
A good rule of thumb is - if you wish your execution of method3() to depend on the name, pass the name as a parameter. In general, you shouldn't use globals inside functions. It can become complicated to debug and maintain. An exception is members of a class, in which case your members are visible inside the methods and there is no need to pass them as parameters.
Related
Is possible in groovy to remove a object from list through the object?
I know how to remove from the list, but can I remove it from the list with only know the reference of the certain object. (I don't want a null object in the list)
Probably it is not possible, but Groovy have surprises.
class Foo() {
List<Boo> boos
}
class BoosHandler {
void doSomethingWithBoo() {
boos.each {
analyse(it)
}
}
void analyse(Boo boo) {
if(boo.something == "wrong") {
remove(boo) // Pseudo style for removing object boo from the list (Foo.boos)
}
}
}
No, not possible.
I would also not do this, as in a multi-threaded environment it would be unpredictable...
You're better (as you probably know) doing:
List<Boo> filter(String notThis) {
boos.findAll { it.something != notThis }
}
ie: return a new list, and don't change the original
What is the simplest way to implement one-method interfaces in Groovy?
Ones, like Runnable or FileFilter?
For example, to list files I wrote java-like:
// works Java-like
new File(".").listFiles(new FileFilter() {
#Override
boolean accept(File file) {
!file.isDirectory()
}
}).each { println it.absolutePath }
but closure-like does not work
// does not work
new File(".").listFiles({file -> !file.isDirectory()}).each { println it.absolutePath }
Is it possible to implement it using closures or something?
In this particular example the following piece of code should work:
return [downloadFolder: downloadFolder.listFiles({ file ->
return !file.isDirectory()
})]
Basically interfaces can be implemented using a Map.
EDIT
In this particular example it should be:
new File(".").listFiles({file -> !file.isDirectory()} as FileFilter).each { println it.absolutePath }
I'm trying to create a haxe.ds.HashMap where the keys are an object I don't control. Thus, they don't implement the hashCode method and I can't change them to.
I would really like to use an abstract to accomplish this, but I'm getting some compile time errors.
Here is the code I'm playing with:
import haxe.ds.HashMap;
abstract IntArrayKey( Array<Int> ) from Array<Int> {
inline public function new( i: Array<Int> ) {
this = i;
}
public function hashCode(): Int {
// General warning: Don't copy the following line. Seriously don't.
return this.length;
}
}
class Test {
static function main() {
var hash = new HashMap<IntArrayKey, Bool>();
}
}
The compile errors are:
Test.hx:15: characters 19-51 : Constraint check failure for haxe.ds.HashMap.K
Test.hx:15: characters 19-51 : IntArrayKey should be { hashCode : Void -> Int }
But the moment I change my abstract over to a class, it compiles fine:
import haxe.ds.HashMap;
class IntArrayKey {
private var _i: Array<Int>;
inline public function new( i: Array<Int> ) {
this._i = i;
}
public function hashCode(): Int {
// General warning: Don't copy the following line. Seriously don't.
return this._i.length;
}
}
class Test {
static function main() {
var hash = new HashMap<IntArrayKey, Bool>();
}
}
It's the exact same hashCode implementation, just a different context. Is there some way to accomplish this? Or is it a language limitation?
As far as I know, abstracts currently can't satisfy type requirements like this, quoting from the code:
abstract HashMap<K:{ function hashCode():Int; }, V >(HashMapData<K,V>) {
So, I doubt you could do that in a meaningful way.
Important point would be that while abstracts can sometimes provide overhead-free abstractions which is quite useful for optimizations, the time needed to instantiate(probably hidden from sight with abstract Name(Holder) to Holder having #:from Array<Int> and #:to Array<Int>) holder for your array which will have the required method isn't that high(compared to usual runtime overheads), and unless it is a really frequent code, should be your first way to go.
However, the HashMap code itself is quite short and simple: here.
You could just copy it and make it work with your example. Maybe you could even forge a better yet generic version by using interfaces(though I'm not sure if abstracts can actually implement them).
I am relatively new to C#, maybe you could help me with this.
I got a couple of methods callServiceXY(param1, param2, ...) that call a certain service. For many reasons these service calls can go wrong (and I don't really care for the reason in the end). So basically I need to always wrap them with something like this - to have them execute again if something goes wrong:
var i = 3;
while(i>0)
try{
call...()
} catch{
i--;
}
i=0;
}
I'd rather write this code only once. Could I somehow have a method like tryXtimes(int x, callService()) that allows me to execute an undefined or anonymous method? (I have Javascript in mind where this is possible...)?
Yes this is possible. C# 3.5 added support for Action and Func<T> types. An Action won't return any value, a Func will always return a value.
You have several different versions that also accept a number of parameters. The following Console Applications describes how you could do this:
using System;
namespace Stackoverflow
{
class Service
{
public int MyMethod() { return 42; }
public void MyMethod(string param1, bool param2) { }
public int MyMethod(object paramY) { return 42; }
}
class Program
{
static void ExecuteWithRetry(Action action)
{
try
{
action();
}
catch
{
action();
}
}
static T ExecuteWithRetry<T>(Func<T> function)
{
try
{
return function();
}
catch
{
return function();
}
}
static void Main(string[] args)
{
Service s = new Service();
ExecuteWithRetry(() => s.MyMethod("a", true));
int a = ExecuteWithRetry(() => s.MyMethod(1));
int b = ExecuteWithRetry(() => s.MyMethod(true));
}
}
}
As you can see, there are two overloads for ExecuteWithRetry. One returning void, one returning a type. You can call ExecuteWithRetry by passing an Action or a Func.
--> Edit: Awesome! Just a little extra code to complete the example:
With anonymous function/method:
ExecuteWithRetry(() =>
{
logger.Debug("test");
});
And with more parameters (action, int)
Method header:
public static void ExecuteWithRetryX(Action a, int x)
Method call:
ExecuteWithRetryX(() => { logger.Debug("test"); }, 2);
I would use the strategy/factory pattern(s) for this. This answer https://stackoverflow.com/a/13641801/626442 gives and example of the use of the strategy/factory pattern with links. The question at the above link will give you another type of example where this pattern can be adopted.
There are great examples of these design patterns here and the following are detailed intros to the Strategy pattern and the Factory pattern. The former of the last two links also shows you how to combine the two to do something like what you require.
I hope this helps.
Try following
void CallServiceXY(params object []objects)
{
Console.WriteLine("a");
throw new Exception("");
}
void Retry(int maxRetryCount, Action<object[]> action, params object[] obj)
{
int retryCount = 1;
while ( retryCount <= maxRetryCount)
{
try
{
action(obj);
return;
}
catch
{
retryCount++;
}
}
}
void Main()
{
Retry(2,CallServiceXY);
Retry(2,CallServiceXY,"");
Retry(2,CallServiceXY,"","");
}
Demo here
Trick is Action<object[]> that accepts object array and return void and params keyword in Retry method.
To return non void value, Change Action<object[]> to Func<T, object[]>.
I am trying to access function of a class in switch case but identifier not found error is coming.Here is the example.
class menu {
switch(a) {
case 1:
tej t;
t.do_something
break;
}
};
class tej:public menu {
public:
void do_something() {
body of function
}
};
There are a few things missing from your code:
Have you forgotten the parentheses after do_something?
Also, are you missing a function somewhere? You can't put a switch statement directly in the class.
You can't declare variables directly in the switch statement. You need an extra set of braces for that.
class menu {
public:
void do_switch(int a) { // Note function
switch(a) {
case 1:
{ // You need an extra set of braces if you intend to declare variables
tej t;
t.do_something(); // <-- N.B. Parentheses!
}
break;
}
} // Note extra brace to close function
};
class tej:public menu {
public:
void do_something() {
// body of function
}
};
I highly recommend that you pick up a good introductory C++ book, as the things you're getting wrong are quite fundamental to the language. It's less frustrating that way.