Language and reusability

Source: Internet
Author: User

One trick to writing fewer bug programs is to reuse as many reliable, proven public libraries as you can with rigorous testing.

When we achieve reusable goals, it is often desirable to have as few code as possible to express greater reusability, rather than being constrained by issues unrelated to the problem. Sometimes, the design of a language can have a significant impact on the implementation of reusability.

Example: Take out a collection of values for the specified field in the object list.

Using the Java implementation is like this:

 PackageCom.qinshuq.zk.study;ImportJava.lang.reflect.Field;Importjava.util.ArrayList;Importjava.util.List; Public classGettingfieldvalues { Public Static voidMain (string[] args) {printallnamesandages ();    PrintAllNamesAndAges2 (); }         Public Static voidprintallnamesandages () {//Get All ages of personslist<person> persons =createpersons (); List<Integer> ages =NewArraylist<integer>();  for(person p:persons) {Ages.add (P.getage ());                } System.out.println (Ages); //Get all name of catsList<cat> cats =createcats (); List<String> names =NewArraylist<string>();  for(Cat c:cats) {Names.add (C.getname ());    } System.out.println (names); }         Public Static voidPrintAllNamesAndAges2 () {List<Person> persons =createpersons (); List<Cat> cats =createcats (); System.out.println (getallfieldvalues (persons, person.class, "Age")); System.out.println (Getallfieldvalues (Cats, Cat.class, "name")); }        Private Static<T> list<object> getallfieldvalues (list<t>objlist, Class C, String Objfieldname) {List<Object> values =NewArraylist<object>(); Try {             for(Object obj:objlist) {Field F=NULL; F=C.getdeclaredfield (objfieldname); F.setaccessible (true);                Values.add (F.get (obj)); F.setaccessible (false); }            returnvalues; } Catch(SecurityException e) {return NewArraylist<object>(); } Catch(nosuchfieldexception e) {return NewArraylist<object>(); } Catch(IllegalArgumentException e) {return NewArraylist<object>(); } Catch(illegalaccessexception e) {return NewArraylist<object>(); }                    }     Public StaticList<person>createpersons () {List<Person> persons =NewArraylist<person>(); Persons.add (NewPerson ("Qin", 30)); Persons.add (NewPerson ("Shu", 29)); returnpersons; }         Public StaticList<cat>createcats () {List<Cat> cats =NewArraylist<cat>(); Cats.add (NewCat ("Mimi", 2)); Cats.add (NewCat ("Nini", 1)); returnCats; }}classPerson {PrivateString name; Private intAge ;  PublicPerson (String name,intAge ) {         This. Name =name;  This. Age =Age ; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }    }classCat {PrivateString name; Private intyears;  PublicCat (String name,intyears) {         This. Name =name;  This. Years =years; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetyears () {returnyears; }     Public voidSetyears (intyears) {         This. Years =years; }}

in the program, the reflection mechanism is used to get the value of the Object field, and the object type is greatly constrained by it. You either need to write multiple for-loop logic, or you need to walk through the type with difficulty.

In fact, there are only three questions that need to be cared for in this requirement: List, Object field, traversal value set. That is: Iterate through the list and take out the object field values. There is no need to care about what the object is and what the value is. Dynamic languages have better support for this. The implementation of Python uses the following:

#!/usr/bin/env python#-*-coding:utf-8-*-# -------------------------------------------------------------------------------#Name:GetSpecFieldValues.py#purpose:extract all values from specified field of the object in a list. #            #Author:qin.shuq##created:2015-03-12#-------------------------------------------------------------------------------defgetspecfieldvalues (Objlist, fieldName):returnMapLambdaObj:obj.__dict__[FieldName], objlist)classPerson (object):def __init__(self, Name, age): Self.name=name Self.age= AgeclassCat (object):def __init__(self, Name, years): Self.name=name Self.years=yearsif __name__=='__main__': Persons= [Person ('Qin', (), Person ('Shu', 29)] Cats= [Cat ('Mimi', 2), Cat ('Nini', 1)]    PrintGetspecfieldvalues (Persons,' Age')    PrintGetspecfieldvalues (Cats,'name')

where Getspecfieldvalues (objlist, fieldName) only needs a single line of code, it can adapt to the various fields of the various object value types!

Java can also achieve the same goal, just around the bush to circle some circles, writing a little laborious, reusability is not good, and the code is not elegant enough to express the concepts and interactions we have scheduled. In addition to frameworks, technologies, and platforms, programmers also want to be able to program comfort, to use programming languages to express their ideas and ways of doing things, not just to pursue "group productivity" in software engineering.

The essence of programming is to express and maintain large-scale logic.

Language and reusability

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.