[VV58] serialization & inheritance, WebMvcTest, useState vs. signal, clean code guide, KISS, interface design, self-management
[VV58] The Java Fullstack Newsletter

[VV58] serialization & inheritance, WebMvcTest, useState vs. signal, clean code guide, KISS, interface design, self-management

???JAVA CERTIFICATION QUESTION: serialization and inheritance

You are working to enhance a legacy application, in particular to add serialization support and add more constraints to new business objects.

The legacy application class looks like this:

public class Person {
  private String name = null;
  public Person() {}
  public Person(String s) {
    name = s;
  }
}        

You’ve also added a new application class.

public class EnhancedPerson extends Person implements Serializable {
  public EnhancedPerson(String s) {
    super(s);
    if (s == null || s.length() == 0) {
      throw new IllegalArgumentException("Invalid name");
    }
  }
}        

Which statement is correct? Choose one.

* The EnhancedPerson class may not participate in serialization because its superclass is not serializable.

* The EnhancedPerson class may not participate in serialization because it does not have a zero-argument constructor.

* The EnhancedPerson class can be serialized but cannot be deserialized.

* Immediately after deserialization, the name field of an EnhancedPerson will have a null value.

* The EnhancedPerson class will always throw IllegalArgumentException during deserialization.

#java #certificationquestion #ocp

https://www.udemy.com/course/ocp-oracle-certified-professional-java-developer-prep/?referralCode=54114F9AD41F127CB99A

Answer. This question investigates the deserialization process of an object that has a nonserializable parent type.

'The EnhancedPerson class may not participate in serialization because its superclass is not serializable.' is wrong because every object has a nonserializable parent (java.lang.Object).

'The EnhancedPerson class may not participate in serialization because it does not have a zero-argument constructor.' is wrong.

'The EnhancedPerson class can be serialized but cannot be deserialized.' is also incorrect because nothing in the code prev ents deserialization.

If the zero-argument constructor of Person were private, or if it did not exist, this option would be correct.

'Immediately after deserialization, the name field of an EnhancedPerson will have a null value.' is correct because the name field belongs to the Person aspect of the EnhancedPerson object.

Such fields are not part of the serialized information.

When the Person instance is re-created, this is done by calling the zero-argument constructor of Person.

Because of this, the name field will be initialized to null.

'The EnhancedPerson class will always throw IllegalArgumentException during deserialization.' is incorrect.

The deserialization process for (nonrecord) classes does not call any constructor in the Serializable aspects of the object.

This means that the code in the EnhancedPerson constructor that validates the supplied name will not be called.

Therefore, no exception can be thrown.




???? SPRING CERTIFICATION QUESTION: Which statement is false about Web slice testing with @WebMvcTest?

* @WebMvcTest disables full auto-configuration

* @WebMvcTest auto-configure MockMvc bean

* @WebMvcTest does not auto-configure by default Spring Security

* Typically @WebMvcTest is used in combination with @MockBean for mocking dependencies

#spring #certificationquestion #vcp

https://www.udemy.com/course/spring-professional-certification-6-full-tests-2v0-7222-a/?referralCode=04B6ED315B27753236AC

Answer: the wrong statement is '* @WebMvcTest does not auto-configure by default Spring Security'

Spring doc:

By default, tests annotated with @WebMvcTest will also auto-configure Spring Security and MockMvc.

https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTest.html

Baeldung:

Testing Controllers With @WebMvcTest

When using the @WebMvcTest annotation approach with Spring Security,

MockMvc is automatically configured with the necessary filter chain required to test our security configuration.

Because MockMvc is configured for us, we’re able to use @WithMockUser for our tests without any additional configuration:

@RunWith(SpringRunner.class)
@WebMvcTest(SecuredController.class)
public class SecuredControllerWebMvcIntegrationTest {
    @Autowired
    private MockMvc mvc;
    // ... other methods
    @WithMockUser(value = "spring")
    @Test
    public void givenAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception {        mvc.perform(get("/private/hello").contentType(MediaType.APPLICATION_JSON))
          .andExpect(status().isOk());
    }
}        

Note that using @WebMvcTest will tell Spring Boot to instantiate only the web layer and not the entire context.

Because of this, controller tests that use @WebMvcTest will run faster than with other approaches.

https://www.baeldung.com/spring-security-integration-tests#testing-controllers-with-webmvctest




QUOTE ???

Be cautious of misleading comments; the truth is always in the code.



React useState() vs. Angular signal()

The React 18 useState() hook and the Angular 16 Signal feature are both ways of managing state in functional components. However, they have some differences in how they work and what they offer. Here are some of the main differences:

Here are some code examples to illustrate the differences:

React useState() hook:

import { useState } from "react";

const Counter = (props) => {
  // Define a state variable for the count and initialize it to 0
  const [count, setCount] = useState(0);

  // Define a function to increment the count by 1
  function increment() {
    // Update the count by passing a new value
    setCount(count + 1);
  }

  // Define a function to decrement the count by 1
  function decrement() {
    // Update the count by passing a function that returns a new value
    setCount((prevCount) => prevCount - 1);
  }

  return (
    <div>
      <p>The count is: {count}</p>
      <button onClick={increment}>+</button>
      <button onClick={decrement}>-</button>
    </div>
  );
};

