Excessive verification of zeros in MVC representations

This is a matter of style and design, not syntax.

I have domain models that have several (due to the lack of a better term) navigation properties. Therefore, in my strongly typed parts view Foo, which has a type property Bar, I could do the following:

<%: Foo.Bar.Name %>

However, sometimes Bar is Null, so I get something like:

<%: Foo.Bar == null ? String.Empty : Foo.Bar.Name %>

In other cases, since the convenience of navigational properties, I could make even more chaining. The drawback, however, is the introduction of a more null check in my view.

Alternatively, I could do all the null checking in the ViewModel so that I go through something β€œclean” in the view. I am looking for some common sense ideas or recommendations to avoid over-checking the null in my views.

PS I am using ASP.NET MVC, but I think this question may be related to other MVC frameworks.

+3
source share
6 answers

You yourself answered:

Alternatively, I could do all the null checking in the ViewModel so that I pass something β€œclean” to the view.

What is it, use ViewModel.

+3
source
+1

, null .

, , . , null " ", .

, .

0

, .

0

. , .

public class Foo
{
    private Bar _bar;

    public Bar Bar
    {
        get
        {
            if (_bar == null)
            {
                _bar = new Bar();
            }
            return _bar;
        }
    }
}

public class Bar
{
    public string Name { get; set; }
}
0

, Foo , Bar NULL. , guard \ Bar.

public class Foo{

        public BarClass _bar;

        public BarClass Bar{
            get{return _bar; }
            set{
                if(value == null)
                   throw new ArgumentNullException();
                _bar = value; } 
            } 

           public Foo(BarClass bar){
              if(bar == null) throw new ArgumentNullException();
              _bar = bar;
          } 
        }

-, - . . Null . , Bar NullBar.

public class Foo{

    public BarClass _bar;

    public BarClass Bar{
        get{return _bar ?? new NullBar(); }
        set{ _bar = value ?? new NullBar(); } 
    } 

       public Foo(){
          Bar = new NullBar(); // initialization
       } 
    }

Bar null.

0

Source: https://habr.com/ru/post/1765188/


All Articles