Lazy Programmers: Chapter 5 and Appendices

In this book we have examined the good side, the bad side, and the ugly ramifications of “lazy programming”.  Let’s briefly recap some of the key points and then answer the “so what” questions we posed in the introduction.  In Chapter 2, The Good, we introduced three ways that lazy programming can be “good”:

1. Lazy can mean “efficient”.

2. Lazy can mean “creative”.

3. Lazy coding techniques are part of the vernacular.

            While all these techniques are good practices that should not be dismissed, the problem lies in attaching the term “lazy” to them.  Automating repetitive tasks can just as easily be labeled “strategic effort” instead of “lazy”.  There are plenty of phrases in common language like “penny wise and pound foolish” that refer to the concept of long-term, strategic thinking (or effort).  In regards to the “creative laziness” of finding an easy way to do “hard things”, it can just as easily be accounted for by simple evolution of our craft.  Finally, the coding techniques explicitly defined as “lazy” like “Lazy Instantiation or Lazy Initialization”, are simply anthropomorphizing our software in a tongue-in-cheek fashion.  A more accurate description would be “just-in-time” or “As Necessary”.   Poor language use is simply that and nothing more.

In Chapter 3, The Bad, we examined three categories (with multiple examples in each) of traditional lazy behavior:

1.      Shortcuts and Band-Aids.

2.      Sweeping Problems Under the Rug.

3.      Avoiding Architectural Issues.

These are serious issues that we demonstrated with concrete examples from hard-won, real-life experience.  Taking shortcuts in the name of expediency is by far the most common poor practice.  The excuse of “not enough time to do it right” is pervasive and sometimes even true.  This practice is so common because it comes from two directions, lazy programmers and short-sighted managers.  Ignoring code smells and technical debt is rationalized away as “not my problem”.  On one end of the spectrum, a code smell is ignored as “just a little messiness that is not a big deal”; whereas technical debt is seen as “too big to tackle right now”.  Both answers are clear signs of both poor training (or no training) and poor code reviews when checking-in code.  Team-wide technical code reviews are critical to train your team members on both “what-to-do” and “what-not-to-do”!  Finally, avoiding architectural issues is the worst variant of a problem seeming to be “too big to handle right now.”  Unfortunately, it also has the most serious ramifications for the long-term health of the project.

In Chapter 4, The Ugly, we revealed and demonstrated three ramifications of the lazy practices of Chapter 3:

1.      Destroying Architectural Cohesion.

2.      Slipping into System Regression.

3.      Most Lazy Programmers are Paycheck Programmers.

A truism in many areas of life is that avoiding problems never works because the problems fester and grow until they are too big to ignore.  This is the fate of every carefully designed software system if expediency trumps quality.  In chapter three’s final section, we described software architecture in terms of the characteristics (reliability, security, scalability, etc.) that the system was designed to achieve.  If those design decisions are not adhered to then the system’s architectural cohesion will diminish.  While this can again generally be blamed on schedule pressures, it is worth noting that Agile processes that are very much in vogue today tend to short-change design (especially BDUF[1]).

Regression testing is a mainstay of good testing practices so that a project continually improves.  If a system regresses, it means that adding new features breaks old features.  This is a cardinal sin for a project and strong evidence that your team has allowed bad habits to slip into their routine.  Laziness in creating automated tests is a major contributor to system regression and this section took pains to demonstrate how to thoroughly test code.  We demonstrated four types of test cases: existence, data-type specific, edge cases and corner cases. Unfortunately, lazy programmers tend to ignore testing edge cases and corner cases for the easier “common case”.  As I have stated many times in this book, these programmers will rationalize this due to schedule pressure.  Though not the subject of this book, I have witnessed the Scrum development process, with its focus on two-week “sprints”, encourage such short-term thinking.  If you only think in terms of two weeks, it is easy to focus only on the “trees” in front of you and miss the forest.

 The end of Chapter 4 opened the aperture to address the ramification of “lazy programming” to the software profession as a whole and to the professionalism of its practitioners.  I strongly asserted that lazy programmers are “paycheck programmers” because they care more for the paycheck then the mission.  By mission, I mean the benefit of the software to the end-users. In some ways we have come full circle because in the introduction of this book we compared it to Ayn Rand’s book the “Virtue of Selfishness”.  In fact, I am asserting that Lazy Programmers subscribe to that vision.  “Laziness as a virtue” is the same puerile nonsense once espoused by Mark Zuckerberg with Facebook’s motto, “move fast and break things”.  Such immature thought has no place in a society where software is “eating the world”, driverless cars are on our roads, and AI algorithms surveil the public spaces. 