export default Counter;        

https://github.com/vinny59200/VV-React-Counter

Angular Signal feature:

import { Component } from "@angular/core";
import { signal, computed }from '@angular/core';

@Component({
  selector: "my-counter",
  template: `
    <div>
      <p>The count is: {{ count() }}</p>
      <p>The double count is: {{ doubleCount() }}</p>
      <button (click)="increment()">+</button>
      <button (click)="decrement()">-</button>
    </div>
  `,
})
export class CounterComponent {
  // Define a writable signal for the count and initialize it to 0
  count = signal(0);

  // Define a computed signal for the double count that depends on the count
  doubleCount = computed(() => this.count() * 2);

  // Define a method to increment the count by 1
  increment() {
    // Update the count by using the update method
    this.count.update((value) => value + 1);
  }

  // Define a method to decrement the count by 1
  decrement() {
    // Update the count by using the set method
    this.count.set(this.count() - 1);
  }
}        

https://github.com/vinny59200/VV-NG-Counter

Learn




How to write code that survives the test of time? ??

I am part of a team that wants to establish some basic good practices for code review. We want to make sure that our code is readable and maintainable even after months of development. We are looking for a concise guide that summarizes the key principles.

But I am not sure if such a guide exists. There are so many recommendations, how can we fit them all in a short document?

What do you think?

#coding #goodPractices #cleancode #teamwork #miniGuide




Keep It Simple, and Stupid ??

?????? ?????????????? ???? ???????????? ???? ???????????????? ?????????????????????? ??

Plato's Wisdom: "???????????? ???? ?????????? ?????? ????????????? ?????? ?????????? ?????? ???????? ?????????? ?????????????? ???? ????????????????????."

In the world of software development, Plato's quote underscores the values we should embrace.

Beauty in style, harmony, grace, and rhythm resonates with our pursuit of

* readability,

* maintainability,

* speed of development, and

* elusive beauty in code.

Simplicity, as Plato suggests, is the keystone for these ideals.

?????? ???????????????????? ???????????? ???? ?????????????????? ???????? ??

Diverse Perspectives: The perception of beautiful code varies with individual backgrounds.

Art-oriented minds compare code to artistry, while science enthusiasts analyze it for symmetry and mathematical precision.

Yet, simplicity consistently underpins their arguments, forming the common ground where beauty emerges.

?????????????????? ?????? ???????????? ???? ???????? ??

Simplicity's Influence: To identify beautiful code, one must seek simplicity in its properties.

Regardless of an application's complexity, simplicity thrives in its foundation.

Embracing simplicity yields clear, maintainable, and testable code with concise methods, ensuring efficiency throughout the system's lifecycle.

Beauty, it seems, is nurtured and discovered in the realm of simplicity.

???? ??????????????, ???????????? ???? ???????????????? ?????????????????????? ???? ?????????? ???? ????????????????????. ??

Remember Da Vinci quote: “Simplicity is the ultimate sophistication”.

#kiss #keepItSimpleStupid #programming #simplicityIsTheUltimateSophistication #programmer




?? Design Interfaces for Simplicity and Error Prevention

?????????????????? ?????????????????????????? ??

Interface specification is a fundamental task in software development, encompassing various levels of abstraction,

? from user interfaces

? to function and class interfaces.

Regardless of the context, designing interfaces is a crucial aspect of the job.

Well-designed interfaces enhance user experience ??,

while poorly designed ones lead to frustration and errors ??.

Effective interfaces share common characteristics:

* they are easy to use correctly, guiding users naturally, and

* hard to use incorrectly, preventing mistakes proactively.

???????? ?????? ??????????-?????????????????? ??

User-friendly interfaces follow the path of least resistance, making correct interactions intuitive, whether in graphical interfaces or APIs.

Anticipating user errors and designing interfaces to prevent them is key.

Prototyping and testing interfaces early in the development process can ensure they meet users' needs and expectations.

Additionally, adjusting interfaces based on user feedback helps eliminate misuse, with the ultimate goal of making incorrect use impossible.

The overarching principle is that interfaces should prioritize user convenience over implementer convenience.

????????-?????????????? ??

In summary, interface design in software development spans various levels of abstraction and plays a pivotal role in user satisfaction and error reduction.

Effective interfaces are user-centric, making correct usage natural while discouraging incorrect interactions through proactive design and iterative improvements.

???????????????????????? ???????? ?????????????????????? ???? ?????? ???????????????? ?????? ???? ?????????????????? ????????????.

#programming #programmer #interfaceDesign #userCentric #software




? SCRUM: Two Ingredients for Self-Management (No Recipe Possible Though) by Marc Kaufmann

Scrum uses self-managed teams, agile and adaptable in complex environments.

They leverage the team's collective potential for faster, creative problem-solving.

Here, I'll discuss implementing self-management for high-performing teams.

