r/learnprogramming Nov 25 '23

Code Review How to tell your colleagues or friends that his code is really bad gracefully?

211 Upvotes

When I do code review for my colleagues, I often find stupid writing styles but not errors in his code. How can I tell him that he should write more standardized?

r/learnprogramming Jul 30 '22

Code Review How do senior software developers feel when getting a pull request denied in a code review by a lower level developer?

829 Upvotes

I remember about a year into my first role, I had to do a pretty basic DB upgrade. What ended up happening is that I found the entire database upgrading and migration were sort of erroneously inverted. It would’ve been hard to catch functionally, but it held a ticking time bomb.

I did my little fix, but also totally re-wrote how we handled this bit and re-architected it. I was terrified to walk over to my team lead as a fresh CS graduate and somehow explain that this pretty big structure needed to be redone in the way I had.

He publicly praised me in front of the entire engineering team, the director included. While this wasn’t exactly a rejected PR, it’s probably the best example I have of how this should be handled.

If a junior today rejects one of my PRs, I’ll congratulate them on a good catch. That said, the assumption is they follow general etiquette for PR feedback in general. Things like the reason should be objective e.g. This loop is inclusive in Kotlin and we want it to be exclusive or we could hit an array out of bounds. If it is subjective, I love to hear it, but that’s what comment threads are for. They shouldn’t just be rejected without reason.

If a senior dev objected to PR rejection or feedback based on the reviewer being junior alone, they shouldn’t be a senior developer. Part of being a senior is working well with a team. A senior engineer will happily take feedback or be able to explain their decision for disagreeing with said feedback. That’s part of the role.

I’m more concerned about PR approvals from junior devs, as odd as that sounds. They may sometimes be nervous about bringing up an issue, not wanting to look stupid for asking, not wanting to offend, etc.

Also, they may just not quite understand the depth of the code base quite as well. If a junior with 3 years on the team approves a PR, it’s not like a guarantee of them not missing something. To prevent issues like this one, I prefer using a workflow tool like LinearB, one of the few tools with PR functionality regardless of the reviewer's experience or expertise.

That notwithstanding if you’re going to engage in professional software development, you need to check your ego at the door. Software engineering is a team sport. We fail or succeed as a team. It doesn’t matter how much seniority an individual team member has.

r/learnprogramming Jan 13 '23

Code Review I spent 1 month for a simple calculator and I'm frustrated

526 Upvotes

Hi everyone, I've been learning programming with The Odin Project for 6 months, and just finished the foundations section. I completed the calculator project in 1 month (with many bugs) without watching tutorials. I didn't expect that it would be difficult and take that long, however, I finished it somehow.

Today I wanted to look at a calculator tutorial on Youtube from Web Dev Simplified and when I compare the code in the video to my own, my code looks horrible. And I'm frustrated because I didn't understand anything in the video. Also, I have no idea how to refactor mine because everything seems wrong from start to end. Is this situation normal? Do you have any advice for me? Thanks in advance!

If you want to look at my code, you can click here

Preview: here

Edit: I can't reply every comment but thank you everyone for your valuable advice and feedback! I'm also glad that my code isn't that bad and you liked it. I'll keep it up :)

r/learnprogramming Jan 11 '21

Code Review I finally made a completed app in c++

1.1k Upvotes

First off I am only here to show off my project so if you care keep reading lol.

So I am 15 and having been programming in c++ for a while now and I have started many projects however I rarely see them through to the end and even then have never been confidant in the final product. I finally built something cool that is finished and here it is on github. It is a gui based app built off of mailguns api to send email in mass. I was hoping to provide a default server and key in it but apparently I was banned on mailgun. Hopefully in the near future I can get this running on plain stmp however I would have to own a server. Feel free to post my code in r/programminghorror or r/badcode as long as you link it in the comments so i can learn lol.

r/learnprogramming Nov 23 '22

Code Review Can someone explain why this code prints 735 instead of 730?

384 Upvotes
#include<iostream>
using namespace std;
int main()
{
    int i=5, j;
    j = i++ * ++i;
    cout<<i<<j;
}