We are now prepared to answer the questions we posed in the introduction of this book:

  • “For skill development and the furtherance of your career, is Laziness a Virtue or Vice?”


If you remove semantics from this question and just focus on the behaviors, the answer becomes clear.  Furthering your skillset requires effort and the right mindset, so anything that seeks to skirt effort or avoid work will not help you improve your technical skills.  To have longevity in the technical field, you must be willing to continually learn new things, challenge yourself and teach the things you know to your fellow programmers.  The traditional definition of lazy violates the principles of conduct clearly laid out in the ACM Code of Ethics and Professional Conduct (reprinted in Appendix 1).

  • “For a team leader, should you develop ‘Laziness’ in your junior developers or squash it like a bad habit?”

    Here we are again faced with a conundrum as to the right approach due to the legitimacy of some of the techniques discussed in Chapter 2. Thus, in the same way a good parent struggles over disciplining a child so as to help and not hinder their growth, a good team leader will struggle over exerting discipline upon team members.  The best way to do this is to separate the attitude from the actions.  In other words, it is good to encourage originality and labor-saving efforts to reduce repetitive tasks.  At the same time, it is important to remain vigilant against taking shortcuts, avoiding difficult tasks (i.e. technical debt, architecture, etc.) and deficient testing.  The ramifications of “bad laziness” are too severe to allow a lazy attitude, in any form, to exist unchallenged by the team leader.  As Thomas More said “Silence gives consent”.  Thus, a team leader must not remain silent on this important issue.

  • “For the profession of programming as an engineering discipline, does ‘Laziness’ enhance or reduce the respect our profession garners from society at large?”

This question is by far the easiest as you will be hard-pressed to find “laziness” in any professional code of conduct.  And if you do happen to find one, please email me so I can avoid that profession at all costs.  A simple thought experiment will prove this point: would you seek medical care from a physician that professed to “lazy diagnoses”? Of course not and the same is true for the software engineering profession.  Unfortunately, lazy practitioners are not the real problem in elevating software engineering to the status of a “profession”.  Free market proponents fear licensing of programmers will “kill the golden goose” and disrupt this growth industry.  Simultaneously, regulators struggle with the nascency of the industry and the very nature of “soft-ware” (in contrast to hardware).  Thus, it is the responsibility of every practitioner to make it clear that our profession has matured to the point where we know how to create reliable software and should be held accountable (via licensing) to do so.  I, for one, am a strong proponent of the licensing of software engineers.  I would acquire a license to practice in this field.

In closing, I encourage every practitioner to read and follow the ACM code of ethics and professional conduct printed in Appendix 1.  To that code of conduct, I would add conduct specifically related to laziness.  Something like this:

“As a Professional Software Engineer, I will not practice, promote or promulgate any behavior that seeks to avoid work to the detriment of the long-term success of the project.  I will not ignore code smells, technical debt or architectural issues for the sake of expediency.  I will support the mission of our end-users by striving, at all times, to deliver high quality software.  Furthermore, I will request the same discipline and vigilance from other members of my team and ask they do the same for me.”


Appendix 1  ACM Code of Ethics

ACM Code of Ethics and Professional Conduct

Preamble

Computing professionals' actions change the world. To act responsibly, they should reflect upon the wider impacts of their work, consistently supporting the public good. The ACM Code of Ethics and Professional Conduct ("the Code") expresses the conscience of the profession.

The Code is designed to inspire and guide the ethical conduct of all computing professionals, including current and aspiring practitioners, instructors, students, influencers, and anyone who uses computing technology in an impactful way. Additionally, the Code serves as a basis for remediation when violations occur. The Code includes principles formulated as statements of responsibility, based on the understanding that the public good is always the primary consideration. Each principle is supplemented by guidelines, which provide explanations to assist computing professionals in understanding and applying the principle.

Section 1 outlines fundamental ethical principles that form the basis for the remainder of the Code. Section 2 addresses additional, more specific considerations of professional responsibility. Section 3 guides individuals who have a leadership role, whether in the workplace or in a volunteer professional capacity. Commitment to ethical conduct is required of every ACM member, and principles involving compliance with the Code are given in Section 4.

