Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Search - "return"
-
Manager: Write a function to get tomorrow's date.
Kids:
int getTomorrowsDate() {
return getCurrentDate() + 1;
}
Legends:
int getTomorrowsDate() {
sleep(1000*60*60*24);
return getCurrentDate();
}14 -
windows update code
function update(){
print("10%");
print("30%");
print("50%");
print("99%");
_doActualUpdate();
_mineBitcoin();
print("100%");
return;
}15 -
Interviewing a junior dev.
> Make this function return false.
> junior: deleted all code in function replaces it with return false;
Literally no words.........20 -
Logic Gem found at work today.
if (value != null) {
return value;
} else {
return null;
}
😂 😂😂😂😂😂10 -
While reading through the Elasticsearch (Java search engine) source code a while ago I found this gem:
return i == -1? -1: i;
I think someone should stop drinking while coding.
Some other nice lines:
int i = 0;
return j + 1000 * i;
Are these guys high?11 -
public boolean even( int num ) {
if ( num < 0 )
num = -1 * num;
while ( num > 1 )
num = num - 2;
if ( num == 0 )
return true;
else
return false;
}19 -
Work.overtimePay = (hours, normalRate) => {
// return hours * (rate * 2)
return "you guys are brilliant!"
}10 -
"What technologies do you know?"
"I can write pretty URLs that return JSON"
"You mean REST?"
"No, I mean pretty URLs that return JSON"3 -
Seen in code:
public String getX(){
if (x != null){
return x;
}
else return null;
}
... I'm not gonna like looking at the rest of this, am I?11 -
Junior dev complained about my request to remove unnecessary comments because they're too obvious. "They may be obvious to you, but not to others" he said.
The codes and the comments:
// Sort the array
arr.Sort()
// Return the first element of the array
return arr[0]14 -
React-Redux's connect() function inspired me to create the coolest way to add numbers in JS:
<script>
function add(num) {
return function(otherNum) {
return num + otherNum
};
};
console.log( add(2)(3) ); // Outputs 5
</script>
I didn't know you could do that. Just found it out!12 -
C is not that hard:
void (* (* f[ ]) () ) () declares f to be array of unspecified size, of pointers to functions, which return pointers to functions which return void.
By the way, I am uncomfortable with the fact that I am comfortable with this statement.6 -
Samsung's sending a “Note 7 Return Kit” with a Thermally-Insulated Box and Safety Gloves!!
2 mins silence to all those who purchased the note 7 😐5 -
Purchase $900 laptop, it's not powerful enough so I return it and get $1,100 laptop, still not powerful enough, return it and get $1,600 laptop. Realize I have a gaming PC and don't need the laptop this powerful and I return it and repurchase the first laptop I bought with a $100 discount because it's now an opened-box, but I know for a fact that it was the one that I got in the first place and opened.
Thanks Best Buy.3 -
!rant
People : Hey, cool wallpaper. Where did you get it from?
Me :
for (Person p : People){
if(p.equals("dev"))
return "It's from somewhere you'd love to be and never come back!";
else
return "Ahh..internet..wait, guess what? Don't bother!";
}6 -
Looking into a helper class written by someone who was clearly not a master of their craft. The class deals with some string IDs...
public getIDPosition1(String id){
return id.substring(0,1);
}
So far so useless. But it gets better. What is declared immediately below the above method?
public getIDPosition2(String id){
return id.substring(1,2);
}
And below that? You guessed it:
public getIDPosition3(String id){
return id.substring(2,3);
}
This continues to position 10.... -.-7 -
Me in a test:
if(boolean)
return value;
return something_else;
I then lost 2 marks for not having an else statement -.-30 -
Going through code left by a senior developer who quit.. Dated 2015..
public static T IfThenElse<T>(bool isTrue, T ifYes, T ifNo)
{
if(isTrue) { return ifNo ; }
else if(!isTrue) { return ifNo ;}
Debugger.Break();
throw new Exception("") ;
}
.....
There was a unit test for it well
....
............. Wow, just wow9 -
Just saw this in the code I'm reviewing:
function encryptOTP(otp){
var enc = MD5(otp);
return enc;
}14 -
Developers who writes something similar
if (count >= 0) { return true; }
else { return false; }
deserves a special room in hell.16 -
public String getDbPasswd(){
try{
String dbPasswd = SomeInhouseEncryptionLib.getPasswd("/hard/coded/path/to/key");
return dbPasswd;
} catch(Exception e){
LOGGER.log(Level.SEVERE,e)
return "the-actual-password";
}
return null;
}
And this is now in production
FML3 -
I have previously seen this in a production code base. The same code base included nested if statements (20+ conditions)...
If (condition == false) {
return false;
} else if (condition == true) {
return true;
}11 -
condition == true
is for boys,
public static boolean isTrue(boolean condition) {
try {
return new Boolean(condition).equals(Boolean.parseBoolean(new String(Boolean.toString((boolean) Boolean.class.getField(String.valueOf(true != false).toUpperCase()).get(null)).toString().toCharArray())));
} catch(Throwable t) {
return condition;
}
}
is for men.6 -
When I define a function which is supposed to return something (for example int), I always write 'return 0;' after I wrote the signature of it to avoid the red error-marker. It drives me crazy... After I finished coding I replace the 'return 0;' with what I actually wanted to return.5
-
If (index == 3) {
return true;
}
else {
return true;
}
Apparently the number 3 is magical or aomething.7 -
This guy who earns 20% more than me wrote a method to check which string of 2 is lexicographically smaller.
public boolean isSmaller(String s1, String s2) {
String [] temp = new String[2];
temp[0] = s1;
temp[1] = s2;
Collections.sort(temp);
if (temp[0].equalsIgnoreCase(s1)) {
return true;
}
else {
return false;
}
}5 -
Visual Studio : Not all code paths return a value
Me : That method is only with a single line, and it's a return with the value. Don't fucking kidding me.10 -
Refactoring nested ifs.
I'm not a pro but I despise working with nested ifs. It's hard to debug and read.
If you cant chunk the if using method, i think you can use ifs like this:
If(){return}
If() {return}
Not like this:
If() {
If() {
If() {
}
}
}
😠😠😤🙅😢8 -
// Return data
return data;
Found this in our code recently, had to check who pushed it to git. Apparently i'm an excessive commenter 😫2 -
print('I love U world !!')
I'm back !! After being fired from my job (read my prev rants) , after a week they called me and told me that I can return! (If only I promise that I'll control my curiosity and i'll never make the same mistake ever again)
It is just like a dream !!
I'm really glad that I listened to your advice and didn't do anything stupid :)7 -
As someone in charge of reviewing this code, how would you react to this function that contains, what could be, the longest ever readable return statement.19
-
I've created an AI!!!!
Code:
switch msg:
case "Hi": return "Hello";
case "What's the weather": return "Weather is great";
case "Are you an AI?": return "Yes, I'm highly intelligent"8 -
IF (no error ) {
Food is delicious;
Weather is nice;
Friends are kind;
Home is comfortable;
Computer is fast;
Return ( continue life );
Else {
Food is disagreeable to the taste;
Weather is stormy;
Friends are zombie;
Home is hell;
Computer is slow;
Return (stop life);
}
}5 -
Return to office, return of the haikus:
Returned to office.
Time for the daily standup
On Microsoft Teams. 😒1 -
public function recruiters($salary)
{
if($salary == "competitive")
{
return NaN;
} else
{
return "What is the real salary?";
}
}3 -
Me: Return data from Firebase into unity project
Firebase: Returns data as object
*Type casting fails for 6hrs*
Finally find the reason Data return type is int64 and I was saving as int32
Now I sit and question my life while listening to epic music2 -
That moment when you replace
If (blablabla) {
return Yes;
}
else {
return No;
}
with
return blablabla;
And it not passed code review because "We should have readable code"2 -
If you are programming in C++ please always return a type from a function as the function prototype return type.
I had to debug some old code that failed to return a boolean on one of its flow paths. It would work on linux in release and debug, would work on windows in debug, and fail on windows in release.
The failure was NOT straightforward at ALL. It would return exit code 3. Then if I added a debug print to the function it would segfault.
Why the hell would popping something extra off the return/call stack not crash more readily? Wth is the point of debug compile if it won't catch shit like this?8 -
Found this gem today
public findHM(int height, int height2) {
if (height < height2) return height;
return findHM(height - 1, height2);
}4 -
Long time no see devRant! Its been a long time since I have been active in this community but I am proud to say in my current job, for the first time, i am being paid to program! A wonderful feeling1
-
Api-docs: Use the query parameter name_pattern to return results that contain name. Otherwise use name to return an exact match
Api: Returns *name* results when using name and everything when using name_pattern without a wildcard -
Few days ago I wrote function that finds occurrence of value in array:
function findOccurrence(value, array) {
for (var i = 0; i < array.length; i++) {
if (value === array[I]) return true;
}
return false;
}
But there's already [].includes() function in JavaScript.5 -
Last year in my first lesson of informatics:
Me: “What does return do?”
My teacher: “If you start your program, Windows will pause and run your program. If your program is coming to the end and hits the return statement, your program will stop and Windows will run again.”
wtf
(I already knew the right answer but I wanted to ask him this question.)12 -
"/path/to/my/file.swift:143:34: error: cannot convert return expression of type 'String.SubSequence' (aka 'Substring') to return type 'String'"
Ah yes, I love it when Substring isn't String5 -
Your choice. Select one
1.
foo (bar) {
return true;
}
2.
foo (bar)
{
return true;
}
3.
foo (bar) { return true; }
4.
foo (bar)
return true;
5. Collapse
|-------------------|
| foo (bar) ... |
|-------------------|
6.
#define foo boo
#define bar par
#define ( `
#define ) '
#define return go_home
#define true false
#define { ☞
#define } ☜
6-1.
boo `par' ☞
go_home false;
☜
6-2
boo `par'
☞
go_home false;
☜
6-3.
boo `par' ☞ go_home false; ☜
6-4.
boo `par'
go_home false;
6-5.
|--------------------|
| boo (par) ... |
|--------------------|
Select and Comment below.
Or add your own.27 -
My first login function
const login = (email, password) => {
If (email && password) {
return true
} else {
return false
}
}10 -
Function bool NewSpeedTestingStandard()
{
AskUserToLoadAPage();
return UserUsesPhoneWhileLoad()
? "Fail" : "Pass";
}8 -
Tekashi 69 was about to snitch on me for hacking and leaking data from the NSA and then I hit em with the...
return;6 -
function Life(crap):void
{
crap = Lemons;
Return crap;
}
function Solution(liquid)
{
liquid = Tequila;
Return liquid;
}
function whatYaGonnaDo():void
{
Life = null;
Liquid = null;
life (Life);
if (life="Lemons")
{
solution(liquid);
}
}
//sorry i was bored. (not sorry)4 -
I am of the firm belief that a function should always return just one type.
I think it's the most convoluted thing that a function should be allowed to return any kind of type.
I've seen shit like return a string when something is valid and then a boolean if it's not valid.
To me, that kind of flexibility has some funky code smell.
I'm looking at you WordPress 🤨11 -
Today I found this jewel in a PR of a respected dev of my workplace:
if(conditions)
{
return true;
}
else
{
return false;
}3 -
Google search results always return 2.7 version of documentation. Load it, hit the drop down, select 3.6...
-
This customer's dev is going to be the end of me. I had to explain to him why it doesn't make any sense to return a value after throwing an exception.
In a function that was supposed to insert a record amd return its id, in the error handling code:
catch(Exception ex) {
//logs the exception
throw ex;
return - 999; //this code will NEVER be reached, and why the f.... - 999?
}
The customer wants us to develop the project together, but he won't listen and always write whatever he wants. Some might be differences in taste. Like me preferring
if(condition) {
return a;
}
return b;
And him preferring :
Foo result = null;
if(condition) {
result = a;
} else {
result = b;
}
return result;
Ok, that I can accept. But things like the one I'm ranting about... I wont.
I'm starting to wonder what was he doing during his "9 years of coding experience"10 -
Me: I feel like JavaScript has buyer's remorse because all day you return, return, return things.
John: That's how you know it's functioning. -
Wish I knew about this lovely community a few years ago, when a dev in my team asked for help because they couldn't understand why their function was only returning one string... Only you guys would understand my pain when I saw this...
string SomeShitStringMethod()
{
<do stuff>
return string1;
<do stuff>
return string2;
<do stuff>
return string3;
}
>_______<2 -
when code comments be like
# loop over the array
for i in 1...10
# divide by 2
x = i / 2
# return the result
return x4 -
...
$html .= '</li></ul></div>' . $label . '</div>';
return new JsonModel(
'status' => true,
'html' => $html
);1 -
int new(int year) {
return ++year;
}
...
long long int year = 2017;
cout << "Happy " << new(year) << "!";1 -
int someFunc()
{
int result = -1;
// imagine all the fucking ifs in the world...
{
{
{
{
{
{
{
{
{
}
}
}
}
}
}
}
}
}
return result;
}4 -
The reason why I don't trust php:
var_dump(0 == "0deadbeef1");
var_dump(7 == "7deadlysins");
(both return true)3 -
I can't use Javascript object destrucuring in react components because a colleague doesn't like / understand it for some reason.
So instead of:
({ something }) => {
return (
<div>{something}</div>
)
}
If have to use
(props) => {
return (
<div>{props.something}</div>
)
}
Its no big issue, but I hate it.8 -
It's truly incredible, what people can create:
let categoriesText = '';
categories.forEach((item, i) => {
if (i !== 0) {
categoriesText =
categoriesText + `, ${item.categoryName}`;
} else {
categoriesText =
categoriesText + `${item.categoryName}`;
}
});
return categoriesText
How about you STFU!!!
return categories.map((category) => category.categoryName).join(', ');12 -
Here’s how my Friday night is going:
def signin
if should_not_sign_user_in?(stuff)
return redirect_to :nope
end
# signin logic
end
The guard says I shouldn’t sign the user in. It logs the details of why. I read the logs; they’re all correct. It logs the return value, which is false, and the user gets signed in anyway.
Wat.
There’s a return and a redirect there!
This is only happening on the QA server, too, so something fishy is going on.5 -
javascript generated captcha and javascript captcha validation in my university website... over hundred thousand students use this website to check results
function ValidCaptcha(){
var string1 = removeSpaces(document.getElementById("AVCODE").value);
var string2 = removeSpaces(document.getElementById("UVCODE").value);
if (string1 == string2){
return true;
}
else{
alert("invalid captcha");
return false;
}
}
function removeSpaces(string){
return string.split(' ').join('');
}1 -
At first it seemed harsh, but then I learned that he committed code like
if (a == b)
return true;
else
return false;9 -
In what fucking programming language a constructor can return a nullable value???
Swift of course. :|
Fuck apple :-)5 -
bool isTrue(bool val){
If(val == true){
return true;
}
else if(val == false){
return false;
}
else{
cout<<"Wrong value";
}
Function isTrue is the future ! 😂😂😂2 -
After I read clean code I talked to a fellow developer about some concepts. Later I reviewed some code of him and he clearly got the concept (not)
Java
...
If (isTrue(someValue))...
public boolean isTrue(boolean value){
if(value == true)
return true;
else
return false;
}9 -
And then, looking for the source of a bug in the code .... I randomly found this:
public bool IsOperationStarted { get; set; }
public bool IsOperationStartedTrue
{
get { return IsOperationStarted == true; }
}
public bool IsOperationStartedFalse
{
get { return IsOperationStarted == false; }
}4 -
You know why i hate JavaScript?
Instead of writing
return x.y.z;
I wrote
return
x
.y
.z;
Just for making the code look clean
and everything broke...10 -
IsIdentical(object l, object r {
if (l.m_Lorum == r.m_Lorum)
if (l.m_Lorum2 == r.m_Lorum2)
if (l.m_Lorum3 == r.m_Lorum3)
if (l.m_Lorum4 == r.m_Lorum4)
if (l.m_Lorum5 == r.m_Lorum5)
if (l.m_Lorum6 == r.m_Lorum6)
if (l.m_Lorum7 == r.m_Lorum7)
if (l.m_Lorum8 == r.m_Lorum8)
if (l.m_Lorum9 == r.m_Lorum9)
return true;
return false;
}
//FML..
Just do this:
return (l.m_Lorum1 == r.m_Lorum1 &&
l.m_Lorum2 == r.m_Lorum2 &&
l.m_Lorum3 == r.m_Lorum3 &&
l.m_Lorum4 == r.m_Lorum4 &&
l.m_Lorum5 == r.m_Lorum5 &&
l.m_Lorum6 == r.m_Lorum6 &&
l.m_Lorum7 == r.m_Lorum7 &&
l.m_Lorum8 == r.m_Lorum8 &&
l.m_Lorum9 == r.m_Lorum9);13 -
Programming while drunk:
if (not drunk !== yes) { then return dance.png } else {return 'idk"}
I shouldn't rant while crunk let alone program 😂🙄5 -
So...
function watch($i = null)
switch($i) {
case 1:
return 'Game of Thrones';
break;
case 2:
return 'Silicon Valley';
break;
case 3:
return 'Fear The Walking Dead';
break;
}
}
echo watch(rand(1,3));6 -
I feel stupid to ask this here
I am getting this error in flask
view didn't return a valid response error. The function either returned None or ended without a return statement.11 -
Applying Occam's razor and I might be wrong..
Hiring a candidate and job hunt, both are fucking exhaustive process.
We, as a human race, have aimed for Moon and Mars but are unable to solve the problem at hand which can save millions of hours each year reflecting in immediate cost savings.
Here's my (idealistic) solution:
A product to connect job seekers and recruiters eliminating all the shitty complexities.
LinkedIn solved it, but then hired some PMs who started chasing metrics and bloated the fuck out of the product.
Here are some features of the product I am envisioning:
1. Job seeker signs up and builds their entire profile.
2. Ability to add/remove different sections (limited choices like certifications, projects, etc.), no custom shit allowed because each will have their own shit.
3. By default accept GDPR, Gender Identity, US equality laws, Vetran, yada yada..
4. No resume needed. Profile serves as resume. Eliminate the need to build a resume in word or resume builders.
5. Easy updates and no external resume, saves the job seeker time and gives a standard structure to recruiters to scan through eliminating cognitive load.
6. Recruiters can post their jobs and have similar sections (limited categories again).
7. Add GDPR, Vetran, etc. check boxes need basis.
8. No social shit. Recruiters can see profiles of job seekers and job seekers can see jobs. Period.
9. Employee working in Google? Awesome. Will not show Google recruiters thier profile and employee such job posts.
10. No need to apply or hunt heads. System will automatch and recommend because we are fucking in AI generation and how hard it is to match keywords!!
11. Saves job seekers and recruiters a fuck ton of time hunting the best fit.
12. This system gets you the best job that fits your profile.
Yes, there are flaws in this idea.
Yes, not all use cases are covered.
Yes, shit can be improved and this is hypothetical.
But hey! Surely doable with high impact than going on Moon or Mars right now.
Start-up world has lost its way.12 -
class Bug():
def __init__():
self._fix = random.randint(1, 6)
def fix():
if self.is_feature :
return Feature(self)
else:
if random.randint(1, 6) == self._fix:
Bug()
del self
else:
return Bug() -
!rant
Even if I don't like a rant that much - if it's getting a lot of ++ and is close to 175 (maybe like 150) I always give it another one to give it that little nudge. I'm just that kind of a guy.3 -
case "addprem" : {
if (isGroup) return reply('This command can only be used in private chat!')
if (args.length < 2) return reply(`Kirim perintah : ${command} number|total`)
if (!q.includes('|')) return reply(`Incorrect usage, use the | . symbol`)
var numb = q.split('|')[0]
var total = q.split('|')[1]
var number = numb.replace(/[+| |(|)|.|-]/gi, "")
if (isNaN(parseInt(number))) return reply('Thats not your number😥')
reply('Success')
let addprems = [];
var object_buy = {
ID: pushname,
number: number,
session: total
}
fs.writeFile(addprems, JSON.stringify(object_buy, null, 3))
break
}5 -
I just spend 15min debugging my answer to a code challenge just to notice I forgot to return the value...
What a fantastic waste of time.1 -
```
public someMethod(index: string): Promise<void> {
return Promise.resolve(someAsyncFunction().then(() => {
return;
})
.catch((error) => {
this.logger.error(error);
throw error;
});
```
Somebdoy doesn't know their async / await syntax but they wanted aboard the promise-hype train. There is an entire class in that style.1 -
location /dev/null {
if ($request_method = POST ) {
return 200;
}
if ($request_method = GET ) {
return 204;
}
}1 -
Life(naive_person) {
While(lesson not learnt) {
Change characters;
Repeat story;
}
Return dead_person;
} -
while (moreFeatures > 0)
{
doWork ();
reduceFeatureCount ();
clientRequest();
moreFeatures++;
}
return finalPayment;4 -
if err != nil {
if err.Error() == sql.ErrNoRows {
return nil, err
}
return nil, err
}
found me some choice, grade A Go code here.5 -
"Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it."
WHERE. TELL ME WHERE THE FUCK THE PROBLEM IS HAPPENING. OR SHUT THE FUCK UP.3 -
public static Map<Integer, List<Integer>> stuff(arguments) {
HashMap<Integer, List<Integer>> map = new HashMap<>();
method(map, otherVariables);
return map;
}
public static void method(HashMap map, otherVariables) {
map.put(things);
}
So... You know how to return a map from a method. Then why do you create the map outside the method and make it an argument that does not get returned, making it confusing because the map gets created empty, given to a different method, then returned, making it look like you're returning an empty map...
...instead of just creating it inside the called method, returning it and assigning it to a map in the calling method? Even if you think that would create another map (it doesn't), the compiler is intelligent and can optimise that away.9 -
What do people like more?
if(condition){
return true;
} else{
return false;
}
Or just
if(condition){
return true;
}
return false;7 -
In Java, I use dummy variables to set breakpoints and get around the return unreachable compiler/Eclipse check2
-
Function works() {
Try {
HorriblyDyingCode();
Return true;
} catch (Exception e) {
Return false;
}
} -
The masculine urge to skew a scredriver in the lungs of the very funny colleague who place several random return statements inside their function13
-
my own code is confusing me so much that I can't even return what I want to return and been trying for hours
I'm going over stuff like a broken record and seems as though I'm not understanding it at all 🤷🏼♀️3 -
After a few months of working in an actually well coded project, I'm back in the one where I find abominations like this every day:
boolean result=false;
<do stuff>
if(<condition>){
<do stuff>
return true;
}
<do stuff>
return result;
Do they even read their code before submitting? -
I'm confused... where am I supposed to be going again?
if (userInfo.isAdmin) {
return (<Redirect to="/my" />);
}
if (userInfo.isSuperUser) {
return (<Redirect to="/my" />);
}
return (<Redirect to="/my" />);1 -
REPOST (since people focused on an unescaped dot rather than on the problem matter).
Has anyone noticed how bad javascript's regex is?
21st century and it still doesn't return capture groups with separate indexes.
regex.exec and str.match doesn't return them either.1 -
1. Commented code instead of actually cleaning it up.
2. Returning default return variables instead of rewriting obsolete code. (Generally if/else conditions with return). So instead of removing the if/else statements i return default value(null or empty objects). This is when the case of if/else will never arise. -
Performing code review for design quality.
So you return HTTP code 200 for 'ok'. So what do you return when things are not 'ok'?
Obviously something that's not 200. Like 300 (The message with the code was literally "not okay").1 -
The second you write `else { return false; }` you should lose the privilege of calling yourselves a dev, from then on. Period.
Example,
if(condition) {
// ...some code
return true;
} else {
return false;
}14 -
int main() {
char age = 0x14;
char tmp = 1;
while ( age & tmp ) {
age &= ~tmp;
tmp <<= 1;
}
return age |= tmp;
}1 -
Questions that are bothering me:
When a function that returns void returns, is any value from the stack frame copied into the register?
Is the return address in the stack frame even allocated, or is it nullptr?
Could a void function theoretically return a value if you hacked one into the frame?
Does the register even know to expect a value from a void function? If so, where is the logic for this and what is difference between a void and non-void function return at the stack frame & register level?
Any good books on this stuff?2 -
Interviewer: What is typeof typeof []
Interviewee: I think it's Array
Interviewer: Why?
Interviewee: Because first one would return Array, so second one will also return Array
:/5 -
I consider myself not all knowing, but even I understand that if there is a base-class, which requires its derived classes to implement a method to return, for instance, the EndOfLive date for the instance of that class and one chooses to implement that method to calculate and return a date, which isn’t always the right date, and then assume that who-ever calls that method magically knows that the result should be re-calculated and converted using an obscure, undocumented correction-method, located somewhere in a undisclosed utility, outside of that class which the person created not to long ago, that there is something structurally wrong with that implementation of said method and something structurally wrong with that person in general.
If a method should return X, then don’t return Y and expect that everybody magically knows that the result needs to be converted to create X. But, FFS, return X! -
That's gonna be a quick rant about Golang.
Anyone else here frustrated by the fact that you can inline assignment in the if statement, but can't inline the if-else itself?
You can do:
if thing := hey.getThatThing(); thing == theThing {
return 'this'
} else {
return 'that'
}
But can't do:
return 'this' if hey.getTheThing() == theThing else 'that'
Or is it just me using too much Python everyday and connecting that with Go in free time?5 -
Not loving the implicit return statement within Scala. I like to avoid else statements to keep the level of nesting low and do early return yet Scala doesn't allow that.
(I am aware that I should flatMap that shit though in some cases I just want a simple if not foo then throw exception line. And continue with the next block until I return something.)
So you either have to create if-else-nesting beats or use pattern matching. The latter seems overly complicated for this use case (though it has its moments).
I know that I can make the return explicit yet the linter warns against that. It feels so verbose and I currently do not see any benefits and would argue that the code becomes both harder to read and maintain.3 -
Do you guys return 200 when a search function in your API returns a not found and you attach a response in the object saying "success: false", or do you return 404? I'm confused. Thanks.
https://softwareengineering.stackexchange.com/...3 -
Advice to new devs: always check function return values. Crash as close to the reason as possible. Make your functions return errors whenever appropriate and check these as well, crashing gracefully.1
-
public String findHappiness()
{
if(EverythingOk)
return “Drink Beer”;
else if(EverythingNotOk)
return “Drink Beer”;
else
return “Drink Beer”;
}1 -
Got a job related travel to a good city on Thursday. I took the Friday as holiday, I will enjoy the city. Normally, I could return on Thursday back with colleagues. I plan to ask company to arrange my return ticket on Saturday or Sunday. Cool or not cool?7
-
#2020 resolutions:
1. Learn Nodejs/E.
2. Learn Golang.
3. Forget to return back home from college.3 -
WTF!! Function that returns multiple outputs!! Why not make a datetime object and return the whole fucking object!!1
-
This will never clash:
static createGuid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + s4() + s4(); // Example => 'e014026082e6237b'
} -
javascript/typescript people
getNumberFromCalculation(number a, number b)
better to throw new RangeError when you get a bad number combo that doesn't make sense
or return a RangeError ? (if that's a thing) and then have to check if you return the calculated return number value or an Error every time14 -
function stressBall(previousPost){
post = makePostAboutWinningStressBall(previousPost);
return stressBall (post);
}2 -
if (in_array($needle, $haystack)){
return true;
}else{
return false;
}
# yeah, I did it.... wtf brain!!1 -
offending devs is easy -
String strName = " John";
String strGreet = Greet(strName.ToString());
return strGreet;11 -
1. getSomeData(params, ((err, data) => {
2. if(!err && data) {
3. try {
4. data = JSON.parse(data);
5. } catch(e) {
6. return null;
7. }
8. return data.someParam;
9. }
10.}
Nothing like bad practice in above code but I always feel that the line 4 should be replaced by below.
4. var result = JSON.parse(data);
and then use result variable to get data one is looking for, like below
8. return result ? result.someParam : null;
Your thoughts?3 -
var self = this;
if (args != null) args = Array.from(args);
return function(){
return self.apply(bind, args || arguments);
};
no wonder nobody likes js. this is not js. this is shit.5 -
Haven’t been on here in ages. People still moaning. Found a rant or two with some severe profanity.
A community of somewhat likeminded individuals who at some point have gone through similar experiences.
I’m back it seems.
(Not today, old friend)1 -
The most normal C++ program be like:
// prints "Hello, World!"
namespace{decltype(+*"")(*main)()=[]()->decltype(main()){return{};};}
decltype(main())(main(decltype(main())={},decltype(&*"")_[]={})){
extern decltype(&"") puts;
reinterpret_cast<decltype(::main())(*)(decltype(&*""))>(&puts)("Hello, World!");
return(decltype(::main()){});
}8 -
So I've spent some time learning a little about the halting problem, and it's quite fascinating. I tried to simplify it down to these few functions. What do you guys think? Obviously, psuedo-code, so don't get too caught up on the syntax 😆
The Halting Problem:
public String doesItHalt(Callable function){
...
if (...){
return "Yes"
} else {
return "No"
}
}
public int someFunctionFooThatHalts(){
...
}
public int someFunctionFooThatDoesNotHalt(){
...
}
public String inverseAnswer(value){
if (value == "Yes"){
return "No"
}
if (value == "No"){
return "Yes"
}
}
public String inverseHalts(Callable function){
return inverseAnswer(doesItHalt(function))
}
————————————————————————————
$ doesItHalt(someFunctionFooThatHalts)
Yes
$ doesItHalt(someFunctionFooThatDoesNotHalt)
No
$ inverseHalts(someFunctionFooThatHalts)
No
$ inverseHalts(someFunctionFooThatDoesNotHalt)
Yes
$ doesItHalt(inverseHalts(doesItHalt))
???2 -
Interview Question:
Are there other options to make this go any shorter?
if (john == doe == max == paul == stella == false)
return "Not Okay";
return "Okay";
I did...
return (!john && !doe && !max && !paul && !stella) ? "Not Okay" : "Okay";
That was the shortest i could come up with... Maybe there is something shorter, dunno.6 -
Just askin:
If you have a method which returns a value from an array. What do you prefer in a case when the item is not found?
A)Throw an exception
B)return null
C)return a special value like a null object or some primitive type edge value like Integer.MIN_VALUE14 -
public static bool IsYouCrazy()
{
// I can't stand random
// carriage returns
bool hasRandomBlankLines = true;
Return hasRandomBlankLines;
} -
Why the fuck does B&R's find in string function return 0 when the search string was not found? The return type is not even unsigned?!5
-
Is it normal that my lead developer insists that if(x){return A} else {return B} must be changed to if (x){return A} return B, and a variable must be renamed from requestFn to requestFunc because the former is confusing?12
-
I pass the day writing a script to encapsulate the migration of the old csproj to the new format. But, when the open source app returns an error of migrating the script continue. I check the return code and when it's an error, it's return 0.
After many tries, I return to my house and start looking at the open source code for understand what's happening and try to correct it.
OMFG, I cannot change the code to return an `int` instead of void. The method is in the public area of the code.
I very happy that this app, it's open source, so I can do my own version for my need.1 -
syncStatus = "PENDING";
if(!carrierId || !responseData || syncStatus) return;
THIS line f*ked me up for about an hour.6 -
//In the code block below. What are both self methods refering to? do both self methods refer to the Suit enum because it is inside the enum block? I am trying to better understand self. Please see link for expanded question.
enum Suit {
case spades, hearts, diamonds, clubs
var rank: Int {
switch self {
case .spades: return 4
case .hearts: return 3
case .diamonds: return 2
case .clubs: return 1
}
}
func beats(_ otherSuit: Suit) -> Bool {
return self.rank > otherSuit.rank
}
}
https://code.sololearn.com/c9KIG0ab... -
So is the difference between inheritance and composition is that of a fridge and iceman?
class Man {
fun greet(){return "hi"}
}
class IceMan extends Man{
override fun greet(){return "hi i am iceman"}
fun getIce(){return "ice"*Random.nextInt()}
}
class Fridge{
private Man manAi;
private String s = "ice";
fun greet(){return manAi.greet()}
fun getIce(){return s*Random.nextInt()}
}
}
=========
Basically , in first case, a class is getting features by inheriting from parent while in another case, a class is getting features by internally having objects of other classes that could provide those features?6 -
I feel like I didn't do this right and I'm a tad confused as to what they mean when they say that the function should look like this when you call it:
let line = openingLine(verb: "row", noun: "boat")
Is my solution correct?10 -
function pmAsksForMore(work) {
return iDoIt(work);
}
function iDoIt(work) {
return pmAsksForMore(work);
} -
Who writes something like this!?!?
if (result == "True")
{
return "True";
}
else
{
return result;
}1 -
Has anyone ever had to choose either to write the remaining letters of a word in the NEXT line or just jot down below that same line?4
-
typedef bool Bool;
Class Description
{
public:
inline Bool IsTypeA() const { return IsType(TYPE_A); }
inline Bool IsTypeB() const { return IsType(TYPE_B); }
inline Bool IsTypeC() const { return IsType(TYPE_C); }
Bool IsType(DescriptionType T) const { return (T == Type()); }
DescriptionType Type() const { return m_Type; }
private:
DescriptionType m_Type;
}
I can't make this shit up3 -
private boolean didWakeUpForNothing() {
if (mathTutoring.isClosed()) {
return true;
} else {
studyForExams();
}
}
private void studyForExams() {
feelEmptyInside = cryInShower = true;
}1 -
```
Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both.
```
(ノ≧∇≦)ノ ミ ┸┸)`ν゚)・;’. -
My rant.... CAM by NZXT. Makes me want to return this CPU cooler. This software is fucking irritating.
-
Axios docs recommend me to use catch() callback for server error
- Not working
Then in git issue someone told to provide error callback as second parameter in then()
- Not working
And I just sit here wondering why it return undefined result when the server return 400 :s6 -
Am I a genius?
```
const co = (obj) { return obj[true] }
src={co({ [isBreakfast]: img1, [!isBreakfast]: img2 })}
```2 -
I can't count likes form my database for an specific post. I made a function that will count all the like by "post.id". It shows the like on the web page when I clicked on like button and it disappears when I refresh the browser. but likes are still remaining in the database but it won't appear on the webpage.
Here are the flask code:
def like_count(post_id):
if request.form.get('like') != None:
if (Like.query.filter_by(post_id=post_id).all())==[]:
return 0
else:
return Like.query.filter_by(post_id=post_id).count()
else:
return 0
def dislike_count(post_id):
if request.form.get('dislike') != None:
if (Dislike.query.filter_by(post_id=post_id).all())==[]:
return 0
else:
return Dislike.query.filter_by(post_id=post_id).count()
else:
return 0
Here are the html code:
<!--dislike-->
<form method="POST" action="">
<input name="dislike" value="1" class="input-style" >
<input value="{{post.id}}" name="post_id" class="input-style">
<button class="fas fa-thumbs-down" class="like-button" >
<div class="like-count" >
{{dislike_count(post.id)}}
</div>
</button>
</form>
<!--like-->
<form method="POST" action="" >
<input name="like" value="1" class="input-style" >
<input name="post_id" value="{{post.id}}" class="input-style" >
<button class="fas fa-thumbs-up" class="like-button" >
<div class="like-count" >
{{like_count(post.id)}}
</div>
</button>
</form>8 -
If (method-exists (devrant->rantAboutBreakingUpWithGirlfriend ()){
Echo "This seriously sucks %#$@£¥";
}else {
Return false;
} -
Class Workday extends NormalDay{
PriorityList taskList = getDefaultTasks() ;
Funitems finitems=getEnjoymentTasks();
Workday addTasks(Task... tasks){
taskList. AddAll(tasks);
return this ;
}
PriorityList getTasks() {
return taskList ;
}
Void act() {
funItem.lookupAppropriateItem().execute();
taskList.popTop(). Execute();
}
}
//class ends
//inside main...
....
...
Office today = new Workday();
today.addTasks(yesterday. GetTasks()) ;
Today. act() ;
//......... -
{
regular: function () { return this }, // ok
arrow: () => { return this } // you mean undefined?
}3 -
pow function accept var ?for example x2=2 ;
int count =2;
pow(count, x);
should return 4 but return other value9 -
Ahh, the beauty of C#/Asp.Net:
MasterPages.MasterPage MasterPage
{
get { return Master as MasterPages.MasterPage;
}
}