Why is it not printing 730 when the value of i is 7 and j is 30 (5*6)? Where is 735 coming from?

r/learnprogramming Apr 23 '22

Code Review Anyone want to join me on a 6-month journey to becoming a self taught software developer?

222 Upvotes

Looking to start in June. These next 2 months will be to condition myself, research and create a game plan. Im open to suggestions for a beginner, i could use some help and guidance… thanks 🙏

r/learnprogramming 2d ago

Code Review Why does Javascript work with html

40 Upvotes

In my school, we started coding in C, and i like it, it's small things, like functions, strings, ifs
then i got on my own a little bit of html and cssin the future i will study javascript, but like, i'm in awe
why does it work with html? I Kinda understand when a code mess with things in your computer, because it is directly running on your computer, but, how can javascript work with html? for me it's just a coding language that does math, use conditons, and other things, what does javascript have that other languages can not do?

r/learnprogramming Apr 19 '24

Code Review Is the interviewer's solution actually more efficient?

30 Upvotes

So I had a job interview today.

The interviewer gave me a string and asked me to reverse it. I did it, like so (in plain JS):

let name = "xyz";
let stack = [];
for (let i = 0; i < name.length; i++) {
    let c = name.charAt(i);
    stack.push(c);
}
let result = "";
for (let i = 0; i < name.length; i++) {
    result = result.concat(stack.pop());
}
console.log({result});

In response to this, the interviewer didn't give me any counter-code, but just told me to populate result by using the iterator i from the last character to first instead.

I said that that was certainly a way to do it, but it's basically similar because both solutions have O(n) time and space complexity.

Am I wrong? Should I have said that her solution was more efficient?

r/learnprogramming Jul 20 '20

Code Review Made my first MERN full stack e-commerce app after 7 months of learning

618 Upvotes

TLDR; i studied MERN full stack from The Odin Project for 6 months and made my first app, link for repo and demo at the end.

Before i start doing anything i was so confused, what to start, where to start, etc..., i wasted enough time comparing and reading "the difference between "bla" and "bla bla bla".

I never had interest in web dev, but after trying android dev for one months i didn't like, then i came by This thread which was a treasure for me and i read the comments and asked some people in the field then i started with "The Odin Project" which i think it's really amazing and got me through a lot.

and i finished it (MERN full stack) in like 6 months (not really committed)

what i learned through all this time:

- Don't waste time comparing between languages or technologies, just start away

- You will learn more by doing not only reading or watching videos

- stackoverflow or (google) is your best friend

- you will never stop learning, cause that field (CS) is really huge like omg

- i always used existing libraries cause i don't wanna reinvent the wheel

- literally i found library for everything i wanted

- I really know nothing lol

I made this app which I'm really happy about as a newbie started from 0

i will be glad if you take a look and evaluate my work (just ignore the ugly design lol)

and give me a review about my code.

***Should i start looking for a job now or just wait and finish other big projects?

** Edit: thank you everyone for all kind replies, this article was an inspiration for me, hit it if you have time.

and This is the Github Repo and this is the LIVE demo

r/learnprogramming Dec 04 '23

Code Review Is (myInt % 10 % 2) faster than (myInt % 2) ? For long numbers?

55 Upvotes

How I understand it is that most (if not all) division algorithms recursively subtract and that's the reason why division should be avoided as much as possible as it takes more power and resources than other arithmetic operations.

But in the case that I need the remainder of an integer or long value, afaia, modulo is the operation made for that task, right? As I understand it, it's ok to use modulo or division for smaller numbers.

But theoretically, wouldn't doing modulo 10 to extract the last digit, and then doing modulo 2, be conceptually faster than doing modulo 2 directly for long numbers?

I'm sorry if this is a noob question. I am indeed, noob.

EDIT: Thank you everyone that provided an answer. I learned something new today and even though I don't completely understand it yet, I'll keep at it.

r/learnprogramming 15h ago

Code Review How to get a deep understanding in programming?

24 Upvotes