The Code as a whole is concerned with how fundamental ethical principles apply to a computing professional's conduct. The Code is not an algorithm for solving ethical problems; rather it serves as a basis for ethical decision-making. When thinking through a particular issue, a computing professional may find that multiple principles should be taken into account, and that different principles will have different relevance to the issue.

Questions related to these kinds of issues can best be answered by thoughtful consideration of the fundamental ethical principles, understanding that the public good is the paramount consideration. The entire computing profession benefits when the ethical decision-making process is accountable to and transparent to all stakeholders. Open discussions about ethical issues promote this accountability and transparency.

1. GENERAL ETHICAL PRINCIPLES.

A computing professional should...

1.1 Contribute to society and to human well-being, acknowledging that all people are stakeholders in computing.

This principle, which concerns the quality of life of all people, affirms an obligation of computing professionals, both individually and collectively, to use their skills for the benefit of society, its members, and the environment surrounding them. This obligation includes promoting fundamental human rights and protecting each individual's right to autonomy. An essential aim of computing professionals is to minimize negative consequences of computing, including threats to health, safety, personal security, and privacy. When the interests of multiple groups conflict, the needs of those less advantaged should be given increased attention and priority.

Computing professionals should consider whether the results of their efforts will respect diversity, will be used in socially responsible ways, will meet social needs, and will be broadly accessible. They are encouraged to actively contribute to society by engaging in pro bono or volunteer work that benefits the public good.

In addition to a safe social environment, human well-being requires a safe natural environment. Therefore, computing professionals should promote environmental sustainability both locally and globally.

1.2 Avoid harm.

In this document, "harm" means negative consequences, especially when those consequences are significant and unjust. Examples of harm include unjustified physical or mental injury, unjustified destruction or disclosure of information, and unjustified damage to property, reputation, and the environment. This list is not exhaustive.

Well-intended actions, including those that accomplish assigned duties, may lead to harm. When that harm is unintended, those responsible are obliged to undo or mitigate the harm as much as possible. Avoiding harm begins with careful consideration of potential impacts on all those affected by decisions. When harm is an intentional part of the system, those responsible are obligated to ensure that the harm is ethically justified. In either case, ensure that all harm is minimized.

To minimize the possibility of indirectly or unintentionally harming others, computing professionals should follow generally accepted best practices unless there is a compelling ethical reason to do otherwise. Additionally, the consequences of data aggregation and emergent properties of systems should be carefully analyzed. Those involved with pervasive or infrastructure systems should also consider Principle 3.7.

A computing professional has an additional obligation to report any signs of system risks that might result in harm. If leaders do not act to curtail or mitigate such risks, it may be necessary to "blow the whistle" to reduce potential harm. However, capricious or misguided reporting of risks can itself be harmful. Before reporting risks, a computing professional should carefully assess relevant aspects of the situation.

1.3 Be honest and trustworthy.

Honesty is an essential component of trustworthiness. A computing professional should be transparent and provide full disclosure of all pertinent system capabilities, limitations, and potential problems to the appropriate parties. Making deliberately false or misleading claims, fabricating or falsifying data, offering or accepting bribes, and other dishonest conduct are violations of the Code.

Computing professionals should be honest about their qualifications, and about any limitations in their competence to complete a task. Computing professionals should be forthright about any circumstances that might lead to either real or perceived conflicts of interest or otherwise tend to undermine the independence of their judgment. Furthermore, commitments should be honored.

Computing professionals should not misrepresent an organization's policies or procedures, and should not speak on behalf of an organization unless authorized to do so.

1.4 Be fair and take action not to discriminate.

The values of equality, tolerance, respect for others, and justice govern this principle. Fairness requires that even careful decision processes provide some avenue for redress of grievances.

Computing professionals should foster fair participation of all people, including those of underrepresented groups. Prejudicial discrimination on the basis of age, color, disability, ethnicity, family status, gender identity, labor union membership, military status, nationality, race, religion or belief, sex, sexual orientation, or any other inappropriate factor is an explicit violation of the Code. Harassment, including sexual harassment, bullying, and other abuses of power and authority, is a form of discrimination that, amongst other harms, limits fair access to the virtual and physical spaces where such harassment takes place.