What is self-management?

Peter Drucker, in 'Management Challenges for the 21st Century,' ??:

“?????????????????? ?????????????? ??????? ???? ???????????? ???????????????????. ??????? ??????? ???? ??????? ????????????????”

--emphasizes that knowledge workers must manage themselves and have autonomy, aligning with Agile principles where teams self-manage tasks and decisions.

Unlike manager-led teams, self-managing teams autonomously determine who does what, when, and how.

Self-management can't be forced; it arises from engaging goals and clear boundaries.

Manipulating these factors shapes the degree and direction of self-management, providing guidance and defining the solution space for the team.

Two curcial ingredients for self-management:

1?? ???????????????????? #1: ???????? ?? ???????? ???????? ???

A good goal motivates and provides context, aiding planning and decision-making.

In Scrum, the Product Goal defines the 'why' for development, while Sprint Goals set short-term objectives.

These goals are concrete, measurable, and visible on the Scrum board, helping the team stay focused and make progress.

2?? ???????????????????? #2: ???????????????????? ??

Teams need clear boundaries for effective self-management.

Supportive boundaries strike a balance between guidance and autonomy, fostering trust and collaboration.

Scrum provides a balanced set of rules:

However external constraints like budget and organizational limitations can hinder self-management.

?? Scrum Events and Artifacts provide transparency and rapid feedback for result inspection and adaptation.

?? Scrum roles clarify responsibilities: Product Owner (what to do), Developers (how to do it), and Scrum Master (framework).

? Timeboxing maintains focus, synchronization, and stakeholder alignment.

?? The Definition of Done ensures transparency and trust in release readiness.

?? Scrum values (focus, respect, openness, commitment, and courage) build a foundation of trust for collaboration.

As Scrum Masters, we work on modifying these boundaries to empower teams.

???????? ???? ?????? ???????????????????? ??

Begin by identifying ?? team boundaries for delivering the Increment and their impact.

Explore ways to make them more supportive, like enhancing transparency and speeding up decision-making.

Use visualization tools and involve the team in proposing small, measurable steps and finding allies.

Make the plan and expected benefits visible to management ????, then collaborate on experiments to address the most limiting boundaries and measure the results.

????????????????????

Scrum encourages self-managing teams, emphasizing the importance of setting good goals and supportive boundaries.

Scrum Masters, coaches, or managers, play a role in helping teams achieve autonomy.




?? JOKE: git push origin --delete master

git push origin --delete master

A tiny coder remains unfazed when a ghost playfully utters "boo" twice. Even when the ghost adds a spine-tingling "booooo" for the third time, the little coder remains unperturbed. However, when the ghost suddenly utters the phrase "git push origin --delete master", the little coder loses his composure and lets out a terrified scream.

要查看或添加评论,请登录

Vincent Vauban的更多文章

  • ?? Broken Function Level Authorization – API5:2023 ??

    ?? Broken Function Level Authorization – API5:2023 ??

    I'm kicking off a series of articles on API Security ?? to help us—developers ????????—better understand and implement…

  • [VV112] The Java 21 Newsletter

    [VV112] The Java 21 Newsletter

    ????2??1?? Dear followers, let's prepare for Java 21 certification together! 1?? How would you answer this question:…

  • FR Les mots sans les maux. ???

    FR Les mots sans les maux. ???

    FR Hier, j’ai eu la chance d’assister à un atelier sur la Communication Non Violente (CNV) avec les superbes people de…

  • ?? Unrestricted Resource Consumption – API4:2023 ??

    ?? Unrestricted Resource Consumption – API4:2023 ??

    I'm kicking off a series of articles on API Security ?? to help us—developers ????????—better understand and implement…

  • ?? Broken Object Property Level Authorization – API3:2023 ??

    ?? Broken Object Property Level Authorization – API3:2023 ??

    I'm kicking off a series of articles on API Security ?? to help us—developers ????????—better understand and implement…

  • [VV111] The Java 21 Newsletter

    [VV111] The Java 21 Newsletter

    ????2??1?? Dear followers, let's prepare for Java 21 certification together! 1?? How would you answer this question:…

    18 条评论
  • ?? Broken Authentication – API2:2023 ??

    ?? Broken Authentication – API2:2023 ??

    I'm kicking off a series of articles on API Security ?? to help us—developers ????????—better understand and implement…

  • ?? BOLA – The #1 API Security Threat (API1:2023)

    ?? BOLA – The #1 API Security Threat (API1:2023)

    I'm kicking off a series of articles on API Security ?? to help us—developers ??????????—better understand and…

  • [VV110] The Java 21 Newsletter

    [VV110] The Java 21 Newsletter

    ????2??1?? Dear followers, let's prepare for Java 21 certification together! 1?? How would you answer this question:…

  • ?2??4?? Java 24 features with Thiago

    ?2??4?? Java 24 features with Thiago

    (Thanks Thiago Gonzaga ) Here are some insights based on Thiago X content. Java 24: JEP 491 Boosts Virtual Threads! ??…

社区洞察

其他会员也浏览了