Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the points that good programmers pay attention to?

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "what are the points that good programmers pay attention to". Interested friends might as well take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what are the points that good programmers pay attention to?"

1. Walk half a mile more

Many things are not difficult, but lack the habit of walking more than half a mile!

Counterexample

Public boolean isInValid (String str) {if (str = = null | | str.trim () .length () = = 0) {return true;} return false;}

One more step, the sea and the sky are broad.

Public boolean isInValid (String str) {return (str = = null) | | (str.trim () .length () = = 0);}

A programmer knows which is better!

There is also a code that has been seen many times:

Public boolean isEmptyName () {return StringUtils.isEmpty (name)? True: false;}

Don't you feel superfluous?

Another half a step, beautiful scenery

Public boolean isEmptyName () {return StringUtils.isEmpty (name);} 2. Empty object

NullPointException, let us be difficult to guard against; especially the use of third-party API, if you throw this exception, it will make people feel the urge to swear. So: if you don't want to step on a hole, please don't dig a hole for others.

Ideal requirement: the word "return null" should not appear in the body of all the public methods we produce with return values. Empty object is the landing realization of this idea.

Case: query and return a teacher or student whose name is steven.

Public static SearchFilter name (String name) {return human-> human.getName (). EqualsIgnoreCase (name);} public Human find (SearchFilter filter) {for (Human human: humans) {if (filter.isMatched (human)) {return human;}} return new NullHuman (); / / if you return to NULL, one day you will be scolded! } / / TestassertFalse (edu.find (name ("steven")). IsNull (); 3. Single instance complex

When it comes to design patterns, many people will feel lofty, so when they learn one of them, they will use them without restraint.

Singleton, the simplest design pattern in GOF, is easy to use and very convenient, but to be honest, many people are abusing it. Our system can be seen everywhere, but before you use it, please ask yourself whether there is really and only one instance of this kind in the system.

Otherwise, reject the single instance. Too many single instances will bring endless annoyance to your automated testing.

4. Make full use of enumerations

Enumerations have some powerful features that are easy to be ignored, such as enumerating objects themselves can also carry variables; this feature makes enumerations play an irreplaceable role in more situations.

For example: different weapons have different lethality, and the lethality variable can be carried into the enumeration value of the weapon.

Public enum EquipmentEnum {Staff (20), Hammer (10); double playerRisedAbility; EquipmentEnum (double playerRiseAbility) {this.playerRisedAbility = playerRiseAbility;} public double getRaiseAbility (double originalAbility) {return Double.sum (originalAbility, playerRisedAbility);}} 5. Improve the quality of notes

The era of 30% code comment ratio is a thing of the past, and the best annotation is that there are no comments, and programmers should strive to make comments disappear through naming.

A large number of practices have proved that with the increasing frequency of refactoring, the possibility of updating comments synchronously with code changes in the process of refactoring is almost zero. Over time, comments and code are poles apart.

6. Customer-oriented naming

Good naming can please the reader's mood and make people want to see the author's true face!

Case study:

A real estate developer opens a new real estate with the original price of 800000 per set, with the following preferential policies, but the preferential policies may be different with the stock of the real estate. Write a program for the developer to calculate the housing price.

Regular customers can buy second homes at a discount of 4%, which can be added up.

Customers can get a discount of 3% for one-time full payment, which can be added up.

Public class Customer {Benefiter benefit = new NullBenefiter (); public void is (Benefiter benefits) {/ / the original set method, renaming can have an unexpected effect. This.benefit = benefits;} public double shouldPay (double srcPrice) {return srcPrice-benefit.benefit (srcPrice);} @ FunctionalInterfacepublic interface Benefiter {abstract double benefit (double srcPrice); default Benefiter and (final Benefiter otherPolicy) {return srcPrice-> (benefit (srcPrice) + otherPolicy.benefit (srcPrice));}}

Benefiting from good naming, the semantics of customer code stands out on paper: customer.is (oldCustomer (). And (fullPay ()

7. Use multidimensional arrays

Arrays are a necessary data structure for any relatively advanced machine language, but it seems to be ignored by object-oriented developers.

In some specific scenarios, it can have an unexpected effect.

Case: conversion between US dollar, franc and RMB. Among them, US dollar: Franc = 1 Fren 2; USD: RMB = 1:8

Public class ExchangeRate {public static final int DOLLAR = 0; public static final int FRANC = 1; public static final int YMB = 2; private static final double [] [] rates = {/ / two-dimensional array defines the exchange rate between currencies, simple and efficient {1.0d, 2.0d, 8.0d}, {0.5d, 1.0d, 4.0d}, {0.125d, 0.25d, 1.0d}} Public static double getRateOf (Currency src, Currency tgt) {return rates [src.ID] [tgt.ID];}} public class Cash {private double value; private Currency unit; public Cash (double value, Currency unit) {this.value = value; this.unit = unit;} @ Override public boolean equals (Object obj) {if (obj instanceof Cash) {Cash other = (Cash) obj Return value = = other.value * getRateOf (other.unit, unit);} return false;}}

If a two-dimensional array of exchange rates is defined and initialized using a profile, it can also take the design to a new level-- easy to extend, even without modifying any Java code.

8. Specification function input parameter

When we call an external API, the ideal is zero input parameters, even if there are input parameters, we want to be of clear type and enumerable range, which will make us more sense of security when using this API! By the same token, when you declare a function as public, be careful to define its arguments.

If you get the exchange rate function between the two currencies in the above case:

Public static double getRateOf (Currency src, Currency tgt) {return rates [src.ID] [tgt.ID];}

Defined as

Public static double getRateOf (int src, int tgt) {return rates [src] [tgt];}

Although the implementation of the function is a little simpler, it is conceivable that this API will make users very afraid! Array out-of-bounds exceptions must occur frequently.

On the contrary, the type and scope of input parameters are specified by enumeration, giving users some fixed options, users have a lot less concern, and our program is more secure.

Therefore: we provide external API input parameters to minimize the use of String, Int, such basic types, the more room for users to play, the greater the possibility of making mistakes, because you expose the risk to uncontrolled users.

9. It is often encapsulated to remove weight.

Whether you are impetuous about repeatedly writing code like "if (tasks! = null & & tasks.size () > 0)" or "if (name! = null & & (! name.isEmpty ())"), you can actually save yourself.

Package it.

Public class CollectionUtil {public static boolean isEmpty (Collection collection) {return collection = = null | | collection.isEmpty ();}}

And

Public class StringUtil {public static boolean isEmpty (String context) {return context = = null | | context.isEmpty ();}}

Everything becomes very simple, the mood is good, the efficiency is also high!

10. Dissolve the toxin of if/else

Our system is full of if/else logic because it is "simple" and easy to use! But with the passage of time and the expansion of requirements, one day you will find that you can't even read the if/else you wrote.

So you have to learn to reject the nesting of this kind of logic in the first place, or when you look at the nested complex logic and boldly reconstruct it.

Example: enter a value of 1-1000 N, if N is 3 or a multiple of 3, return "FIZZ"; if N is 5 or a multiple of 5, return "BUZZ"; if it is both a multiple of 3 and a multiple of 5, return "FIZZBUZZ"; others output N.

Original implementation: process-oriented code public String say (int input) throws Exception {if (input) wrapped in an object shell

< 1 || input >

1000) {throw new Exception ("Invalid input");} if (input% 15 = = 0) {return "FIZZBUZZ";} if (input% 5 = = 0) {return "BUZZ";} if (input% 3 = = 0) {return "FIZZ";} return String.valueOf (input);}

Smell the bad smell, if the demand expands in the future, such as introducing multiples of 7. According to this logic, continue to add if, the problem is solved, but one day you will doubt life!

Improvement 1: introducing responsibility chain and template method model

Public String say (int input) throws Exception {if (input)

< 1 || input >

1000) {throw new Exception ("Invalid input");} DefaultParser defaultParser = new DefaultParser (null); MultiOfThreeParser multiOfThreeParser = new MultiOfThreeParser (defaultParser); MultiOfFiveParser multiFiveParser = new MultiOfFiveParser (multiOfThreeParser); MultiOfFifteenParser fifteenPaser = new MultiOfFifteenParser (multiFiveParser); return fifteenPaser.parse (input);} public abstract class Parser {abstract boolean isFixedResponsibility (int inputContext); abstract String response (int inputContext) throws Exception Public String parse (int inputContext) throws Exception {if (isFixedResponsibility (inputContext)) {return response (inputContext);} if (nextParser! = null) {return nextParser.parse (inputContext);} return NULL;}} public class MultiOfFifteenParser extends Parser {public MultiOfFifteenParser (Parser nextParser) {super (nextParser) @ Override public String response (int inputContext) throws Exception {return FLAG_FOR_MULIT_OF_FIFTEEN;} @ Override boolean isFixedResponsibility (int inputContext) {return inputContext% 15 = = 0;}}

It looks much better, but there seems to be something wrong with it.

Improvement 2: put on the object's robe thoroughly

Keen readers may also find that there is a slight problem with the above improvements, which is the exception branch handling in the say method. How there is still an if, for a perfectionist obsessive-compulsive disorder, its existence is a disaster. Continue to improve:

Public String say (int input) throws Exception {DefaultParser defaultParser = new DefaultParser (null); MultiOfThreeParser multiOfThreeParser = new MultiOfThreeParser (defaultParser); MultiOfFiveParser multiOfFiveParser = new MultiOfFiveParser (multiOfThreeParser); MultiOfFifteenParser FifteenPaser = new MultiOfFifteenParser (multiOfFiveParser); InvalidNumberParser invalidNumberPaser = new InvalidNumberParser (FifteenPaser); return invalidNumberPaser.parse (input);} public class InvalidNumberParser extends Parser {public InvalidNumberParser (Parser nextParser) {super (nextParser) } @ Override String response (int inputContext) throws Exception {throw new Exception ("Invalid input");} @ Override boolean isFixedResponsibility (int inputContext) {return (inputContext)

< L_THRESHOLD) || (inputContext >

H_THRESHOLD);}} at this point, I believe you all have a deeper understanding of what good programmers are paying attention to, so you might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report