The use of information and technology may cause new, or enhance existing, inequities. Technologies and practices should be as inclusive and accessible as possible and computing professionals should take action to avoid creating systems or technologies that disenfranchise or oppress people. Failure to design for inclusiveness and accessibility may constitute unfair discrimination.

1.5 Respect the work required to produce new ideas, inventions, creative works, and computing artifacts.

Developing new ideas, inventions, creative works, and computing artifacts creates value for society, and those who expend this effort should expect to gain value from their work. Computing professionals should therefore credit the creators of ideas, inventions, work, and artifacts, and respect copyrights, patents, trade secrets, license agreements, and other methods of protecting authors' works.

Both custom and the law recognize that some exceptions to a creator's control of a work are necessary for the public good. Computing professionals should not unduly oppose reasonable uses of their intellectual works. Efforts to help others by contributing time and energy to projects that help society illustrate a positive aspect of this principle. Such efforts include free and open source software and work put into the public domain. Computing professionals should not claim private ownership of work that they or others have shared as public resources.

1.6 Respect privacy.

The responsibility of respecting privacy applies to computing professionals in a particularly profound way. Technology enables the collection, monitoring, and exchange of personal information quickly, inexpensively, and often without the knowledge of the people affected. Therefore, a computing professional should become conversant in the various definitions and forms of privacy and should understand the rights and responsibilities associated with the collection and use of personal information.

Computing professionals should only use personal information for legitimate ends and without violating the rights of individuals and groups. This requires taking precautions to prevent re-identification of anonymized data or unauthorized data collection, ensuring the accuracy of data, understanding the provenance of the data, and protecting it from unauthorized access and accidental disclosure. Computing professionals should establish transparent policies and procedures that allow individuals to understand what data is being collected and how it is being used, to give informed consent for automatic data collection, and to review, obtain, correct inaccuracies in, and delete their personal data.

Only the minimum amount of personal information necessary should be collected in a system. The retention and disposal periods for that information should be clearly defined, enforced, and communicated to data subjects. Personal information gathered for a specific purpose should not be used for other purposes without the person's consent. Merged data collections can compromise privacy features present in the original collections. Therefore, computing professionals should take special care for privacy when merging data collections.

1.7 Honor confidentiality.

Computing professionals are often entrusted with confidential information such as trade secrets, client data, nonpublic business strategies, financial information, research data, pre-publication scholarly articles, and patent applications. Computing professionals should protect confidentiality except in cases where it is evidence of the violation of law, of organizational regulations, or of the Code. In these cases, the nature or contents of that information should not be disclosed except to appropriate authorities. A computing professional should consider thoughtfully whether such disclosures are consistent with the Code.

2. PROFESSIONAL RESPONSIBILITIES.

A computing professional should...

2.1 Strive to achieve high quality in both the processes and products of professional work.

Computing professionals should insist on and support high quality work from themselves and from colleagues. The dignity of employers, employees, colleagues, clients, users, and anyone else affected either directly or indirectly by the work should be respected throughout the process. Computing professionals should respect the right of those involved to transparent communication about the project. Professionals should be cognizant of any serious negative consequences affecting any stakeholder that may result from poor quality work and should resist inducements to neglect this responsibility.

2.2 Maintain high standards of professional competence, conduct, and ethical practice.

High quality computing depends on individuals and teams who take personal and group responsibility for acquiring and maintaining professional competence. Professional competence starts with technical knowledge and with awareness of the social context in which their work may be deployed. Professional competence also requires skill in communication, in reflective analysis, and in recognizing and navigating ethical challenges. Upgrading skills should be an ongoing process and might include independent study, attending conferences or seminars, and other informal or formal education. Professional organizations and employers should encourage and facilitate these activities.

2.3 Know and respect existing rules pertaining to professional work.

"Rules" here include local, regional, national, and international laws and regulations, as well as any policies and procedures of the organizations to which the professional belongs. Computing professionals must abide by these rules unless there is a compelling ethical justification to do otherwise. Rules that are judged unethical should be challenged. A rule may be unethical when it has an inadequate moral basis or causes recognizable harm. A computing professional should consider challenging the rule through existing channels before violating the rule. A computing professional who decides to violate a rule because it is unethical, or for any other reason, must consider potential consequences and accept responsibility for that action.

2.4 Accept and provide appropriate professional review.

