2017-06-02 186 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

相關問題