Error: not all code paths Return a value

Asked

Viewed 2,223 times

15

I would like to understand why my code is causing the error

not all code paths Return a value

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace WindowsFormsApplication1
{
    public partial class painel : Form
    {
        public painel()
        {
            InitializeComponent();
        }

        public class componente
        {
            public int ID
            {
                get { return ID; }
                set { ID = value; }
            }

            private string nome;
            public string NOME
            {
                get { return nome; }
                set { nome = value; }
            }

            private string local_armazenamento;
            public string LOCAL_ARMAZENAMENTO
            {
                get { return local_armazenamento; }
                set { local_armazenamento = value; }
            }

            private string descricao;
            public string DESCRICAO
            {
                get { return descricao; }
                set { descricao = value; }
            }
        }

        private List<componente> ObterLista(string nome_componente)
        {
            MySqlConnection caminho = new MySqlConnection(@"SERVER=LOCALHOST;DATABASE=portfolio;UID=root;PASSWORD=vertrigo");
            List<componente> lista = new List<componente>();
            string query = "SELECT * FROM componentes ";

            MySqlCommand cmd = new MySqlCommand(query, caminho);
            caminho.Open();

            MySqlDataReader leitor = cmd.ExecuteReader();

            if (leitor.HasRows)
            {
                while (leitor.Read())
                {
                    componente componente = new componente();

                    componente.ID = Convert.ToInt32(leitor["id"]);
                    componente.NOME = leitor["nome"].ToString();
                    componente.LOCAL_ARMAZENAMENTO = leitor["local_armazenamento"].ToString();
                    componente.DESCRICAO = leitor["descricao"].ToString();
                    lista.Add(componente);
                }
                caminho.Close();
                return lista;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            dataGridView1.DataSource = ObterLista(button1.Text);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            dataGridView1.DataSource = ObterLista(button1.Text);
        }
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

    }
}

8 answers

19


Because not all execution paths return an expected value. Note that the only one return exists in this code is within a if, so it will only run conditionally. What happens if the code does not enter the if? Does it return anything? The code doesn’t say to return anything. Apart from the return of if solves the problem.

The list will be empty, you need to treat that where to consume this method.

private List<componente> ObterLista(string nome_componente) {
    var caminho = new MySqlConnection(@"SERVER=LOCALHOST;DATABASE=portfolio;UID=root;PASSWORD=vertrigo");
    List<componente> lista = new List<componente>();
    var cmd = new MySqlCommand("SELECT * FROM componentes ", caminho);
    caminho.Open();
    MySqlDataReader leitor = cmd.ExecuteReader();
    if (leitor.HasRows) {
        while (leitor.Read()) {
            componente componente = new componente();
            componente.ID = Convert.ToInt32(leitor["id"]);
            componente.NOME = leitor["nome"].ToString();
            componente.LOCAL_ARMAZENAMENTO = leitor["local_armazenamento"].ToString();
            componente.DESCRICAO = leitor["descricao"].ToString();
            lista.Add(componente);
        }
        caminho.Close();
    }
    return lista;
}

I put in the Github for future reference.

Basing my choice

You don’t have to have one else in a code that will return the same thing that is inside the if. Whenever you have two equal codes one inside the if and the other inside the else there’s no need to duplicate the code, take both of the if and else and eliminate redundancy.

There’s no point in having the return nor within the else, that does not need to exist, nor within the if, because whatever happens return lista would need to be returned.

Nor does it seem good to return null. At least nothing in the question indicates that this is desirable. If that were the case it would be better not to initialize the list (List<componente> list;) at first, just initialize inside if, so again would only need to return the list once in the code.

The else is only increasing the cyclomatic complexity for no profit at all.

In addition to eliminating redundancy may be contributing to the DRY, thus the return gets more canonical.

Has forms simpler to make (see more) all the code and with best style. This code will have problems if there is an exception in the middle of the operation. See how it should be.

  • Yeah, that’s right, thanks. But now there are more problems in the code, but this I solve, obg

  • 1

    I figured they would, I’m sorry, but this code is badly written. You can post specific questions for each error, but it will take time to resolve everything because it seems to me that you lack the basis.

  • There’s a lot of ground missing, I’m learning to program myself

  • 3

    @Igor seeks to learn in a structured way. If you stand around like a silly cockroach looking for a solution to every problem that comes along you won’t learn, you’ll just put out a fire. You have to understand why every comma, every space, every word in the code.

14

Your code needs to return a value to All cases, in your Get class this does not happen, when the code enters the condition IF he has a Return, but in case you don’t get in(Else) it returns nothing, which generates the exception, just add a Else that returns a value (a null list for example, but remember to treat this value so as not to generate errors in the rest of the code)

private List<componente> ObterLista(string nome_componente)
{
    MySqlConnection caminho = new MySqlConnection(@"SERVER=LOCALHOST;DATABASE=portfolio;UID=root;PASSWORD=vertrigo");
    List<componente> lista = new List<componente>();
    string query = "SELECT * FROM componentes ";

    MySqlCommand cmd = new MySqlCommand(query, caminho);
    caminho.Open();

    MySqlDataReader leitor = cmd.ExecuteReader();

    if (leitor.HasRows)
    {
        while (leitor.Read())
        {
            componente componente = new componente();
            componente.ID = Convert.ToInt32(leitor["id"]);
            componente.NOME = leitor["nome"].ToString();
            componente.LOCAL_ARMAZENAMENTO = leitor["local_armazenamento"].ToString();
            componente.DESCRICAO = leitor["descricao"].ToString();
            lista.Add(componente);
        }
        caminho.Close();

    }
    else
    {
        //Trata valor a ser retornado
    }

 return lista;

}

If no specific treatment is required for the null list, simply do not use the Else

    }
    else
    {
        //Trata valor a ser retornado
    }