High quality professional work in computing depends on professional review at all stages. Whenever appropriate, computing professionals should seek and utilize peer and stakeholder review. Computing professionals should also provide constructive, critical reviews of others' work.

2.5 Give comprehensive and thorough evaluations of computer systems and their impacts, including analysis of possible risks.

Computing professionals are in a position of trust, and therefore have a special responsibility to provide objective, credible evaluations and testimony to employers, employees, clients, users, and the public. Computing professionals should strive to be perceptive, thorough, and objective when evaluating, recommending, and presenting system descriptions and alternatives. Extraordinary care should be taken to identify and mitigate potential risks in machine learning systems. A system for which future risks cannot be reliably predicted requires frequent reassessment of risk as the system evolves in use, or it should not be deployed. Any issues that might result in major risk must be reported to appropriate parties.

2.6 Perform work only in areas of competence.

A computing professional is responsible for evaluating potential work assignments. This includes evaluating the work's feasibility and advisability, and making a judgment about whether the work assignment is within the professional's areas of competence. If at any time before or during the work assignment the professional identifies a lack of a necessary expertise, they must disclose this to the employer or client. The client or employer may decide to pursue the assignment with the professional after additional time to acquire the necessary competencies, to pursue the assignment with someone else who has the required expertise, or to forgo the assignment. A computing professional's ethical judgment should be the final guide in deciding whether to work on the assignment.

2.7 Foster public awareness and understanding of computing, related technologies, and their consequences.

As appropriate to the context and one's abilities, computing professionals should share technical knowledge with the public, foster awareness of computing, and encourage understanding of computing. These communications with the public should be clear, respectful, and welcoming. Important issues include the impacts of computer systems, their limitations, their vulnerabilities, and the opportunities that they present. Additionally, a computing professional should respectfully address inaccurate or misleading information related to computing.

2.8 Access computing and communication resources only when authorized or when compelled by the public good.

Individuals and organizations have the right to restrict access to their systems and data so long as the restrictions are consistent with other principles in the Code. Consequently, computing professionals should not access another's computer system, software, or data without a reasonable belief that such an action would be authorized or a compelling belief that it is consistent with the public good. A system being publicly accessible is not sufficient grounds on its own to imply authorization. Under exceptional circumstances a computing professional may use unauthorized access to disrupt or inhibit the functioning of malicious systems; extraordinary precautions must be taken in these instances to avoid harm to others.

2.9 Design and implement systems that are robustly and usably secure.

Breaches of computer security cause harm. Robust security should be a primary consideration when designing and implementing systems. Computing professionals should perform due diligence to ensure the system functions as intended, and take appropriate action to secure resources against accidental and intentional misuse, modification, and denial of service. As threats can arise and change after a system is deployed, computing professionals should integrate mitigation techniques and policies, such as monitoring, patching, and vulnerability reporting. Computing professionals should also take steps to ensure parties affected by data breaches are notified in a timely and clear manner, providing appropriate guidance and remediation.

To ensure the system achieves its intended purpose, security features should be designed to be as intuitive and easy to use as possible. Computing professionals should discourage security precautions that are too confusing, are situationally inappropriate, or otherwise inhibit legitimate use.

In cases where misuse or harm are predictable or unavoidable, the best option may be to not implement the system.

3. PROFESSIONAL LEADERSHIP PRINCIPLES.

Leadership may either be a formal designation or arise informally from influence over others. In this section, "leader" means any member of an organization or group who has influence, educational responsibilities, or managerial responsibilities. While these principles apply to all computing professionals, leaders bear a heightened responsibility to uphold and promote them, both within and through their organizations.

A computing professional, especially one acting as a leader, should...

3.1 Ensure that the public good is the central concern during all professional computing work.

People—including users, customers, colleagues, and others affected directly or indirectly—should always be the central concern in computing. The public good should always be an explicit consideration when evaluating tasks associated with research, requirements analysis, design, implementation, testing, validation, deployment, maintenance, retirement, and disposal. Computing professionals should keep this focus no matter which methodologies or techniques they use in their practice.

3.2 Articulate, encourage acceptance of, and evaluate fulfillment of social responsibilities by members of the organization or group.

Technical organizations and groups affect broader society, and their leaders should accept the associated responsibilities. Organizations—through procedures and attitudes oriented toward quality, transparency, and the welfare of society—reduce harm to the public and raise awareness of the influence of technology in our lives. Therefore, leaders should encourage full participation of computing professionals in meeting relevant social responsibilities and discourage tendencies to do otherwise.