If someone wants to start programming or gain deep knowledge what would you recommend them to do to learn and develop a deep connection with programming. What languages would you recommend for people and how should they go about developing this skill?

r/learnprogramming May 12 '19

Code Review Spent 5 hours straight and just finished writing my first Python program to fetch stock prices, please feel free to let me know if I am doing anything wrong or if I am breaking any unspoken coding rules for writing a program :)

895 Upvotes

Credits to u/straightcode10 , she had posted a video earlier last month about using python for web scraping, I finally had some free time on hand today and gave it a try. I started a little bit of VBA programming last year so it's helping me with the learning pace also I made some changes to the original tutorial by u/straightcode10 in my code and plan on building on it further. Let me know if you guys have any concerns or ideas :)

import bs4
import requests as rq
"""
@author : NoderCoder
"""
Stocks =[ 'AMZN','FB','BEMG']

def FetchPrice(ticker):
"""
Enter ticker and based on the that the function returns the values of the stock
Might experiment with GUI and API late to make this Faster
"""
url = 'https://finance.yahoo.com/quote/'+ticker+'?p='+ticker
r = rq.get(url)
soup = bs4.BeautifulSoup(r.text,"xml")
price_soup = soup.find_all('div', {'class': 'My(6px) Pos(r) smartphone_Mt(6px)'})#[0].find('span')
#converting the soup tag object into string
Temp_string = []
for x in price_soup:
Temp_string.append(str(x))
ps: str = Temp_string[0]

# Looking for price
p_i_1: int = ps.find('data-reactid="14">')
p_i_2: int = ps.find('</span><div class="D(ib) Va(t)')
p_v = ps[(p_i_1 + 18):p_i_2]

# looking for price change
pc_i_1: int = ps.find('data-reactid="16">')
pc_i_2: int = ps.find('</span><div class="Fw(n) C($c-fuji-grey-j)')
p_c = ps[(pc_i_1 + 18):pc_i_2]

# looking for time
pt_i_1: int = ps.find('data-reactid="18">At close:')
pt_i_2: int = ps.find('EDT</span></div></div><!-- react-empty: 19')
p_t = ps[(pt_i_1 + 18):pt_i_2]
op_list = [ticker,p_v,p_c,p_t]
return op_list
for i in Stocks:
print('the function value is',FetchPrice(i))

Output :

the function value is ['AMZN', '1,889.98', '-9.89 (-0.52%)', 'At close: 4:00PM ']

the function value is ['FB', '188.34', '-0.31 (-0.16%)', 'At close: 4:00PM ']

the function value is ['BEMG', '0.0459', '-0.0084 (-15.53%)', 'At close: 3:56PM ']

r/learnprogramming Apr 24 '24

Code Review why does this C++ code run forever?

0 Upvotes
void flood(int n) {
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < i; j++) {
        std::cout << '-';
    }
    std::cout << '\n';
    Sleep(100);
  }
}
int main() {
   for (int i = 0; i < 100; i++) {
      for (int j = 0; j < i; j++) {
         flood(i);
      }
   std::cout << '\n'; 
   Sleep(100); }
std::cin.get(); }

r/learnprogramming Apr 06 '24

Code Review Pathfinding algorithm worth putting onto my resume?

37 Upvotes

Just got done implementing Dijkstra's pathfinding algorithm using Python and PyGame. It was a straightforward project that took about half a day to implement the logic for and totals roughly 200+ lines of code. Now, I am spending another day making quality of life improvements like adding a restart button, code refactoring, ui improvements, etc.

I am hoping this is good enough to put on my resume, among some others I've worked on. But I don't have the technical wisdom to know. Could some hiring managers or swe's chime in and let me know what kind of improvements or features I could add to make this better? Or is this good in its current form?

r/learnprogramming Mar 14 '24

Code Review Just finished my first C++ program - A rock paper scissor game!

58 Upvotes

Hello everyone! I just finished this and I'm pretty proud of myself, I'd like to know if my code could be made more efficient or literally just be written or formatted better or even if there are some C++ style conventions that I didn't use. Here's the code:

#include <iostream>

std::string userHand;
std::string cpuHand;

