2017-06-02 180 views
-5

我使用spring-boot框架开发了一个应用程序java。在我的课程中,在保存用户之前,我需要检查他的电子邮件是否存在于1000封电子邮件列表中,如果检查可以,我必须设置一个布尔值,表明用户是loyel用户。检查电子邮件是否存在的最佳方法

我的问题是什么是检查,如果用户的电子邮件在该列表中存在或不短的时间内最好的实现:

1- Read a file that contain the 1000 emails each time when a user will be created. What is the best way to do that without read every time the file ? 
using a singleton.... 
2- Create an email ArrayList and parse it each time ??? 
3. create a database and make a request to check each time if the email exists 

你有什么建议吗?

最好的问候

+0

当你说'最好的方式'时,你是什么意思?性能最好? Mainentantability?你的教师学位?较少的代码? – ADS

+0

我的意思是性能和速度 – Victor

+0

请澄清。什么速度?你打算使用clasters?你确定会有1000封电子邮件,而且从来没有1,001封吗? – ADS

回答

0

这取决于。不希望你第一次找到合适的解决方案。把它写下来然后去。如果您遇到了一些问题的退货和重新编写。这是编程中的惯例

你现在可以做的主要事情是开发一种不会随时变化的契约(或接口)。最简单的合约将是Collection<String> getCorrectEmails()。可能Iterable<String> getCorrectEmails()会更好,因为你可以用流/数据库/微服务实现它/不管


修订 既然你有电子邮件的只有1000这可能是不改变,你可以硬编码它们。为了避免源代码膨胀,我建议在另一个文件中介绍的支架:

class ValidEmailHolder { 
    // note method is non-static. It WILL help you in the future 
    /* use Collection instead List isn't necessary but a good practice 
    to return more broad interface when you assume it could be changed in next 10 years */ 
    public Collection<String> getEmails() { 
     return EMAILS; 
    } 

    private static final List<String> EMAILS = Arrays.asList(
     "[email protected]", 
     "[email protected]", 
    // many lines here 
     "[email protected]" 
    ); 
} 

,然后用它在你的类

public Collection<String> getValidEmails() { 
    ValidEmailHolder.getEmails(); 
} 

注意到我只是叫ValidEmailHolder.getEmails()内法。这是一个Bridge pattern,这里它会帮助你,如果你想改变行为。很可能你会想要在外部文件中引入电子邮件列表,可能是在数据库中,甚至是在系统属性中。然后,您可以写下ValidEmailFileHolder,然后只需更改呼叫。你也可以添加这样的逻辑

Collection<String> result = ValidEmailDbHolder.getEmails(); 
if (result == null || result.isEmpty()) { 
    result = ValidEmailHolder.getEmails(); 
} 
return result; 

但可能你不需要这个。你可以轻松做到这一点

+0

谢谢@ADS但是,我将在checkIfEmailExist内部实现的最棘手的解决方案。 – Victor

+0

最为棘手的解决方案是写下'getCorrectEmails(){// TODO}'。 – ADS

+0

除非你知道经常可以改变它,谁会改变你不知道你需要什么。没关系,因为在运行原型一周后你会知道很多事情。你** definetely将重写这种方法**所以现在不在乎它 – ADS

相关问题