3.3 Manage personnel and resources to enhance the quality of working life.

Leaders should ensure that they enhance, not degrade, the quality of working life. Leaders should consider the personal and professional development, accessibility requirements, physical safety, psychological well-being, and human dignity of all workers. Appropriate human-computer ergonomic standards should be used in the workplace.

3.4 Articulate, apply, and support policies and processes that reflect the principles of the Code.

Leaders should pursue clearly defined organizational policies that are consistent with the Code and effectively communicate them to relevant stakeholders. In addition, leaders should encourage and reward compliance with those policies, and take appropriate action when policies are violated. Designing or implementing processes that deliberately or negligently violate, or tend to enable the violation of, the Code's principles is ethically unacceptable.

3.5 Create opportunities for members of the organization or group to grow as professionals.

Educational opportunities are essential for all organization and group members. Leaders should ensure that opportunities are available to computing professionals to help them improve their knowledge and skills in professionalism, in the practice of ethics, and in their technical specialties. These opportunities should include experiences that familiarize computing professionals with the consequences and limitations of particular types of systems. Computing professionals should be fully aware of the dangers of oversimplified approaches, the improbability of anticipating every possible operating condition, the inevitability of software errors, the interactions of systems and their contexts, and other issues related to the complexity of their profession—and thus be confident in taking on responsibilities for the work that they do.

3.6 Use care when modifying or retiring systems.

Interface changes, the removal of features, and even software updates have an impact on the productivity of users and the quality of their work. Leaders should take care when changing or discontinuing support for system features on which people still depend. Leaders should thoroughly investigate viable alternatives to removing support for a legacy system. If these alternatives are unacceptably risky or impractical, the developer should assist stakeholders' graceful migration from the system to an alternative. Users should be notified of the risks of continued use of the unsupported system long before support ends. Computing professionals should assist system users in monitoring the operational viability of their computing systems, and help them understand that timely replacement of inappropriate or outdated features or entire systems may be needed.

3.7 Recognize and take special care of systems that become integrated into the infrastructure of society.

Even the simplest computer systems have the potential to impact all aspects of society when integrated with everyday activities such as commerce, travel, government, healthcare, and education. When organizations and groups develop systems that become an important part of the infrastructure of society, their leaders have an added responsibility to be good stewards of these systems. Part of that stewardship requires establishing policies for fair system access, including for those who may have been excluded. That stewardship also requires that computing professionals monitor the level of integration of their systems into the infrastructure of society. As the level of adoption changes, the ethical responsibilities of the organization or group are likely to change as well. Continual monitoring of how society is using a system will allow the organization or group to remain consistent with their ethical obligations outlined in the Code. When appropriate standards of care do not exist, computing professionals have a duty to ensure they are developed.

4. COMPLIANCE WITH THE CODE.

A computing professional should...

4.1 Uphold, promote, and respect the principles of the Code.

The future of computing depends on both technical and ethical excellence. Computing professionals should adhere to the principles of the Code and contribute to improving them. Computing professionals who recognize breaches of the Code should take actions to resolve the ethical issues they recognize, including, when reasonable, expressing their concern to the person or persons thought to be violating the Code.

4.2 Treat violations of the Code as inconsistent with membership in the ACM.

Each ACM member should encourage and support adherence by all computing professionals regardless of ACM membership. ACM members who recognize a breach of the Code should consider reporting the violation to the ACM, which may result in remedial action as specified in the ACM's Code of Ethics and Professional Conduct Enforcement Policy.

The Code and guidelines were developed by the ACM Code 2018 Task Force: Executive Committee Don Gotterbarn (Chair), Bo Brinkman, Catherine Flick, Michael S Kirkpatrick, Keith Miller, Kate Varansky, and Marty J Wolf. Members: Eve Anderson, Ron Anderson, Amy Bruckman, Karla Carter, Michael Davis, Penny Duquenoy, Jeremy Epstein, Kai Kimppa, Lorraine Kisselburgh, Shrawan Kumar, Andrew McGettrick, Natasa Milic-Frayling, Denise Oram, Simon Rogerson, David Shamma, Janice Sipior, Eugene Spafford, and Les Waguespack. The Task Force was organized by the ACM Committee on Professional Ethics. Significant contributions to the Code were also made by the broader international ACM membership. This Code and its guidelines were adopted by the ACM Council on June 22nd, 2018.

