Table of Contents
回复内容:
Home Backend Development PHP Tutorial 如何改进这段代码

如何改进这段代码

Jun 06, 2016 pm 08:34 PM
java php Refactor

如下伪代码,
AService do2对P进行了操作,然后碰到的问题是PService里对P进行操作,如果调用了AService do2那么
由于不是对P最新的引用,save时会把AService do2的修改覆盖掉。

//Update 2015年05月22日17:24:28
@Ke_Wu 这不应该是逻辑问题,事实上,我作为后来的调用者没必要也不可能知道AService::do2里的具体实现,但现在碰到问题了,那么就是设计的问题了

<code>class AService
{
    function do2(pid)
    {
        ...

        p = P.getById(pid);

        p.s = 'zz';

        p.save();

        ...
    }
}

class PService
{
    function do1(pid)
    {
        ...

        p = P.getById(pid);

        p.s = 'yy';

        AService.do2(pid);

        ...
        p.a = 'a';p.b = 'b';
        ...

        p.save();//p.s 仍旧是yy, zz被yy覆盖

        ...
    }
}

class CService
{
    function do4(cid)
    {
        ...
        c = C.getById(cid);
        pid = c.pid;
        AService.do2(pid);

        ...
    }
}

</code>
Copy after login
Copy after login

回复内容:

如下伪代码,
AService do2对P进行了操作,然后碰到的问题是PService里对P进行操作,如果调用了AService do2那么
由于不是对P最新的引用,save时会把AService do2的修改覆盖掉。

//Update 2015年05月22日17:24:28
@Ke_Wu 这不应该是逻辑问题,事实上,我作为后来的调用者没必要也不可能知道AService::do2里的具体实现,但现在碰到问题了,那么就是设计的问题了

<code>class AService
{
    function do2(pid)
    {
        ...

        p = P.getById(pid);

        p.s = 'zz';

        p.save();

        ...
    }
}

class PService
{
    function do1(pid)
    {
        ...

        p = P.getById(pid);

        p.s = 'yy';

        AService.do2(pid);

        ...
        p.a = 'a';p.b = 'b';
        ...

        p.save();//p.s 仍旧是yy, zz被yy覆盖

        ...
    }
}

class CService
{
    function do4(cid)
    {
        ...
        c = C.getById(cid);
        pid = c.pid;
        AService.do2(pid);

        ...
    }
}

</code>
Copy after login
Copy after login

简化下来其实问题就是:

<code>php</code><code>p1 = P.getById(pid);
p1.s = 'yy';
...
    p2 = P.getById(pid);
    p2.s = 'zz';
    p2.save();
...
p1.save();
</code>
Copy after login

保存了p2的修改(可能是存到数据库),并不意味着内存里的p1随之更新,除非你重新get一遍p1。
重构的目的是用来改善正确工作代码的风格和设计。
这段代码的问题是逻辑错误,对它而言谈重构还为时过早。

你的问题的本质,是两个“主语”(只是在你的案例中恰好都是service而已)的各自一个“行为”(do1 和 do2)含有了完全相同的一个“行动效果”(修改p.s的值)。
冲突不在于service,而在于行动效果冗余。
试想一下,换一个案例,其中只有一个主语,两个行为(do1 和 do2)都是它的,那么问题也是等价的。
两个行为有重叠的行动效果,实在太常见的了。
关键在于,你怎样界定,哪种重叠是满足需求的?哪种是错误、不合理的?

举一个满足需求的例子:
需求是:p是一个鼠标悬停的tips(界面组件)。先根据鼠标坐标,赋值p.top为一个值。随后,计算tips是否超出了窗口边缘。如果是,则计算tips的top的最大值(因为窗口大小可能会被改变,所以需要计算),然后赋值p.top为该最大值。p.left同理。
这是我做网页前端开发时遇到过的需求。

你的解决办法,大概可以解决你的那一个具体案例,但换成别的情况可能就又不对症了。
在我看来,关键在于,一个行为的源头(往往是事件)所导致一连串行动效果,其中要避免出现重叠;除非需求要求必要的重叠。
这“一连串”的“串法”,是设计上要想清楚的。你已经在朝这个方向努力了,只是关注点稍有偏离。
至于串的过程中的对象(主语/宾语)是不是service、是何种service,倒是没有关系。

我的解决办法如下,有什么缺点请指教:

Service应该分为2种:1,名词Service; 2, 行为Service
如:UserService 与 RegisterService

对于【名词Service】其里面每个method都必须返回相应的对象,如UserService下的upgrade(uid)就必须返回被升级后的user对象。

对于【行为Service】只对外暴露出一个execute(data),excute(data)必须返回行为成功与否的状态以及被施加这个行为的对象,如RegisterService下的excute(data)就必须返回注册成功与否,以及如果成功了它影响的对象。

通常我们约定对外只调用【行为Service】,再在【行为Service】里调用多个【名词Service】和其他【行为Service】,如在RegisterService::execute(data)里调用UserService::create(), UserService::markNewbee(uid),SendEmailService::execut()等;
【名词Service】中不允许调用【行为Service】。

所有Service的每个method的入参都可以是id或者对象实例,如upgrade()可以接受uid也可以接受user作为入参。

回到我的提问,可以这么写

<code>class AService
{
    function get(aid_or_object)
    {
        if (aid_or_object instanceOf A) {
            return aid_or_object;
        }
        return A.getById(aid);
    }
}

class PService
{
    function get(pid_or_object)
    {
        if (pid_or_object instanceOf P) {
            return pid_or_object;
        }
        return P.getById(pid);
    }
}


class Do2Service
{
    function execute(aid_or_object, pid_or_object = null)
    {
        a = AService.get(aid_or_object);
        if (pid_or_object instanceOf P) {
            p = pid_or_object
        } else {
            p = PService.get(a.pid);
        }
        p.s = 'zz';
        p.save();
        a.save();
        return [:success, a, p];
    }
}

class Do3Service
{
    function execute(pid_or_object)
    {
        p = PService.get(pid_or_object);
        p.s = 'cc';
        p.save();
        return [:success, p];
    }
}

class Do1Service
{
    function execute(pid_or_object)
    {
        p = PService.get(pid_or_object);
        p.s = 'yy' if condition1        
        result, a, p = Do2Servce.execute(p.aid, p) if condition2
        result, p = Do3Servce.execute(p) if condition3

        p.a = 'a';
        p.b = 'b';

        p.save()

        return [:success, p, a];
    }
}
</code>
Copy after login

想要解决什么问题?

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

See all articles