Organize functions - where do you test parameters of function? - conceptual

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.

Related

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:

Why is there no compile error since the method only returns in the "if" block?

I am working with Dart in Flutter right now, and in a tutorial I came across this method:
Future getData() async {
http.Response response = await http.get(url);
if (response.statusCode == 200) {
String data = response.body;
return jsonDecode(data);
} else {
print(response.statusCode);
}
}
Why is there no compile error? In Java or C++, there would be an error because if statusCode wasn't 200, the method wouldn't return anything. Is it because Future can act like a void type? Just don't really understand what is going on.
Yes,
When you define a "Future" it automatically defaults to
Future<void> or Future<dynamic>
If you want to force it to a certain return type you must declare it like so.
Future<int> or Future<double>
You get the idea.
However Dart doesn't operate like Java or C++, if you create a function that is supposed to return a value, but in a certain if, else clause there is no return clause, then the function will return null.

what is the correct way to extract two sets of data from a method class

I am new to OOP and still a bit confused by the concepts
I created a class` method that will extract two sets of data from a Zend_Session_Namespace. my problem now is that I don't know how to extract these data when its pulled into another method.
It might be best if I show you what I mean:
Public function rememberLastProductSearched()
{
$session = new Zend_Session_Namespace(searchedproducts);
if ($this->getRequest()->getParam('product-searched')) {
$session->ProductSearched = $this->getRequest()->getParam('product-searched');
return " $session->ProductSearched";
} else {
if ($session->ProductSearched) {
return " $session->ProductSearched ";
}
}
if ($this->getRequest()->getParam('search-term')) {
$session->SearchTerm = $this->getRequest()->getParam('search-term');
return " $session->SearchTerm";
} else {
if ($session->SearchTerm) {
return " $session->SearchTerm ";
}
}
This method should obtain two sets of data i.e the
$session->SearchTerm
$session->ProductSearched
my confusion is this; how do I now extract both sets of data in another method call (that is within the same class).i.e
Above is my attempt to extract the information- but it did not work.
Alternatively, should I have placed the information into an array- if so, can somebody please tell me how I could have done this.
It looks like what you're trying to do is use the product-searched and search-terms from params and store them in the session if they're set, otherwise access previously saved values. It would help a bit to see how you're calling this method, but I would probably modify your code slightly to return the session namespace object instead, since that then contains the two values, regardless of whether they came from params or were there already:
public function rememberLastProductSearched()
{
$searchedProducts = new Zend_Session_Namespace('searchedproducts');
if ($this->getRequest()->getParam('product-searched')) {
$searchedProducts->ProductSearched = $this->getRequest()->getParam('product-searched');
}
if ($this->getRequest()->getParam('search-term')) {
$searchedProducts->SearchTerm = $this->getRequest()->getParam('search-term');
}
return $searchedProducts;
}
I'm assuming you have this method in a controller class, so you'd call it like this:
public function searchAction()
{
$searchedProducts = $this->rememberLastProductSearched();
// do something with the values here
}
you'll then have the two values in $searchedProducts->ProductSearched and $searchedProducts->SearchTerm.
The line "return $something;" will stop the code execution and return the value. If you want to return more than one value, you will need to either return an array or use two separate functions to return the values. If you want to return an array, you could do it this way:
public function rememberLastProductSearched() {
$returnArray = array();
$session = new Zend_Session_Namespace(searchedproducts);
if ($this->getRequest()->getParam('product-searched')) {
$session->ProductSearched = $this->getRequest()->getParam('product-searched');
$returnArray['productSearched'] = $session->ProductSearched;
} else {
if ($session->ProductSearched) {
$returnArray['productSearched'] = $session->ProductSearched;
}
}
if ($this->getRequest()->getParam('search-term')) {
$session->SearchTerm = $this->getRequest()->getParam('search-term');
$returnArray['searchTerm'] = $session->SearchTerm;
} else {
if ($session->SearchTerm) {
$returnArray['searchTerm'] = $session->SearchTerm;
}
}
return $returnArray;
}
In your controller or wherever you wanted to check for those values:
$lastSearch = $this->rememberLastProductSearched();
echo $lastSearch['productSearched']; // Product Searched
echo $lastSearch['searchTerm']; // Search terms
But it might be cleaner to use two function
public function getLastProductSearched() {
$session = new Zend_Session_Namespace(searchedproducts);
if ($this->getRequest()->getParam('product-searched')) {
$session->ProductSearched = $this->getRequest()->getParam('product-searched');
$returnValue = $session->ProductSearched;
} else {
if ($session->ProductSearched) {
$returnValue = $session->ProductSearched;
}
}
return $returnValue;
}
public function getLastSearchTerms() {
$session = new Zend_Session_Namespace(searchedproducts);
if ($this->getRequest()->getParam('search-term')) {
$session->SearchTerm= $this->getRequest()->getParam('search-term');
$returnValue = $session->SearchTerm;
} else {
if ($session->SearchTerm) {
$returnValue = $session->SearchTerm;
}
}
return $returnValue;
}
And you could use them like this:
echo $this->getLastProductSearched(); // Product Searched
echo $this->getLastSearchTerms(); // Search terms
It will make your code easier to read and debug later on. A few more notes on your code. You could avoid using nested ifs by using ||.
if ($this->getRequest()->getParam('product-searched') || $session->ProductSearched) {
$returnValue = $this->getRequest()->getParam('product-searched') || $session->ProductSearched;
}
will achieve the same thing as :
if ($this->getRequest()->getParam('product-searched')) {
$session->ProductSearched = $this->getRequest()->getParam('product-searched');
$returnArray['productSearched'] = $session->ProductSearched;
} else {
if ($session->ProductSearched) {
$returnArray['productSearched'] = $session->ProductSearched;
}
}
Hope this helps !

Is there a DRY way to reuse a forloop?

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.

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