return lista;

for

}
return lista;

Avoiding unnecessary redundancies and always having a return of the method.

11

Because of that:

        if (leitor.HasRows)
        {
            while (leitor.Read())
            {
                componente componente = new componente();

                componente.ID = Convert.ToInt32(leitor["id"]);
                componente.NOME = leitor["nome"].ToString();
                componente.LOCAL_ARMAZENAMENTO = leitor["local_armazenamento"].ToString();
                componente.DESCRICAO = leitor["descricao"].ToString();
                lista.Add(componente);
            }
            caminho.Close();
            return lista;
        }

If leitor no lines, nothing is returned. After the if, put a return null; that must resolve.

10

You are only returning the list in the Obtainer method, if you enter if (reader.Hasrows), if you do not enter, still the method should return something. Follow change in code:

    private List<componente> ObterLista(string nome_componente)
    {
        MySqlConnection caminho = new MySqlConnection(@"SERVER=LOCALHOST;DATABASE=portfolio;UID=root;PASSWORD=vertrigo");
        List<componente> lista = new List<componente>();
        string query = "SELECT * FROM componentes ";

        MySqlCommand cmd = new MySqlCommand(query, caminho);
        caminho.Open();

        MySqlDataReader leitor = cmd.ExecuteReader();

        if (leitor.HasRows)
        {
            while (leitor.Read())
            {
                componente componente = new componente();

                componente.ID = Convert.ToInt32(leitor["id"]);
                componente.NOME = leitor["nome"].ToString();
                componente.LOCAL_ARMAZENAMENTO = leitor["local_armazenamento"].ToString();
                componente.DESCRICAO = leitor["descricao"].ToString();
                lista.Add(componente);
            }
            caminho.Close();
            return lista;
        }
        else return lista;

    }
  • 3

    If the Else return is the same as if, no need to create an Else, you can leave the "Return list" out of the if, save a few lines of code and avoid redundancy.

9

It is because the Get List method is not returning result when reader.Hasrows is equal to false. Change to:

