Coffeescript promises on multiple lines syntax - coffeescript

I have this code in Coffeescript:
#update().success((company)=>
).error((company)=>
).finally((company)=>
)
I wonder if this can be changed to remove some of the brackets. Something like this:
#update()
.success (company)=>
.error (company)=>
.finally (company)=>
But I always get an SyntaxError: [stdin]:18:9: unexpected .. Any idea what I am doing wrong?
Thanks.

Just because you can use anonymous functions doesn't mean you have to. Busting the functions out and giving them names often makes your code clearer, easier to read, and less whitespace-fragile.
For example:
frobnicate_the_things = => # some pile of logic goes here
complain_about_the_problems = => # and another pile here
clean_up_the_mess = => # and yet another here
#update()
.success frobnicate_the_things
.error complain_about_the_problems
.finally clean_up_the_mess
Of course I don't know what your callbacks are actually doing so I had to make up some silly names but that's not the point. The point is that you have nice self-documenting code without a bunch of fiddling around with syntax and whitespace.

If you are willing to put up with semicolons:
#update()
.success (company)=>;
.error (company)=>;
.finally (company)=>;

As long as you fill in a function body, that syntax works just fine:
#update()
.success (company) => true
.error (company) => true
.finally (company) => true
Otherwise you'd have to clearly delineate the callback functions:
#update()
.success ((company) =>)
.error ((company) =>)
.finally ((company) =>)
But then again, you wouldn't be writing an empty callback in the first place.

You're almost there, you just forgot to add return statement:
#update()
.success (company)=>
return
.error (company)=>
return
.finally (company)=>
return

Related

How to stop the execution or throw an error in scala play framework

I'm developing a scala application with play framework, but i got something strange.
i can't stop the execution nor throwing an error in order to send a response for the client, it always continue the code and it always returning okay, however i made a dummy function that it should return a bad request but unfortunately it is returning OK here is what i wrote. any help will be appreciated
def foo(locale: String, orderId: Int) = Action { implicit request => {
val x=4+7;
if(x==11){
BadRequest(JsonHelper.convertToJson("Bad bad it is really bad "))
}
OK(JsonHelper.convertToJson("Well Done"))
}
}
the above code returning OK Well done.
To make your code return a BadRequest, add an else:
def foo(locale: String, orderId: Int) = Action { implicit request => {
val x = 4 + 7;
if (x == 11)
BadRequest(JsonHelper.convertToJson("Bad bad it is really bad "))
else // <---
OK(JsonHelper.convertToJson("Well Done"))
}}
Your problem is your if without curly braces.
refered to this link :https://docs.scala-lang.org/style/control-structures.html#curly-braces
if - Omit braces if you have an else clause. Otherwise, surround the
contents with curly braces even if the contents are only a single
line.
so you can just suuround the BadRequest with curly braces or add an else statement between your Bad and OK instruction. Be careful, don't forget the indentation !
edit 20/12/2017 >> un scala the last instruction is implicitly returned. Your last instruction is OK, so it returns OK.
Add explicit return statement in your if block or add an else statement.

How to indiciate a failure for a function with a void result

