Need a pretty method

Need a pretty method

Post by fernho » Mon, 25 Feb 2008 03:16:30


How do I make my count() method prettier?
TIA fh

public class ObjectCounter {

Object a;
Object b;

public ObjectCounter() {
Object a = null;
Object b = null;
}

public int count() {
if(a == null && b == null)
return 0;
else if(a != null && b !== null)
return 2;
else
return 1;
}

public Object getObjectA() {
return a;
}

public Object getObjectB() {
return b;
}

public void setObjectA(Object a) {
this.a = a;
}

public void setObjectB(Object b) {
this.b = b;
}
}
 
 
 

Need a pretty method

Post by Lew » Mon, 25 Feb 2008 03:21:46


Depends on what you find "pretty". You can certainly avoid testing each
variable twice, though.


public int count()
{
return (a == null? 0 : 1) + (b == null? 0 : 1);
}

--
Lew

 
 
 

Need a pretty method

Post by Patricia S » Mon, 25 Feb 2008 03:26:34


public int count(){
int result = 0;
if(a != null){
result++;
}
if(b != null){
result++;
}
return result;
}

also avoids testing twice. I find it a bit more readable, and it is
obvious how to extend it to deal with more references, for example an array.

Patricia
 
 
 

Need a pretty method

Post by fernho » Mon, 25 Feb 2008 03:27:59


> > else if(a != null && b !==>n>ll)
> > >e>urn 2;
>>>>else
> > gt;gt;ret>rn>1;
> > }
>
> pub>ic i>t count()
> {
> return (a == null? 0 : 1) + (b >= >ull?>0 : 1);
>
> }
>
Simple a> 1+1 :)
thanks
 
 
 

Need a pretty method

Post by fernho » Mon, 25 Feb 2008 03:35:12


> >> else if(a != null && b !==>n>>l)
> >> >e>>rn 2;
> >>>> else
> >> gt;gt;> retu>n >;> > >> }
>
> > pub>i> int>c>unt()
> > {
> > eturn (a == null? 0 : 1) + (b => >ull?>0 > 1);
> > }
>
> publ>c int count(){
> >int result = 0;
> > f(a != null)>
> > esult++;
> > > f(b != n>ll){
> > gt;
> > gt;eturn result;
>
> }
>
> also avoids testing twice. I find it a bit>more readable, and it is
> obvious how to extend it to deal with more referenc>s, for example an array.
>
Simple as result + 1 :)
yep,cou>d need to extend
thanks
 
 
 

Need a pretty method

Post by Daniel Pit » Tue, 26 Feb 2008 03:21:21


public class ObjectCounter {
Map<String, Object> obj = new HashMap<String, Object>();

public int count() {
return obj.size();
}

// ...
}


--
Daniel Pitts' Tech Blog: < http://www.yqcomputer.com/ ;