private List<componente> ObterLista(string nome_componente)
    {
        MySqlConnection caminho = new MySqlConnection(@"SERVER=LOCALHOST;DATABASE=portfolio;UID=root;PASSWORD=vertrigo");
        List<componente> lista = new List<componente>();
        string query = "SELECT * FROM componentes ";

        MySqlCommand cmd = new MySqlCommand(query, caminho);
        caminho.Open();

        MySqlDataReader leitor = cmd.ExecuteReader();

        if (leitor.HasRows)
        {
            while (leitor.Read())
            {
                componente componente = new componente();

                componente.ID = Convert.ToInt32(leitor["id"]);
                componente.NOME = leitor["nome"].ToString();
                componente.LOCAL_ARMAZENAMENTO = leitor["local_armazenamento"].ToString();
                componente.DESCRICAO = leitor["descricao"].ToString();
                lista.Add(componente);
            }
            caminho.Close();
            return lista;
        }

        return null;

    }

6

In your method signature, you say it returns a Component list.

Try to put the instruction of return outside the if.

Code:

private List<componente> ObterLista(string nome_componente)
{
    MySqlConnection caminho = new MySqlConnection(@"SERVER=LOCALHOST;DATABASE=portfolio;UID=root;PASSWORD=vertrigo");
    List<componente> lista = new List<componente>();
    string query = "SELECT * FROM componentes ";

    MySqlCommand cmd = new MySqlCommand(query, caminho);
    caminho.Open();

    MySqlDataReader leitor = cmd.ExecuteReader();

    if (leitor.HasRows)
    {
        while (leitor.Read())
        {
            componente componente = new componente();

            componente.ID = Convert.ToInt32(leitor["id"]);
            componente.NOME = leitor["nome"].ToString();
            componente.LOCAL_ARMAZENAMENTO = leitor["local_armazenamento"].ToString();
            componente.DESCRICAO = leitor["descricao"].ToString();
            lista.Add(componente);
        }
        caminho.Close();
    }
    return lista;
}

6

Try to put the Return statement out of the if.

private List<componente> ObterLista(string nome_componente)
{
    MySqlConnection caminho = 
    new MySqlConnection(@"SERVER=LOCALHOST;DATABASE=portfolio;UID=root;PASSWORD=vertrigo");

    List<componente> lista = new List<componente>();
    string query = "SELECT * FROM componentes ";

    MySqlCommand cmd = new MySqlCommand(query, caminho);
    caminho.Open();

    MySqlDataReader leitor = cmd.ExecuteReader();

    if (leitor.HasRows)
    {
        while (leitor.Read())
        {
            componente componente = new componente();

            componente.ID = Convert.ToInt32(leitor["id"]);
            componente.NOME = leitor["nome"].ToString();
            componente.LOCAL_ARMAZENAMENTO = leitor["local_armazenamento"].ToString();
            componente.DESCRICAO = leitor["descricao"].ToString();
            lista.Add(componente);
        }
        caminho.Close();
    }
    return lista;
}

0

private List ObterLista(string nome_componente)
{
    MySqlConnection caminho = 
    new MySqlConnection(@"SERVER=LOCALHOST;DATABASE=portfolio;UID=root;PASSWORD=vertrigo");

List<componente> lista = new List<componente>(); string query = "SELECT * FROM componentes "; MySqlCommand cmd = new MySqlCommand(query, caminho); caminho.Open(); MySqlDataReader leitor = cmd.ExecuteReader(); if (leitor.HasRows) { while (leitor.Read()) { componente componente = new componente(); componente.ID = Convert.ToInt32(leitor["id"]); componente.NOME = leitor["nome"].ToString(); componente.LOCAL_ARMAZENAMENTO = leitor["local_armazenamento"].ToString(); componente.DESCRICAO = leitor["descricao"].ToString(); lista.Add(componente); } caminho.Close(); } return lista;

}

  • 11

    What is the purpose of this answer?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.