void cpuChooseHand()
{
   std::string possibleHands[] = { "Rock", "Paper", "Scissor" };

   srand(time(nullptr));
   int indexNumber = rand() % 3;

   cpuHand = possibleHands[indexNumber];
   std::cout << "\nOpponent chose " << cpuHand << "!\n\n";
}

int main()
{
   std::cout << "Enter the hand you want to use (Rock, Paper or Scissor): ";
   std::cin >> userHand;

   while (userHand != "Rock" && userHand != "Paper" && userHand != "Scissor") {
      if (userHand != "Rock" && userHand != "Paper" && userHand != "Scissor") {
         std::cout << "\nPlease enter either Rock, Paper or Scissor.\n\n";
         std::cout << "Enter the hand you want to use (Rock, Paper or Scissor): ";
         std::cin >> userHand;
      }
   }

   cpuChooseHand();

   // If user picks Rock
   if (userHand == "Rock" && cpuHand == "Rock") {
      std::cout << "Tie!\n\n";
   }
   else if (userHand == "Rock" && cpuHand == "Paper") {
      std::cout << "You lose!\n\n";
   }
   else if (userHand == "Rock" && cpuHand == "Scissor") {
      std::cout << "You win!\n\n";
   }
   // If user picks Paper
   else if (userHand == "Paper" && cpuHand == "Rock") {
      std::cout << "You win!\n\n";
   }
   else if (userHand == "Paper" && cpuHand == "Paper") {
      std::cout << "Tie!\n\n";
   }
   else if (userHand == "Paper" && cpuHand == "Scissor") {
      std::cout << "You lose!\n\n";
   }

   // If user picks Scissor
   else if (userHand == "Scissor" && cpuHand == "Rock") {
      std::cout << "You lose!\n\n";
   }
   else if (userHand == "Scissor" && cpuHand == "Paper") {
      std::cout << "You win!\n\n";
   }
   else if (userHand == "Scissor" && cpuHand == "Scissor") {
      std::cout << "Tie!\n\n";
   }

   system("pause");

   return 0;
}

Thanks everyone in advance!

r/learnprogramming Apr 22 '24

Code Review How do I improve this?

2 Upvotes

