두 개의 프래그먼트에 중복된 조금 다른 함수가 있다.
private fun showCitiesPopup(anchorView: View) {
val cities = cityList.map { it.name }.toList()
val popupBinding = PopupListBinding.inflate(layoutInflater, null, false).also {
it.cityList.adapter =
ArrayAdapter(requireContext(), android.R.layout.simple_list_item_1, cities)
}
PopupWindow(popupBinding.root, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true).apply {
setBackgroundDrawable(getDrawable(requireContext(), R.drawable.rectangle_background))
elevation = 10f
showAsDropDown(anchorView)
popupBinding.cityList.setOnItemClickListener { _, _, position, _ ->
val selectedCity = cities[position]
viewModel.setRegion(selectedCity)
fetchWeatherData()
dismiss()
}
}
}
// private fun fetchWeatherData(city: String = "서울특별시") {
// viewModel.getWeather(currentDate, city)
// }
위와같은 함수가 있고 다른 하나의 프래그먼트에서는 주석 처리된 부분이 활성화 되어 있다.
중복되는 부분이 너무 많기 때문에
처음에는 별도의 파일에 주석을 제외한 함수를 구현한 뒤 오버로드로 기능을 추가하려야였다.

하지만 fetchWeatherData 라는 함수를 this.를 이용해 불러오지 못하는 문제가 발생했다.

private 때문에 다른 클래스에서 불러내지 못한다고 판단하고 private를 제거하거나 public을 붙였지만 해결되지 않았다.
fun Fragment.showCitiesPopup(anchorView: View, viewModel: WeatherViewModel, fetchWeatherDataCallback: () -> Unit)
함수를 별도의 파일로 분리한 뒤 Fragment 클래스에 확장 함수를 추가한다. fetchWeatherData는 함수의 인자로 받는다.
popupBinding.cityList.setOnItemClickListener { _, _, position, _ ->
val selectedCity = cities[position]
viewModel.setRegion(selectedCity)
fetchWeatherDataCallback()
dismiss()
}
인자로 받은 fetchWeatherData함수를 콜백함수로 넣는다.
모든 프래그먼트에서 showCitiesPopup라는 함수가 존재하며, 인자로 받을 fetchWeatherData 함수는 각각의 프래그먼트 파일의 상세 구현에 따라서 만들면 된다.
중복을 얼마나 없앨 수 있느냐를 잘 생각해야한다.
처음에는 다른 프래그먼트에 같은 함수 showCitiesPopup가 존재하며, 함수 내에서 이름이 같은 다른 함수fetchWeatherData를 부르기 때문에 별도의 파일로 확장함수를 구현하면 쉽게 해결될 것이라고 생각하였다.
if문을 이용해서 fetchWeatherData 참조를 시도했다. 하지만 확장함수 fun Fragment.showCitiesPopup는 Fragment 클래스를 참조하기 때문에 각각의 클래스에 구현된 fetchWeatherData를 가져올 수 없었다. 결국 showCitiesPopup에서 함수를 인자로 받은 뒤 각각 프래그먼트의 onViewCreated 메서드에서 불러오는 것으로 불러왔다.
내가 없앨 수 있는 중복은 showCitiesPopup라는 함수까지였고, fetchWeatherData는 이름까지만 공통되게 만든 뒤 각각의 프래그먼트에 적절하게 구현하는 수밖에 없었다.