I have a function in scala which has no return-value (so unit). This function can sometimes fail (if the user provided parameters are not valid). If I were on java, I would simply throw an exception. But on scala (although the same thing is possible), it is suggested to not use exceptions.
I perfectly know how to use Option or Try, but they all only make sense if you have something valid to return.
For example, think of a (imaginary) addPrintJob(printJob: printJob): Unit command which adds a print job to a printer. The job definition could now be invalid and the user should be notified of this.
I see the following two alternatives:
Use exceptions anyway
Return something from the method (like a "print job identifier") and then return a Option/Either/Try of that type. But this means adding a return value just for the sake of error handling.
What are the best practices here?
You are too deep into FP :-)
You want to know whether the method is successful or not - return a Boolean!
According to this Throwing exceptions in Scala, what is the "official rule" Throwing exceptions in scala is not advised as because it breaks the control flow. In my opinion you should throw an exception in scala only when something significant has gone wrong and normal flow should not be continued.
For all other cases it generally better to return the status/result of the operation that was performed. scala Option and Either serve this purpose. imho A function which does not return any value is a bad practice.
For the given example of the addPrintJob I would return an job identifier (as suggested by #marstran in comments), if this is not possible the status of addPrintJob.
The problem is that usually when you have to model things for a specific method it is not about having success or failure ( true or false ) or ( 0 or 1 - Unit exit codes wise ) or ( 0 or 1 - true or false interpolation wise ) , but about returning status info and a msg , thus the most simplest technique I use ( whenever code review naysayers/dickheads/besserwissers are not around ) is that
val msg = "unknown error has occurred during ..."
val ret = 1 // defined in the beginning of the method, means "unknown error"
.... // action
ret = 0 // when you finally succeeded to implement FULLY what THIS method was supposed to to
msg = "" // you could say something like ok , but usually end-users are not interested in your ok msgs , they want the stuff to work ...
at the end always return a tuple
return ( ret , msg )
or if you have a data as well ( lets say a spark data frame )
return ( ret , msg , Some(df))
Using return is more obvious, although not required ( for the purists ) ...
Now because ret is just a stupid int, you could quickly turn more complex status codes into more complex Enums , objects or whatnot , but the point is that you should not introduce more complexity than it is needed into your code in the beginning , let it grow organically ...
and of course the caller would call like
( ret , msg , mayBeDf ) = myFancyFunc(someparam, etc)
Thus exceptions would mean truly error situations and you will avoid messy try catch jungles ...
I know this answer WILL GET down-voted , because well there are too much guys from universities with however bright resumes writing whatever brilliant algos and stuff ending-up into the spagetti code we all are sick of and not something as simple as possible but not simpler and of course something that WORKS.
BUT, if you need only ok/nok control flow and chaining, here is bit more elaborated ok,nok example, which does really throw exception, which of course you would have to trap on an upper level , which works for spark:
/**
* a not so fancy way of failing asap, on first failing link in the control chain
* #return true if valid, false if not
*/
def isValid(): Boolean = {
val lst = List(
isValidForEmptyDF() _,
isValidForFoo() _,
isValidForBar() _
)
!lst.exists(!_()) // and fail asap ...
}
def isValidForEmptyDF()(): Boolean = {
val specsAreMatched: Boolean = true
try {
if (df.rdd.isEmpty) {
msg = "the file: " + uri + " is empty"
!specsAreMatched
} else {
specsAreMatched
}
} catch {
case jle: java.lang.UnsupportedOperationException => {
msg = msg + jle.getMessage
return false
}
case e: Exception => {
msg = msg + e.getMessage()
return false
}
}
}
Disclaimer: my colleague helped me with the fancy functions syntax ...

Go: C like macros for writing test code

When writing test code, I do a lot of this
if (!cond) {
t.Fatal("error message")
}
It's a bit tedious. So I'd like to achieve the following
CHECK(cond, "error message")
So I attempted this
func CHECK(t *testing.T, cond bool, fmt string, a ...interface{}) {
if !cond {
t.Fatal(fmt, a)
}
}
If it were a C macro it would've worked perfectly. But in Go, the line number where the failure is is wrong.
Is there a fix for this?
Sadly you can't do that.
A workaround would be to get the line / function yourself, something like the trace function from https://stackoverflow.com/a/25954534/145587.
You could possibly make use of runtime.Callers()&plus;runtime.Caller(): the first one gives you the call stack while the second allows to extract the debug info about any arbitrary stack frame (obtained from that list).
Your CHECK() function is always one function call down the place the check should have happened at if it was a macro, so you can inspect the stack frame just above.
Update: the only functon which is really needed is runtime.Caller(). Here's your case, simplified:
package main
import (
"runtime"
"testing"
)
func CHECK(t *testing.T, cond bool) {
if !cond {
_, fname, lineno, ok := runtime.Caller(1)
if !ok {
fname, lineno = "<UNKNOWN>", -1
}
t.Fatalf("FAIL: %s:%d", fname, lineno)
}
}
func TestFoo(t *testing.T) {
CHECK(t, 12 == 13)
}
When saved as check_test.go and run via go test, it produces:
$ go test
--- FAIL: TestFoo (0.00 seconds)
check_test.go:14: FAIL: /home/kostix/devel/go/src/check/check_test.go:19
FAIL
exit status 1
FAIL check 0.001s
where line 19 is the line a call to CHECK() is located inside TestFoo().
While the above answer to use CHECK() function will work, I think that the actual answer is code readibility. Much of Go has been designed as a compromise to increase readibility among the community as a whole. See gofmt for example. Most people will agree that it's format is not best for every case. But having a convention agreed to by all is a huge plus for Go. The same answer is to your question. Go is for writing code for your peers, not for yourself. So don't think "I prefer this." Think "what will people reading my code understand."
Your original code should be like this, without parenthesis.
if !cond {
t.Fatal("error message")
}
This is idiomatic and every Go coder will recognize it instantly. That is the point.

Lazy filter for one element

I'm refactoring some scala code to teach my coworkers about for-comprehensions, and I've got a line like:
for {
// ...
result <- components.collectFirst({ case section if section.startsWith(DESIRED_SUBSTRING) => section.substring(section.indexOf(DELIM) + 1).trim() == "true" })
} yield result
That's a bit long.
At first, I wished I could just skip the result <- ... followed by the immediate yield, as I can in Haskell, but then I noticed the processing going on inside collectFirst.
So I thought it'd be much easier to read as I should better do this as
for {
// ...
section <- components.filter(_.startsWith(DESIRED_SUBSTRING)).headOption
} yield section.substring(section.indexOf(DELIM) + 1).trim() == "true"
Which works, but it is less efficient, since filter has to process all the elements. I'd like to be able to use a lazy filter:
components.withFilter(_.startsWith(DESIRED_SUBSTRING)).headOption
But FilterMonadic doesn't seem to support headOption, and I can't figure out a way to derive it from the operations it does support. I'm sure there's a way with flatMap and some bf, but I'm too unfamiliar with the scala ecosystem at the moment.
If I want to stick with standard library tricks, am I stuck with
for {
// ...
section <- components.collectFirst({ case section if section.startsWith(DESIRED_SUBSTRING) => section })
} yield section.substring(section.indexOf(DELIM) + 1).trim() == "true"
Or is there something better I can use?
If you use components.find(_.startsWith(DESIRED_SUBSTRING)) that will give you an Option with the first element that meets the condition. Then, you can just map over it with any subsequent processing you need.

How can I use goto in a switch statement in Objective-C?

In my code I need to be able to jump (goto) a different case within the same switch statement. Is there a way to do this?
My code is something like this: (There is a lot of code I just left it all out)
switch (viewNumber) {
case 500:
// [...]
break;
case 501:
// [...]
break;
.
.
.
.
.
case 510:
// [...]
break;
default:
break;
}
Thank you for your time!
-Jeff
It's generally very bad practice to unconditionally jump like you're asking.
I think a more readable/maintainable solution would be to place the shared code in a method and have multiple cases call the method.
If you really want to, you can use goto to do something like:
switch(viewNumber) {
case 500:
// [...]
goto jumpLabel;
case 501:
// [...]
break;
case 502:
// [...]
jumpLabel:
// Code that 500 also will execute
break;
default:break;
}
Note: I only provided the code example above to answer your question. I now feel so dirty I might have to buy some Bad Code Offsets.
Instead of using goto, refactor your code so that the two (or more) cases that use common code instead call it in a common method.
Something like:
switch (value) {
case (firstValue):
// ...
break;
case (secondValue):
[self doSharedCodeForSecondAndThirdValues];
break;
case (thirdValue):
[self doSharedCodeForSecondAndThirdValues];
break;
default:
break;
}
// ...
- (void) doSharedCodeForSecondAndThirdValues {
// do stuff here that is common to second and third value cases
}
It wouldn't be the end of the world to use goto, though it is bad practice.
The practical reason for avoiding use of goto is that you have to search through your swtich-case tree to find that goto label.
If your switch logic changes, you'll have a messy situation on your hands.
If you pull out common code to its own method, the code is easier to read, debug and extend.
You should probably try rewrite your code, like a recursive call or just factor out common stuff and call a separate function. But as a fix and quick answer to your question you could put a label before your switch and goto it, like so
switchLabel:
switch(viewNumber) {
case 500: {
viewNumber = 501;
goto switchLabel;
}
}
Not sure of the Objective-C syntax here, but you could also try a variation thereof
int lastView = 0;
while (lastView != viewNumber)
switch(lastView = viewNumber) {
case 500: {
viewNumber = 501;
break;
}
}
which will keep on looping until the viewNumber doesn't change any more. This is still pretty much just a pretty-looking goto though.
And since we're doing gotos you could just goto into another case, as pointed out already. You could also do fancy stuff similar to Duff's device, by putting cases inside of other blocks. But that's just mad.. :)
[I'm making this answer community wiki because this doesn't actually answer the question per se]
As others have said, this is very bad style, and makes for unreadable code...
Alternatives:
Factor the common code into a separate function, and call that in 2 places.
Use fallthroughs, leave off the the break on a case and it falls through to the next one (remember, cases don't have to be in numerical order!)
if you only want part of a case to be done in the other case, protect it with an if:
as in
case 500:
.
.
.
case 501:
if(viewNumber == 501) {
.
.
.
}
.
.
.
break;