How can I avoid repeating code?

0

I have a command that will need to perform several execuutes, but I have to put 1,2,3 ..., can you 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();
    
asked by anonymous 12.06.2017 / 22:23

1 answer

2

Whenever you verify that you are repeating code the first approach is to isolate it in a method. The method must 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 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 a little, but it gets "tidier", more DRY.

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

    
12.06.2017 / 22:42