Лучший способ написать простой логический метод с хорошим синтаксисом C # - PullRequest
2 голосов
/ 23 февраля 2011

Привет всем, у меня, кажется, везде есть такие методы.

Метод ниже хочет выполнить следующие простые задачи:

  1. Открыть соединение с БД (объект IntLMPDB)
  2. Считать простую запись из небольшой таблицы БД (таблица БД снабжена строками, потому что каждая строка - это имя метода, поэтому я хочу, чтобы в таблице была только одна строка), остальная часть строкиэто серия отметок времени, которые сообщают мне, когда что-то случилось.
  3. Если вы не можете найти запись, верните исключение, потому что ничего нельзя сделать.
  4. Если вы найдете записьпосмотрите на второе свидание, если оно просто отсутствует, затем установите значение true, потому что это первый запуск.
  5. Или, наконец, перейти к мясу, если первая дата больше, чем вторая, для которой установлено значение True, поскольку она обновлена ​​и пора запускать.Иначе, если нет, установите значение «Ложь», потому что обновления пока нет.

Итак, вот код ... Я пытаюсь сделать это, сводя это к лучшему и быстрому способу выполнения этих проверок.,Меня не волнуют проблемы с подключением к БД или что-то в этом роде.

    private static bool isLastIntervalNewerThanDB(string muiMethod)
    {
       using (var db = new IntLMPDB())
        {
            // Try to load a matching record.
            LastIntervalUpdated liRec = db.LastIntervalUpdateds.FirstOrDefault(rec => rec.method == muiMethod);
            // If it could not be loaded, exit because there's no way to determine if we should run.
             if (liRec == null) { throw new Exception(string.Format("Could NOT find LastIntervalUpdated record for muiMethod: {0}", muiMethod)); }
            else
            {
                // we have a valid interval record, so lets check that it has been updated since the last webPostTime.
                // put another way, there are three datetime values in the LastIntervalUpdated table. First is the
                // interval itself, second is the retrievalTime and third is the webPostTime. Whenever the MUI is 
                // checked for a new interval if one is found then the code updates the retrievalTime to the current
                // instant in time. This tells us what the last interval this application found on its last run was.
                // The thrid value is the webPostTime, this time instant is only updated by this very method we're in
                // right here. We can use this logic: if the retrievalTime is greater than the webPostTime then there's
                // a newer interval that we haven't yet processed and inserted into the databse. So we should run the
                // method below and update ALL of the syncable values into the databse. Then we'll set the dbPostTime to 
                // the current instance. As it goes, if this program then runs again before the interval is updated
                // then the dbPostTime will be greater than the retrieval time and we'll know to do nothig. Simple Right? :)

                // or check here includes a NULL check on dbPostTime because it's possible that dbPostTime is NULL,
                // in the example of the first time the system runs. It might have run a LastUpdate sync and not yet
                // done this method, so dbPostTime would be NULL. None of the other columns are allowed to be null.
                if (liRec.dbPostTime_EST == null || liRec.retrievalTime_EST > liRec.dbPostTime_EST)
                { return true; }
                else { return false; }
            }
       }
    }

Ответы [ 4 ]

10 голосов
/ 23 февраля 2011

Я думаю, что логика в порядке. Я бы посоветовал вам сделать что-то подобное для улучшения читабельности *:

private static bool isLastIntervalNewerThanDB(string muiMethod)
{
   using (var db = new IntLMPDB())
    {
        LastIntervalUpdated liRec 
            = db.LastIntervalUpdateds
                    .FirstOrDefault(rec => rec.method == muiMethod);

        if (liRec == null) 
        { 
            throw new Exception(
                string.Format("Could NOT find LastIntervalUpdated record for muiMethod: {0}", muiMethod)); 
        }

        return liRec.dbPostTime_EST == null 
            || liRec.retrievalTime_EST > liRec.dbPostTime_EST;        
   }
}

* Хотя удобочитаемость субъективна, я бы сказал, что else после if (liRec == null) только добавляет ненужное вложение, и окончательное условное выражение может быть объединено в одно выражение. Кроме того, никогда не стоит недооценивать хорошо размещенную новую строку в длинном выражении - это может сделать всю разницу между читаемым и нечитаемым кодом.

2 голосов
/ 23 февраля 2011
private static bool isLastIntervalNewerThanDB(string muiMethod)
    {
       using (var db = new IntLMPDB())
        {
            // Try to load a matching record.
            LastIntervalUpdated liRec = db.LastIntervalUpdateds.FirstOrDefault(rec => rec.method == muiMethod);
            // If it could not be loaded, exit because there's no way to determine if we should run.
             if (liRec == null) { 
                     throw new Exception(string.Format("Could NOT find LastIntervalUpdated record for muiMethod: {0}", muiMethod)); 
             }

                // we have a valid interval record, so lets check that it has been updated since the last webPostTime.
                // put another way, there are three datetime values in the LastIntervalUpdated table. First is the
                // interval itself, second is the retrievalTime and third is the webPostTime. Whenever the MUI is 
                // checked for a new interval if one is found then the code updates the retrievalTime to the current
                // instant in time. This tells us what the last interval this application found on its last run was.
                // The thrid value is the webPostTime, this time instant is only updated by this very method we're in
                // right here. We can use this logic: if the retrievalTime is greater than the webPostTime then there's
                // a newer interval that we haven't yet processed and inserted into the databse. So we should run the
                // method below and update ALL of the syncable values into the databse. Then we'll set the dbPostTime to 
                // the current instance. As it goes, if this program then runs again before the interval is updated
                // then the dbPostTime will be greater than the retrieval time and we'll know to do nothig. Simple Right? :)

                // or check here includes a NULL check on dbPostTime because it's possible that dbPostTime is NULL,
                // in the example of the first time the system runs. It might have run a LastUpdate sync and not yet
                // done this method, so dbPostTime would be NULL. None of the other columns are allowed to be null.

               return liRec.dbPostTime_EST == null 
                      || liRec.retrievalTime_EST > liRec.dbPostTime_EST;     

       }
    }
0 голосов
/ 23 февраля 2011

Я бы переместил логическую логику в класс LastIntervalUpdated:

public class LastIntervalUpdated
{
    public bool IsLastIntervalNewer
    {
        get
        {
            return this.dbPostTime_EST == null || this.retrievalTime_EST > this.dbPostTime_EST
        }
    }
    //other properties...
}

Затем вы можете поместить комментарий ближе к определению.Это также позволяет упростить запрос до:

private static bool isLastIntervalNewerThanDB(string muiMethod)
{
    using (var db = new IntLMPDB())
    {
        LastIntervalUpdated liRec = db.LastIntervalUpdateds.FirstOrDefault(rec => rec.method == muiMethod);
        if(liRec == null) throw new Exception(string.Format("Could NOT find LastIntervalUpdated record for muiMethod: {0}", muiMethod))
        return liRec.IsLastIntervalNewer;
    }
}

Я бы также рассмотрел создание типа исключения для неудачных поисков, таких как ObjectNotFoundException, а не бросок Exception напрямую.

0 голосов
/ 23 февраля 2011

Оставьте первое, если избавитесь от первого, и сведите последнее в одну строку, если / еще

if (liRec == null) { throw new Exception(string.Format("Could NOT find LastIntervalUpdated record for muiMethod: {0}", muiMethod)); }

liRec.dbPostTime_EST == null || liRec.retrievalTime_EST > liRec.dbPostTime_EST ? return true : return false
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...