This Code may be published without permission as long as it is not changed in any way and it carries the copyright notice. Copyright (c) 2018 by the Association for Computing Machinery.


Listing 8. ImageTool

package us.daconta.lazy.programmers.examples;

import java.awt.BorderLayout;

import java.awt.Dimension;

import java.awt.Graphics;

import java.awt.Image;

import java.awt.Rectangle;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.IOException;

import javax.imageio.ImageIO;

import javax.swing.ImageIcon;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

/**

 *

 * @author mdaconta

 */

public class ImageTool extends JFrame

{

    private BufferedImage image;

    public ImageTool(String fullpath) throws IOException

    {

        this(new ImageIcon(fullpath));

    }

   

    public ImageTool(BufferedImage img)

    {

        this(new ImageIcon(img));

    }

   

    public ImageTool(ImageIcon icon)

    {

        super("Image Frame");

        image = imageToBufferedImage(icon.getImage());

        JLabel imgLabel = new JLabel();

        imgLabel.setIcon(icon);

        JPanel panel = new JPanel();

        panel.add(imgLabel);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        getContentPane().add(panel);

        pack();       

    }

    

    public static BufferedImage imageToBufferedImage(Image img)

    {

        BufferedImage bufImg = new BufferedImage

        (img.getWidth(null),img.getHeight(null),BufferedImage.TYPE_INT_RGB);

        Graphics graphics = bufImg.getGraphics();

        graphics.drawImage(img, 0, 0, null);

        graphics.dispose();

        return bufImg;

  }

   

    public BufferedImage getImage()

    {

        return image;

    }

    

    public BufferedImage getSubImage(Rectangle r)

    {

        BufferedImage subImage = null;

        if (image != null)

        {

            Rectangle imgRect = new Rectangle(0, 0, image.getWidth(),  

                                                                        image.getHeight());

            if (r != null && imgRect.contains(r))

            {

                subImage = image.getSubimage(r.x, r.y, r.width, r.height);

            }

        }

        return subImage;

    }

    

    public static void main(String [] args)

    {

        try

        {

            ImageTool imgFrame = new ImageTool(args[0]);

            imgFrame.setVisible(true);

            int x = Integer.parseInt(args[1]);

            int y = Integer.parseInt(args[2]);

            int width = Integer.parseInt(args[3]);

            int height = Integer.parseInt(args[4]);

            BufferedImage subImage = imgFrame.getSubImage(new

                                                                           Rectangle(x,y,width,height));

            ImageTool subImageFrame = new ImageTool(subImage);

            subImageFrame.setVisible(true);

        } catch (Throwable t)

          {

              t.printStackTrace();

          }

    }

}

Listing 9. ImageToolTest

package us.daconta.lazy.programmers.examples;

import java.awt.Image;

import java.awt.Rectangle;

import java.awt.image.BufferedImage;

import java.awt.image.Raster;

import java.io.IOException;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

/**

 * JUnit tests for ImageTool class.

 * @author mdaconta

 */

public class ImageToolTest {

   

    private boolean comparePixels(BufferedImage image1, BufferedImage image2) {

       int width = image1.getWidth();

       int height = image1.getHeight();

       int width2 = image2.getWidth();

       int height2 = image2.getHeight();

       if (width != width2 || height != height2) {

           return false;

       }

       for (int row = 0; row < height; row++) {

          for (int col = 0; col < width; col++) {

              if (image1.getRGB(col,row) != image2.getRGB(col,row))

              {

                  return false;

              }

          }

       }

       return true;

    }

    /**

     * Test of getSubImage method, of class ImageTool.

     */

    @org.junit.jupiter.api.Test