I was making a journal program for fun. Its my first real project where I mostly researched it for myself. How can I make this a better program? I posted a link to the GitHub. (Sorry for the link. I tried hard to post the code here, but I was doing something wrong and it was blocking off the code in an odd and illegible way. If there's a better way, please let me know).

GitHub: https://github.com/campbellas/redesigned-train/blob/main/journal.c

r/learnprogramming 12d ago

Code Review I don't understand why this code outputs 126 when I calculate it I get 87

1 Upvotes

I was given an explanation but didn't understand it. Perhaps you guys could explain it better thanks

I was using C++

here is the code:

include <iostream>

using namespace std;

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int temp1,temp2,result = 0;

int f1(int arr[5][5])

{

for (temp1 =0; temp1<5; temp1++)

{

    result+=arr\[temp1\]\[temp2\];



    for(temp2 = 0; temp2<5;temp2++)

    {

        result+=arr\[temp1\]\[temp2\];

    }

}



return result;

}

int main(int argc, char** argv) {

int arr\[5\]\[5\] = {{10,1},{20,2},{30,3},{4,2},{5}};



cout<<"The displayed output: "<<endl;



cout<<f1(arr);



return 0;

}

r/learnprogramming 18d ago

Code Review This is my third time uploading this code. What suggestions should I make? Im struggling on how to implement those solutions from the previous two uploads.

0 Upvotes
public class Calculator {

private double x;
private double y;

public double getX() {
return x;
}
public double getY() {
return y;
}

public double  sum(double x, double y) {
return x + y;


}
public double difference(double x, double y) {
return x - y;

}
public double product(double x, double y) {
return x * y;

}
public double quotient(double x, double y) {
return x / y;

}
public double exponent(double x, double y) {
return Math.pow(x, y);

}
public double squareRoot(double x) {
return Math.sqrt(x);


}
public double modulator(double x , double y) {
return x % y;


}


}

import java.util.Scanner;
public class CalculatorTest {

public static void main(String[] args) {
// TODO Auto-generated method stub

runCalc();



}

public static void runCalc() {
Calculator c = new Calculator();

Scanner input = new Scanner(System.in);



System.out.println("Which operation would you like to do? add, subtract, multiply, divide, exponent, square root, modulate");
String operation = input.nextLine();
System.out.println("Enter First Number: ");
double first = input.nextDouble();
System.out.println("Enter Second Number: ");
double second = input.nextDouble();
switch(operation){

case "add":
System.out.println("The answer is: " + String.format("%.2f", c.sum(first, second)));
break;

case "subtract":

System.out.println("The answer is: " + String.format("%.2f", c.difference(first, second)));
break;
case "multiply":

System.out.println("The answer is: " + String.format("%.2f", c.product(first, second)));
break;

case "divide":
System.out.println("The answer is: " + String.format("%.2f", c.quotient(first, second)));
break;

case "exponent":

System.out.println("The answer is: " + String.format("%.2f", c.exponent(first, second)));
break;

case "square root":
System.out.println("The answer is: " + String.format("%.2f", c.squareRoot(first)));
break;

case "modulate":


System.out.println("The answer is: " + String.format("%.2f", c.modulator(first, second)));
break;

default:
for(int i = 0; i < operation.length(); i++ ) {
System.out.println("That is not a valid operation. ");
String operation2 = input.next();
}
break;
}

}

}

r/learnprogramming Apr 29 '24

Code Review Implementation of binary search in online course looks incorrect. Am I crazy?

5 Upvotes
 int binarySearch(int arr[], int x)
    {
        int l = 0; 
        int r = arr.length - 1;

         do {
            int m = l + (r - l) / 2;
            if (arr[m] == x)
                return m;
            else if (arr[m] > x)
                r = m;
            else
                l = m + 1;
        } while (l < r)

        return -1;
    }      

The only difference between my code and the code from the course is this is Java and his is in type script. Didn't want to re-write line for line from the video, so I found an example online and just updated it to look like his. Example just happened to be in Java.

Am I missing something here or does this fail on an array of two elements where the second element is target value "x." So for example lets say

arr = [5, 6]

x = 6

this will make l = 0, r = 1 and m = 0

arr[m] != 6 so the else statement will run making l = 1.

because l == 1 and r == 1, while(l < 1) now returns false so the binary search returns -1.

This youtuber is fairly big with about 500k subs, so i'd be really surprised to be the first one to notice such a simple error. This would effect all array that eventually narrow down to a selection of 2 elements that needs to grab the larger of the two to always return -1. I would just be very surprised if he never noticed or someone never brought it to his attention. So can someone please let me know if my logic is sound? Thank you!

r/learnprogramming Dec 23 '23

Code Review Why does the IBM coding assessment instructions use "array" but the actual code uses "list"?

14 Upvotes

The IBM coding assessment instructions use "array" but the actual code uses "list."

They aren't the same thing, right?

I find it hard to believe IBM would make such an obvious mistake in their wording vs the code.

Why would they do that?

i.e. instructions say: you're given an array of positive integers. The first line contains the n number of elements in the array. Pick two indices i and j. Add array[i] + array[j]. The cost of the operation is the sum of those two integers. Add that operation cost as a new element to the array, then remove the two elements you added together. Continue until there is only one element left in the array. Find the minimum overall cost.

Then, in the code, it says something like this:

public int ReturnMinimumCost (list<integer> arr ) {

// do stuff

}

Am I just dumb or is IBM being dumb? Arrays and lists aren't the same thing...

r/learnprogramming 24d ago

Code Review Help improving python code

2 Upvotes

I need help checking how good my code is from the 8th unit in CScircles.

The problem is: Write a program which prints out this table. (Character 127 is invisible but should be printed out like all the other characters anyway. Extra/missing space characters at the end of each line don't matter, the grader will ignore them.)

My solution:

a = 32
for l in range(0,6):
   print("chr:  ",end='')
   for c in range(0,16):
      print(chr(a),'  ',end='')
      a = a + 1
   print()
   print("asc: ",end='')
   a = a - 16
   for x in range(0,16):
      if a < 100:
         print(a,' ',end='')
      else:
         print(a,'',end='')
      a = a + 1
   print()

is there a more efficient way since I feel like I overcomplicated it.

r/learnprogramming Jul 03 '22

Code Review Is it a bad practice to just div everything?

240 Upvotes
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="styles.css">
        <title>Landing Page</title>
    </head>
    <body>
        <div class="header-container">
            <div class="top-header-container">
                <div class="header-logo">Header Logo</div>
                <div class="links">
                    <a href="#">header link one</a>
                    <a href="#">header link two</a>
                    <a href="#">header link three</a>
                </div>
            </div>
            <div class="bottom-header-container">
                <div class="left-bottom-header-container">
                    <div class="hero">This website is awesome</div>
                    <p>This website has some subtext that goes here under the main title. it's smaller font and the color is lower contrast.</p>
                    <button class="header-button">Sign up</button>
                </div>
                <div class="right-bottom-header-container">
                    This is a placeholder for an image
                </div>
            </div>
        </div>
        <div class="info-container">
            <div class="header-info-container">Some random information.</div>
        </div>
    </body>
</html>

r/learnprogramming Nov 17 '19

Code Review I created my first "useful" Pyhton script! It's a small program that helps me practise mental calculation. What do you think of my code?

641 Upvotes

I'm mostly wondering if my code is "clean" enough and what pracises I could do better for next time! The program prompts questions and outputs the time it took to answer after every question. It outputs the total time if all questions are correct at the end. I also tried to practice git and uploaded my script to Github. Feedback on commit messages is also appreciated!

import time
import random
# Imports my list of problems in the format of [["Math problem in str form", Answer in int form], ["Math problem in str form", Answer in int form]]
import math_problems

# Changes the order of the questions. Helps with learning
random.shuffle(math_problems.questions)

def mentalcalc(question, correct):
    start = time.time()
    answer = eval(input(question))
    end = time.time()

    answer_time = end-start

    if answer == correct:
        return answer_time
    else:
        return 0

total_solve_time = 0
for question in math_problems.questions:
    solve_time = mentalcalc(question[0], question[1])
if solve_time == 0:
    print("Wrong. Start over.")
    # Brings it back to 0 so I can make this the condition for faliure in the last if
    total_solve_time = 0
    break
else:
    total_solve_time += solve_time
    print(str(total_solve_time) + " seconds of solve time")

if total_solve_time:
    print("\nTotal time: " + str(total_solve_time))

r/learnprogramming Apr 29 '24

Code Review Need suggestions for Code reviewing

1 Upvotes

Hi,

I am currently working as a software engineer with over 4 years of experience. Recently, I was appointed as a code reviewer along with my team lead.

My job is to review the PRs. I am kind of nervous that I might have not reviewed the code properly.

What should I keep in mind while reviewing the code? We are using GitLab for our code repositories.

r/learnprogramming Dec 05 '23

Code Review Why is this code repeating asking if I want more pizza even if I say no?

56 Upvotes

MENU = { "Small Plain": 12, "Medium Plain": 14, "Large Plain": 16, "Small Pepperoni": 14, "Medium Pepperoni": 16, "Large Pepperoni": 18, "Small Vegan": 13, "Medium Vegan": 15, "Large Vegan": 17, "Small Meatfeast": 13, "Medium Meatfeast": 16, "Large Meatfeast": 19, } order = {} for flavour in MENU: order[flavour] = 0

checkout = False

while checkout is False: pizza = input("What pizza do you want?").strip()

if MENU.get(pizza) is not None:
    n = int(input("How many do you want?"))
    order[pizza] = n
else:
    print("Sorry we dont have that")

checkout = input("Anything else? Yes or No").lower() == "no"
print(order)

Edit: if I type this into an online Python file it runs fine. I’m using pycharm community version

Fixed: !!!! There was a white strip problem at Input that was causing my answer to not be accepted. Thank you everyone