Is there a DRY way to reuse a forloop? - dry

Say I have a slightly complicated for loop, being used in different situations. Is there a way to extract that forloop and still keep the code readable?
For example:
private function bar(){
for(i=0;i<arrayA.length;i++){
if(arrayA[i].someVar == foobar){
doSomethingA();
}
}
}
private function foo(){
for(i=0;i<arrayA.length;i++){
if(arrayA[i].someVar == foobar){
doSomethingB();
}
}
}
The way I would do this/answer the question is to write something like this:
private function loopFunction(callback:Function){
for(i=0;i<arrayA.length;i++){
if(arrayA[i].someVar == foobar){
callback();
}
}
}
private function bar(){
loopFunction(doSomethingA);
}
private function foo(){
loopFunction(doSomethingB);
}
However I find this approach makes the code rather unreadable at times, as you aren't quite sure who is doing what when. Especially if the function passed in comes from another class. Is there a better way to do this?
Another reason why this sollution may not work is if you need to pass in different parameters to the callback function. For example.
private function bar(){
for(i=0;i<arrayA.length;i++){
if(arrayA[i].someVar == foobar){
doSomethingA(arrayA);
}
}
}
private function foo(){
for(i=0;i<arrayA.length;i++){
if(arrayA[i].someVar == foobar){
doSomethingB(i);
}
}
}

As others have pointed out, higher-order functions such as map, fold, and filter provide this kind of functionality. Of course, the precise implementation will vary by language.
Here's a sample in C#:
var foobarList = arrayA.Where(x => x.someVar == foobar).ToList();
foobarList.ForEach(x => doSomethingA());
foobarList.ForEach(x => doSomethingB());
And VB.NET:
Dim foobarList = arrayA.Where(Function(x) x.someVar = foobar).ToList()
foobarList.ForEach(Function(x) doSomethingA())
foobarList.ForEach(Function(x) doSomethingB())
And Javascript:
var foobarList = arrayA.filter(function(x) { return x.someVar == foobar });
foobarList.forEach(function(x) { doSomethingA(); });
foobarList.forEach(function(x) { doSomethingB(); });

You should stop abstracting when it is making your code worse :)
Many languages have higher level constructs built in to deal with common iteration patterns. C++11 has range-based for loops to make iterating over data structures less tedious. Functional languages often have map, fold and filter.

Related

Organize functions - where do you test parameters of function?