    public void testGetSubImage() throws IOException {

        System.out.println("Testing getSubImage");

        ImageTool instance = new ImageTool(

"C:\\Users\\mdaconta\\Documents\\ paycheck-programmer.jpg");

        BufferedImage image = instance.getImage();

        System.out.println("Test #1: null");

        Rectangle r = null;

        BufferedImage expResult = null;

        BufferedImage result = instance.getSubImage(r);

        assertEquals(expResult, result);

        /* Note: these would all be separately viewed and validated against a known

            image for correctness or even better, generated programmatically in a

            standard, synthetic test pattern. */

        BufferedImage upperEdge = image.getSubimage(0, 0, image.getWidth(), 1);

        BufferedImage lowerEdge = image.getSubimage(0, image.getHeight() - 1,

                                                                                      image.getWidth(),1);

        BufferedImage rightEdge = image.getSubimage(image.getWidth() - 1, 0, 1,

                                                                                     image.getHeight());

        BufferedImage leftEdge = image.getSubimage(0, 0, 1, image.getHeight());

        BufferedImage upperLeftCorner = image.getSubimage(0, 0, 1, 1);

        BufferedImage upperRightCorner = image.getSubimage(image.getWidth() - 1,

                                                                                                  0, 1, 1);

        BufferedImage lowerLeftCorner = image.getSubimage(0, image.getHeight() -  

                                                                                               1, 1, 1);

        BufferedImage lowerRightCorner = image.getSubimage(image.getWidth() - 1,

                                                                                       image.getHeight() - 1, 1, 1);

        

        System.out.println("Test #2: zeroes");

        r = new Rectangle(0,0,0,0);

        expResult = null;

        result = instance.getSubImage(r);

        assertEquals(expResult, result);  

       

        System.out.println("Test #3: negative");

        r = new Rectangle(-1,1,1,1);

        expResult = null;

        result = instance.getSubImage(r);

        assertEquals(expResult, result);   

        

        // upper edge

        System.out.println("Test #4: upper edge");

        r = new Rectangle(0,0,image.getWidth(),1);

        int expectedWidth = image.getWidth();

        int expectedHeight = 1;

        result = instance.getSubImage(r);

        assertResults(result, upperEdge, expectedWidth, expectedHeight);

       

        // lower edge

        System.out.println("Test #5: lower edge");

        r = new Rectangle(0, image.getHeight() - 1, image.getWidth(),1);

        expectedWidth = image.getWidth();

        expectedHeight = 1;

        result = instance.getSubImage(r);

        assertResults(result, lowerEdge, expectedWidth, expectedHeight);

       

        // left egde

        System.out.println("Test #6: left edge");

        r = new Rectangle(0, 0, 1, image.getHeight());

        expectedWidth = 1;

        expectedHeight = image.getHeight();

        result = instance.getSubImage(r);

        assertResults(result, leftEdge, expectedWidth, expectedHeight);

       

        // right edge

        System.out.println("Test #7: right edge");

        r = new Rectangle(image.getWidth() - 1, 0, 1, image.getHeight());

        expectedWidth = 1;

        expectedHeight = image.getHeight();

        result = instance.getSubImage(r);

        assertResults(result, rightEdge, expectedWidth, expectedHeight);

        

        // UL corner

        System.out.println("Test #8: UL corner");

        r = new Rectangle(0, 0, 1, 1);

        expectedWidth = 1;

        expectedHeight = 1;

        result = instance.getSubImage(r);

        assertResults(result, upperLeftCorner, expectedWidth, expectedHeight);

       

        // UR corner

         System.out.println("Test #9: UR corner");

        r = new Rectangle(image.getWidth() - 1, 0, 1, 1);

        expectedWidth = 1;

        expectedHeight = 1;

        result = instance.getSubImage(r);

        assertResults(result, upperRightCorner, expectedWidth, expectedHeight);

       

        // LL corner

         System.out.println("Test #10: LL corner");

        r = new Rectangle(0, image.getHeight() - 1, 1, 1);

        expectedWidth = 1;

        expectedHeight = 1;

        result = instance.getSubImage(r);

        assertResults(result, lowerLeftCorner, expectedWidth, expectedHeight);

       

        // LR corner

        System.out.println("Test #11: LR corner");

        r = new Rectangle(image.getWidth() - 1, image.getHeight() - 1, 1, 1);

        expectedWidth = 1;

        expectedHeight = 1;

        result = instance.getSubImage(r);

        assertResults(result, lowerRightCorner, expectedWidth, expectedHeight);

    }

   

    private void assertResults(BufferedImage result, BufferedImage expectedResult,

                          int expectedWidth, int expectedHeight)

    {

        assertNotNull(result);

        assertEquals(result.getWidth(), expectedWidth);

        assertEquals(result.getHeight(), expectedHeight);

        assertTrue(comparePixels(result, expectedResult));

    }

}



[1]https://en.wikipedia.org/wiki/Big_Design_Up_Front