How can I avoid repeating code?

Asked

Viewed 92 times

0

I have a command that will need to perform several executions, but I have to put 1,2,3... have to use the same name ?

 btnadd1.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {

            //new Activity_addinf.onbuttonclickHttpPost().execute();
            HttpConnection postCatLivro = new HttpConnection(Activity_addinf.this,
                    catliv.toString(),
                    "http://192.168.1.207/api/v2/bookdemo/_table/cad_categorias?fields=id_cat&filter=%20tx_cat%3D%22Direito%22",
                    0);

            HttpConnection postCatLivro2 =  new HttpConnection(Activity_addinf.this,
                  catliv.toString(),

            "http://192.168.1.207/api/v2/bookdemo/_table/cad_categorias?fields=id_cat&filter=tx_cat%3DRomance",
                  2);



            postCatLivro.execute();
            postCatLivro2.execute();

1 answer

2


Whenever you verify that you are repeating code the first approach is to isolate it in a method. The method should have parameters to receive what is different:

private void postCatLivro(String url, int seq){
    HttpConnection postCatLivro = new HttpConnection(Activity_addinf.this, catliv.toString(),
                                                     url, seq);
    postCatLivro.execute();
}

Use like this:

btnadd1.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view){

        postCatLivro("http://192.168.1.207/api/v2/bookdemo/_table/cad_categorias?fields=id_cat&filter=%20tx_cat%3D%22Direito%22", 0);
        postCatLivro("http://192.168.1.207/api/v2/bookdemo/_table/cad_categorias?fields=id_cat&filter=tx_cat%3DRomance", 2);
    }
}

The difference may seem small, but it gets "tidier", more DRY.

If you find that what is done in this method should not be the responsibility of this class write a new class.

  • That’s what I needed, I just couldn’t explain, thank you !!

Browser other questions tagged

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