i wonder what that would be the best solution on the area to test parameters of function.
"SRP = one function, one responsibility"
few solutions :
at the beginning of the function
in a other function
// example "at the beginning of the function"
function main() {
let arr_errors = [];
// many tests
//at the end of tests, if we are errors, we return an array (how do we distinguish between this errors array and result of function ?)
if([] !== arr_errors) {
return arr_errors;
}
// many process
return result;
}
// example "in a other function"
function main() {
if([] !== (arr_errors = testA()) {
displayErrors(arr_errors);
}
else {
return A2();
}
}
What do you think about ?
Thanks in advance.

Is there any concern about returning generic type object in Dart?

I want to implement a different error handling approach in a project without chaining exceptions.
To make it simple as possible, I am tend to write my own basic either-like model.
class Either<F, T> {
final F failure;
final T value;
const Either(this.failure, this.value);
Object check (){
if (failure != null) return failure;
return value;
}
}
I am concerning about returning the type Object, is there any problem or considerations with that in Dart or any other language?
Edit:
or returning dynamic type...
dynamic check(){
if (failure != null) return failure;
return value;
}
I think in your case, it's kind of a wired implementation. The question is, what do you want to do with the actual implementation ? Do you want to replace an if else that will appear over and over? In that case, what would you do if you have to handle the error (failure) ? I think a better approach is to use functions as parameters. Here's a short suggestion.
class Either<T, F> {
T value;
F fail;
Either(this.value, this.fail);
void check(success(T value), {failure(F fail)}) {
if (fail != null && failure != null) {
failure(fail);
} else if (value != null) {
success(value);
}
}
}
class SomeClass {
void checkTheImplementation() {
Either<String, Error> maybeString = Either("testing", null);
// if you don't want to handle the error.
maybeString.check((value) => print(value));
// if you want to handle the error
maybeString.check((value) => print(value), failure: (err) {
print(err.toString());
});
}
}
I have looked over and decided to go with baihu92's either_type way. It's much more clear and comprehensible than either in the dartz package. Here is my implementation:
and the usage is like:

Private functions in Typescript

Note that I have already checked out this question, but the answers to it do not seem to be correct.
If I wanted to have private methods in regular JavaScript (which the answers suggest is not possible), I'd do something like this:
function myThing() {
var thingConstructor = function(someParam) {
this.publicFn(foo) {
return privateFn(foo);
}
function privateFn(foo) {
return 'called private fn with ' + foo;
}
}
}
var theThing = new myThing('param');
var result = theThing.publicFn('Hi');//should be 'called private fn with Hi'
result = theThing.privateFn; //should error
I'm trying to figure out what the syntax is to encapsulate the private function in TypeScript. If it turns out you can't, that's fine, but given that the answers in that older question incorrectly state that you can't create private methods in ordinary JavaScript, I am unwilling to just take those answers as authoritative.
So, it turns out it's just as simple as marking the method private. The thing I was missing is to be able to use the method is you need to use the this keyword.
So
export class myThing {
constructor(){}
publicFn(foo) {
return this.privateFn(foo);
}
private privateFn(foo) {
return 'called private fn with ' + foo;
}
}

Chain of Responsibility Design Pattern

I want to get an intuitive feeling for Chain of Responsibility pattern. I guess a good way to get that would be to learn about some real world examples. Can you guys share such examples?
One of the things about this pattern is that if the chain has many stages, lets say more than 10, implementation gets quite ugly. What do you guys do about that?
I think the Servlet filters are a good example. The chain is built for you and you can decide to call the next one. However the construction/wiring is done for you here.
If the 10 is hairy you can simplify with a builder:
interface ChainElement {
void setNext(ChainElement next);
void doSomething();
}
class ChainBuilder {
private ChainElement first;
private ChainElement current;
public ChainBuilder then(ChainElement next) {
if (current == null) {
first = current = next;
} else {
current.setNext(next);
current = next;
}
return this;
}
public ChainElement get() {
return first;
}
}
Then at construction:
ChainElement chain = new ChainBuilder()
.then(new FirstElement())
.then(new SecondElement())
.then(new ThirdElement())
.get();
chain.doSomething();

JavaScript - run once without booleans

Is there a way to run a piece of JavaScript code only ONCE, without using boolean flag variables to remember whether it has already been ran or not?
Specifically not something like:
var alreadyRan = false;
function runOnce() {
if (alreadyRan) {
return;
}
alreadyRan = true;
/* do stuff here */
}
I'm going to have a lot of these types of functions and keeping all booleans would be messy...
An alternative way that overwrites a function when executed so it will be executed only once.
function useThisFunctionOnce(){
// overwrite this function, so it will be executed only once
useThisFunctionOnce = Function("");
// real code below
alert("Hi!");
}
// displays "Hi!"
useThisFunctionOnce();
// does nothing
useThisFunctionOnce();
'Useful' example:
var preferences = {};
function read_preferences(){
// read preferences once
read_preferences = Function("");
// load preferences from storage and save it in 'preferences'
}
function readPreference(pref_name){
read_prefences();
return preferences.hasOwnProperty(pref_name) ? preferences[pref_name] : '';
}
if(readPreference('like_javascript') != 'yes'){
alert("What's wrong wth you?!");
}
alert(readPreference('is_stupid') ? "Stupid!" : ":)");
Edit: as CMS pointed out, just overwriting the old function with function(){} will create a closure in which old variables still exist. To work around that problem, function(){} is replaced by Function(""). This will create an empty function in the global scope, avoiding a closure.
I like Lekensteyn's implementation, but you could also just have one variable to store what functions have run. The code below should run "runOnce", and "runAgain" both one time. It's still booleans, but it sounds like you just don't want lots of variables.
var runFunctions = {};
function runOnce() {
if(!hasRun(arguments.callee)) {
/* do stuff here */
console.log("once");
}
}
function runAgain() {
if(!hasRun(arguments.callee)) {
/* do stuff here */
console.log("again");
}
}
function hasRun(functionName) {
functionName = functionName.toString();
functionName = functionName.substr('function '.length);
functionName = functionName.substr(0, functionName.indexOf('('));
if(runFunctions[functionName]) {
return true;
} else {
runFunctions[functionName] = true;
return false;
}
}
runOnce();
runAgain();
runAgain();
A problem with quite a few of these approaches is that they depend on function names to work: Mike's approach will fail if you create a function with "x = function() ..." and Lekensteyn's approach will fail if you set x = useThisFunctionOnce before useThisFunctionOnce is called.
I would recommend using Russ's closure approach if you want it run right away or the approach taken by Underscore.js if you want to delay execution:
function once(func) {
var ran = false, memo;
return function() {
if (ran) return memo;
ran = true;
return memo = func.apply(this, arguments);
};
}
var myFunction = once(function() {
return new Date().toString();
});
setInterval(function() {console.log(myFunction());}, 1000);
On the first execution, the inner function is executed and the results are returned. On subsequent runs, the original result object is returned.
What about an immediately invoked anonymous function?
(function () {
// code in here to run once
})();
the code will execute immediately and leave no trace in the global namespace.
If this code is going to need to be called from elsewhere, then a closure can be used to ensure that the contents of a function are run only once. Personally, I prefer this to a function that rewrites itself as I feel doing so can cause confusion, but to each their own :) This particular implementation takes advantage of the fact that 0 is a falsy value.
var once = (function() {
var hasRun = 0;
return function () {
if (!hasRun) {
hasRun++;
// body to run only once
// log to the console for a test
console.log("only ran once");
}
}
})();
// test that the body of the function executes only once
for (var i = 0; i < 5; i++)
once();
Elegant solution from Douglas Crockford, spent some time to understand how it works and stumbled upon this thread.
So the wrapper once return function which is just invokes parameter's function you passed. And taking advantage of closures this construction replaced passed function to empty function, or null in original source, after the first call, so all the next calls will be useless.
This is something very close to all other answers, but it is kinda self containing code and you could use it independently, which is good. I am still trying to grasp all the entire mechanism of replacement, but practically it just works perfectly.
function once (func) {
return function () {
var f = func;
func = null;
return f.apply(this, arguments);
};
}
function hi(name) {
console.log("Hi %s", name);
}
sayonce = once(hi);
sayonce("Vasya");
sayonce("Petya");
for those who are curious here is jsbin transformations
(function (){
var run = (function (){
var func, blank = function () {};
func = function () {
func = blank;
// following code executes only once
console.log('run once !');
};
return function(){
func.call();
};
})();
run();
run();
run();
run();
})();
I just ran into this problem, and ended up doing something like the following:
function runOnce () {
if (!this.alreadyRan) {
// put all your functionality here
console.log('running my function!');
// set a property on the function itself to prevent it being run again
this.alreadyRan = true;
}
}
This takes advantage of the fact that Javascript properties are undefined by default.
In addition, the nature of what happens in the "/* do stuff here */" may leave something around that, when present, must mean that the function has run e.g.
var counter = null;
function initCounter() {
if (counter === null) {
counter = 0;
}
}
If not bound to an event, code is usually ran once